Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(databricks): dump (#12424)
Azusain7d30e3c5406f
diff --git a/backend/plugin/db/databricks/databricks.go b/backend/plugin/db/databricks/databricks.goindex 0c1413dc18..c14bc5b701 100644--- a/backend/plugin/db/databricks/databricks.go+++ b/backend/plugin/db/databricks/databricks.go@@ -180,6 +180,11 @@ func toStrColInfo(colInfo []dbsql.ColumnInfo) ([]string, []string) {func toV1pbRowVal(colType dbsql.ColumnInfoTypeName, val string) (*v1pb.RowValue, error) {rowVal := v1pb.RowValue{}+ if val == "" && colType != dbsql.ColumnInfoTypeNameString {+ rowVal.Kind = &v1pb.RowValue_NullValue{}+ return &rowVal, nil+ }+switch colType {case dbsql.ColumnInfoTypeNameBoolean:boolVal, err := strconv.ParseBool(val)diff --git a/backend/plugin/db/databricks/dump.go b/backend/plugin/db/databricks/dump.goindex 728448845e..8eb12055a8 100644--- a/backend/plugin/db/databricks/dump.go+++ b/backend/plugin/db/databricks/dump.go@@ -2,9 +2,200 @@ package databricksimport ("context"+ "errors"+ "fmt""io"+ "regexp"+ "strings"++ "github.com/databricks/databricks-sdk-go/service/catalog"++ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++const (+ schemaStmtFmt = "" ++ "--\n" ++ "-- %s structure for %s\n" ++ "--\n" ++ "%s;\n")-func (*Driver) Dump(_ context.Context, _ io.Writer, _ bool) (string, error) {+func (d *Driver) Dump(ctx context.Context, writer io.Writer, _ bool) (string, error) {+ catalogMap, err := d.listCatologTables(ctx, "")+ if err != nil {+ return "", err+ }++ for catalogName, schemaMap := range catalogMap {+ if _, err := writer.Write([]byte(fmt.Sprintf("CREATE CATALOG %s\n", catalogName))); err != nil {+ return "", err+ }++ for schemaName, tableList := range schemaMap {+ if _, err := writer.Write([]byte(fmt.Sprintf("CREATE SCHEMA `%s`.`%s`\n", catalogName, schemaName))); err != nil {+ return "", err+ }++ viewDDL := strings.Builder{}+ mtViewDDL := strings.Builder{}+ extTblDDL := strings.Builder{}+ mngTblDDL := strings.Builder{}+ for _, tblUnion := range tableList {+ qualifiedName, err := getQualifiedTblName(catalogName, schemaName, tblUnion.name)+ if err != nil {+ return "", err+ }++ switch tblUnion.typeName {+ case catalog.TableTypeView:+ ddl, err := d.showCreateTable(ctx, qualifiedName)+ if err != nil {+ return "", err+ }+ formatDDL := fmt.Sprintf(schemaStmtFmt, "VIEW", qualifiedName, ddl)+ if _, err := viewDDL.WriteString(formatDDL); err != nil {+ return "", err+ }+ case catalog.TableTypeMaterializedView:+ tblAddInfo, err := d.descTbl(ctx, qualifiedName)+ if err != nil {+ return "", err+ }+ tblProperties, err := formatTblProperties(tblAddInfo)+ if err != nil {+ return "", err+ }+ formatDDL, err := genMaterializedViewDDL(qualifiedName, tblUnion.materialView, tblProperties)+ if err != nil {+ return "", err+ }+ if _, err := mtViewDDL.WriteString(formatDDL); err != nil {+ return "", err+ }+ case catalog.TableTypeExternal:+ ddl, err := d.showCreateTable(ctx, qualifiedName)+ if err != nil {+ return "", err+ }+ formatDDL := fmt.Sprintf(schemaStmtFmt, "EXTERNAL TABLE", qualifiedName, ddl)+ if _, err := extTblDDL.WriteString(formatDDL); err != nil {+ return "", err+ }+ case catalog.TableTypeManaged:+ ddl, err := d.showCreateTable(ctx, qualifiedName)+ if err != nil {+ return "", err+ }+ formatDDL := fmt.Sprintf(schemaStmtFmt, "MANAGED TABLE", qualifiedName, ddl)+ if _, err := mngTblDDL.WriteString(formatDDL); err != nil {+ return "", err+ }+ default:+ // we do not sync streaming table.+ continue+ }+ }+ if _, err := writer.Write([]byte(mngTblDDL.String())); err != nil {+ return "", err+ }+ if _, err := writer.Write([]byte(extTblDDL.String())); err != nil {+ return "", err+ }+ if _, err := writer.Write([]byte(viewDDL.String())); err != nil {+ return "", err+ }+ if _, err := writer.Write([]byte(mtViewDDL.String())); err != nil {+ return "", err+ }+ }+ }+return "", nil}++func (d *Driver) showCreateTable(ctx context.Context, qualifiedTblName string) (string, error) {+ rows, colInfo, err := d.execSingleSQLSync(ctx, fmt.Sprintf("SHOW CREATE TABLE %s", qualifiedTblName))+ if err != nil {+ return "", err+ }++ if len(rows) != 1 || len(colInfo) != 1 {+ return "", errors.New("invalid ddl format")+ }++ return rows[0][0], nil+}++func genMaterializedViewDDL(qualifiedName string, mtViewMeta *storepb.MaterializedViewMetadata, tblProperties string) (string, error) {+ builder := strings.Builder{}+ if _, err := builder.WriteString(""); err != nil {+ return "", err+ }++ if _, err := builder.WriteString(fmt.Sprintf("CREATE MATERIALIZED VIEW %s\n", qualifiedName)); err != nil {+ return "", err+ }++ if _, err := builder.WriteString(fmt.Sprintf("COMMENT %s\n", mtViewMeta.Comment)); err != nil {+ return "", err+ }++ if _, err := builder.WriteString(fmt.Sprintf("TBLPROPERTIES %s\n", tblProperties)); err != nil {+ return "", err+ }++ return builder.String(), nil+}++type tableAdditionalInfo struct {+ tblProps map[string]string+}++func (d *Driver) descTbl(ctx context.Context, tblName string) (*tableAdditionalInfo, error) {+ tblAddInfo := &tableAdditionalInfo{+ tblProps: make(map[string]string),+ }+ rows, _, err := d.execSingleSQLSync(ctx, fmt.Sprintf("DESC FORMATTED %s", tblName))+ if err != nil {+ return nil, err+ }++ for _, row := range rows {+ infoKey := row[0]+ infoVal := row[1]+ if infoKey == "Table Properties" {+ pattern := regexp.MustCompile("([a-zA-Z0-9-.]*)=([a-zA-Z0-9-.]*)")+ matches := pattern.FindAllStringSubmatch(infoVal, -1)+ if matches == nil {+ continue+ }+ for _, match := range matches {+ tblAddInfo.tblProps[match[1]] = match[2]+ }+ }+ }++ return tblAddInfo, nil+}++func formatTblProperties(tblAddInfo *tableAdditionalInfo) (string, error) {+ if tblAddInfo == nil || tblAddInfo.tblProps == nil {+ return "", errors.New("properties cannot be nil value")+ }++ builder := strings.Builder{}+ idx := 0+ for key, val := range tblAddInfo.tblProps {+ comma := ","+ if idx == len(tblAddInfo.tblProps)-1 {+ comma = ""+ }+ if _, err := builder.WriteString(fmt.Sprintf("%s = %s%s\n", key, val, comma)); err != nil {+ return "", err+ }+ idx+++ }++ return builder.String(), nil+}diff --git a/backend/plugin/db/databricks/sync.go b/backend/plugin/db/databricks/sync.goindex a1af51ef40..d225c216b9 100644--- a/backend/plugin/db/databricks/sync.go+++ b/backend/plugin/db/databricks/sync.go@@ -2,6 +2,7 @@ package databricksimport ("context"+ "fmt""strings""time"@@ -18,6 +19,7 @@ type tableUnion struct {view *storepb.ViewMetadatamaterialView *storepb.MaterializedViewMetadatatypeName catalog.TableType+ name string}type databricksSchemaMap = map[string][]*tableUnion@@ -31,7 +33,7 @@ func (d *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchemaMetad}// fetch table data from databricks.- catalogMap, err := d.listAllTables(ctx)+ catalogMap, err := d.listCatologTables(ctx, d.curCatalog)if err != nil {return nil, err}@@ -67,7 +69,7 @@ func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error)instanceMetadata.Version = splitVersion[0]// fetch table data from databricks.- catalogMap, err := d.listAllTables(ctx)+ catalogMap, err := d.listCatologTables(ctx, "")if err != nil {return nil, err}@@ -90,7 +92,8 @@ func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]*storepreturn nil, nil}-func (d *Driver) listAllTables(ctx context.Context) (databricksCatalogMap, error) {+// list all tables in the workspace when catalogName is set to "".+func (d *Driver) listCatologTables(ctx context.Context, targetCatalogName string) (databricksCatalogMap, error) {catalogMap := make(databricksCatalogMap)catalogsInfo, err := d.Client.Catalogs.ListAll(ctx)@@ -99,6 +102,9 @@ func (d *Driver) listAllTables(ctx context.Context) (databricksCatalogMap, error}for _, catalogInfo := range catalogsInfo {+ if targetCatalogName != "" && targetCatalogName != catalogInfo.Name {+ continue+ }schemasInfo, err := d.Client.Schemas.ListAll(ctx, catalog.ListSchemasRequest{CatalogName: catalogInfo.Name,})@@ -106,6 +112,20 @@ func (d *Driver) listAllTables(ctx context.Context) (databricksCatalogMap, errorreturn nil, err}for _, schemaInfo := range schemasInfo {+ // init map.+ scMap, ok := catalogMap[catalogInfo.Name]+ if !ok {+ catalogMap[catalogInfo.Name] = databricksSchemaMap{+ schemaInfo.Name: []*tableUnion{},+ }+ } else {+ _, ok := scMap[schemaInfo.Name]+ if !ok {+ scMap[schemaInfo.Name] = []*tableUnion{}+ }+ catalogMap[catalogInfo.Name] = scMap+ }+ // list tables in the schema.tablesInfo, err := d.Client.Tables.ListAll(ctx, catalog.ListTablesRequest{CatalogName: catalogInfo.Name,SchemaName: schemaInfo.Name,@@ -113,7 +133,9 @@ func (d *Driver) listAllTables(ctx context.Context) (databricksCatalogMap, errorif err != nil {return nil, err}- appendSchemaTables(catalogMap, tablesInfo)+ if err := appendSchemaTables(catalogMap, tablesInfo); err != nil {+ return nil, err+ }}}@@ -121,33 +143,34 @@ func (d *Driver) listAllTables(ctx context.Context) (databricksCatalogMap, error}// extract tables' metadata from 'tablesInfo' and store it in 'catalogMap'.-func appendSchemaTables(catalogMap databricksCatalogMap, tablesInfo []catalog.TableInfo) {+func appendSchemaTables(catalogMap databricksCatalogMap, tablesInfo []catalog.TableInfo) error {for _, tableInfo := range tablesInfo {table := tableUnion{typeName: tableInfo.TableType,+ name: tableInfo.Name,}switch tableInfo.TableType {case catalog.TableTypeView:table.view = &storepb.ViewMetadata{- Name: tableInfo.Name,+ Name: table.name,Definition: tableInfo.ViewDefinition,Comment: tableInfo.Comment,DependentColumns: convertToDependentColumns(tableInfo.SchemaName, tableInfo.Name, tableInfo.Columns),}case catalog.TableTypeMaterializedView:table.materialView = &storepb.MaterializedViewMetadata{- Name: tableInfo.Name,+ Name: table.name,Definition: tableInfo.ViewDefinition,Comment: tableInfo.Comment,}case catalog.TableTypeExternal:table.externalTable = &storepb.ExternalTableMetadata{- Name: tableInfo.Name,+ Name: table.name,}case catalog.TableTypeManaged:table.table = &storepb.TableMetadata{- Name: tableInfo.Name,+ Name: table.name,Columns: convertToColumnMetadata(tableInfo.Columns),Comment: tableInfo.Comment,}@@ -156,19 +179,15 @@ func appendSchemaTables(catalogMap databricksCatalogMap, tablesInfo []catalog.Tacontinue}- if schemaMap, ok := catalogMap[tableInfo.CatalogName]; !ok {- catalogMap[tableInfo.CatalogName] = databricksSchemaMap{- tableInfo.SchemaName: []*tableUnion{&table},- }+ // catalogMap[tableInfo.CatalogName] must not be nil.+ if tblList, ok := catalogMap[tableInfo.CatalogName][tableInfo.SchemaName]; ok {+ tblList = append(tblList, &table)+ catalogMap[tableInfo.CatalogName][tableInfo.SchemaName] = tblList} else {- if tableList, ok := schemaMap[tableInfo.SchemaName]; ok {- tableList = append(tableList, &table)- schemaMap[tableInfo.SchemaName] = tableList- } else {- schemaMap[tableInfo.SchemaName] = []*tableUnion{&table}- }+ return errors.New("table list not initialized")}}+ return nil}func convertToColumnMetadata(columnInfo []catalog.ColumnInfo) []*storepb.ColumnMetadata {@@ -222,3 +241,14 @@ func convertToStorepbSchemas(schemaMap databricksSchemaMap) []*storepb.SchemaMet}return schemas}++func getQualifiedTblName(catalogName, schemaName, tblName string) (string, error) {+ if tblName == "" || schemaName == "" {+ return "", errors.New("table name and schema name must be specified")+ }+ qualifiedName := fmt.Sprintf("`%s`.`%s`", schemaName, tblName)+ if catalogName != "" {+ qualifiedName = fmt.Sprintf("`%s`.%s", catalogName, qualifiedName)+ }+ return qualifiedName, nil+}