Skip to content

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

refactor: remove unused table/col/idx/extension API (#3921)

Danny Xued7fbbe87913
diff --git a/api/column.go b/api/column.go
deleted file mode 100644
index 0673234879..0000000000
--- a/api/column.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package api
-
-import (
- "encoding/json"
-)
-
-// Column is the API message for a table column.
-type Column struct {
- ID int `jsonapi:"primary,column" json:"id"`
-
- // Standard fields
- CreatorID int
- CreatedTs int64 `json:"createdTs"`
- UpdaterID int
- UpdatedTs int64 `json:"updatedTs"`
-
- // Related fields
- DatabaseID int `json:"databaseId"`
- TableID int `json:"tableId"`
-
- // Domain specific fields
- Name string `json:"name"`
- Position int `json:"position"`
- Default *string `json:"default"`
- Nullable bool `json:"nullable"`
- Type string `json:"type"`
- CharacterSet string `json:"characterSet"`
- Collation string `json:"collation"`
- Comment string `json:"comment"`
-}
-
-// ColumnCreate is the API message for creating a column.
-type ColumnCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
-
- // Related fields
- DatabaseID int
- TableID int
-
- // Domain specific fields
- Name string
- Position int
- Default *string
- Nullable bool
- Type string
- CharacterSet string
- Collation string
- Comment string
-}
-
-// ColumnFind is the API message for finding columns.
-type ColumnFind struct {
- ID *int
-
- // Related fields
- DatabaseID *int
- TableID *int
-
- // Domain specific fields
- Name *string
-}
-
-func (find *ColumnFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
-// ColumnPatch is the API message for patching a column.
-type ColumnPatch struct {
- ID int
-
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- UpdaterID int
-}
-
-// ColumnDelete is the API message for deleting a column.
-type ColumnDelete struct {
- ID int
-}
diff --git a/api/db_extension.go b/api/db_extension.go
deleted file mode 100644
index 353e5f7320..0000000000
--- a/api/db_extension.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package api
-
-import (
- "encoding/json"
-)
-
-// DBExtension is the API message for a database extension.
-type DBExtension struct {
- ID int `jsonapi:"primary,dbExtension"`
-
- // Standard fields
- CreatorID int
- Creator *Principal `jsonapi:"relation,creator"`
- CreatedTs int64 `jsonapi:"attr,createdTs"`
- UpdaterID int
- Updater *Principal `jsonapi:"relation,updater"`
- UpdatedTs int64 `jsonapi:"attr,updatedTs"`
-
- // Related fields
- DatabaseID int
- Database *Database `jsonapi:"relation,database"`
-
- // Domain specific fields
- Name string `jsonapi:"attr,name"`
- Version string `jsonapi:"attr,version"`
- Schema string `jsonapi:"attr,schema"`
- Description string `jsonapi:"attr,description"`
-}
-
-// DBExtensionCreate is the API message for creating a database extension.
-type DBExtensionCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
- CreatedTs int64
- UpdatedTs int64
-
- // Related fields
- DatabaseID int
-
- // Domain specific fields
- Name string
- Version string
- Schema string
- Description string
-}
-
-// DBExtensionFind is the API message for finding extensions.
-type DBExtensionFind struct {
- ID *int
-
- // Related fields
- DatabaseID *int
-
- // Domain specific fields
-}
-
-func (find *DBExtensionFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
-// DBExtensionDelete is the API message for deleting a database extension.
-type DBExtensionDelete struct {
- ID int
-}
diff --git a/api/table.go b/api/table.go
deleted file mode 100644
index fedd767d3a..0000000000
--- a/api/table.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package api
-
-import (
- "encoding/json"
-)
-
-// Table is the API message for a table.
-type Table struct {
- ID int `jsonapi:"primary,table"`
-
- // Standard fields
- CreatorID int
- Creator *Principal `jsonapi:"relation,creator"`
- CreatedTs int64 `jsonapi:"attr,createdTs"`
- UpdaterID int
- Updater *Principal `jsonapi:"relation,updater"`
- UpdatedTs int64 `jsonapi:"attr,updatedTs"`
-
- // Related fields
- DatabaseID int
- Database *Database `jsonapi:"relation,database"`
-
- // Domain specific fields
- Name string `jsonapi:"attr,name"`
- Type string `jsonapi:"attr,type"`
- Engine string `jsonapi:"attr,engine"`
- Collation string `jsonapi:"attr,collation"`
- RowCount int64 `jsonapi:"attr,rowCount"`
- DataSize int64 `jsonapi:"attr,dataSize"`
- IndexSize int64 `jsonapi:"attr,indexSize"`
- DataFree int64 `jsonapi:"attr,dataFree"`
- CreateOptions string `jsonapi:"attr,createOptions"`
- Comment string `jsonapi:"attr,comment"`
- ColumnList []*Column `jsonapi:"attr,columnList"`
- IndexList []*Index `jsonapi:"attr,indexList"`
-}
-
-// TableCreate is the API message for creating a table.
-type TableCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
- CreatedTs int64
- UpdatedTs int64
-
- // Related fields
- DatabaseID int
-
- // Domain specific fields
- Name string
- Type string
- Engine string
- Collation string
- RowCount int64
- DataSize int64
- IndexSize int64
- DataFree int64
- CreateOptions string
- Comment string
-}
-
-// TableFind is the API message for finding tables.
-type TableFind struct {
- ID *int
-
- // Related fields
- DatabaseID *int
-
- // Domain specific fields
- Name *string
-}
-
-func (find *TableFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
-// TablePatch is the API message for patching a table.
-type TablePatch struct {
- ID int
-
- // Standard fields
- UpdaterID int
-
- // Domain specific fields
- Type string
- Engine string
- Collation string
- RowCount int64
- DataSize int64
- IndexSize int64
- DataFree int64
- CreateOptions string
- Comment string
-}
-
-// TableDelete is the API message for deleting a table.
-type TableDelete struct {
- ID int
-}
diff --git a/api/table_index.go b/api/table_index.go
deleted file mode 100644
index 7327de5143..0000000000
--- a/api/table_index.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package api
-
-import (
- "encoding/json"
-)
-
-// Index is the API message for an index.
-type Index struct {
- ID int `jsonapi:"primary,index"`
-
- // Standard fields
- CreatorID int
- CreatedTs int64 `json:"createdTs"`
- UpdaterID int
- UpdatedTs int64 `json:"updatedTs"`
-
- // Related fields
- DatabaseID int
- TableID int
-
- // Domain specific fields
- Name string `json:"name"`
- Expression string `json:"expression"`
- Position int `json:"position"`
- Type string `json:"type"`
- Unique bool `json:"unique"`
- Primary bool `json:"primary"`
- Visible bool `json:"visible"`
- Comment string `json:"comment"`
-}
-
-// IndexCreate is the API message for creating an index.
-type IndexCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
-
- // Related fields
- DatabaseID int
- TableID int
-
- // Domain specific fields
- Name string
- Expression string
- Position int
- Type string
- Unique bool
- Primary bool
- Visible bool
- Comment string
-}
-
-// IndexFind is the API message for finding indices.
-type IndexFind struct {
- ID *int
-
- // Related fields
- DatabaseID *int
- TableID *int
-
- // Domain specific fields
- Name *string
- Expression *string
-}
-
-func (find *IndexFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
-// IndexDelete is the API message for deleting an index.
-type IndexDelete struct {
- ID int
-}
diff --git a/api/view.go b/api/view.go
deleted file mode 100644
index 38c40a1f78..0000000000
--- a/api/view.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package api
-
-import (
- "encoding/json"
-)
-
-// View is the API message for a view.
-type View struct {
- ID int `jsonapi:"primary,view"`
-
- // Standard fields
- CreatorID int
- Creator *Principal `jsonapi:"relation,creator"`
- CreatedTs int64 `jsonapi:"attr,createdTs"`
- UpdaterID int
- Updater *Principal `jsonapi:"relation,updater"`
- UpdatedTs int64 `jsonapi:"attr,updatedTs"`
-
- // Related fields
- DatabaseID int
- Database *Database `jsonapi:"relation,database"`
-
- // Domain specific fields
- Name string `jsonapi:"attr,name"`
- Definition string `jsonapi:"attr,definition"`
- Comment string `jsonapi:"attr,comment"`
-}
-
-// ViewCreate is the API message for creating a view.
-type ViewCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
- CreatedTs int64
- UpdatedTs int64
-
- // Related fields
- DatabaseID int
-
- // Domain specific fields
- Name string
- Definition string
- Comment string
-}
-
-// ViewFind is the API message for finding views.
-type ViewFind struct {
- ID *int
-
- // Related fields
- DatabaseID *int
-
- // Domain specific fields
- Name *string
-}
-
-func (find *ViewFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
-// ViewDelete is the API message for deleting a view.
-type ViewDelete struct {
- ID int
-}
diff --git a/server/database.go b/server/database.go
index a9170ceffd..ba5e540442 100644
--- a/server/database.go
+++ b/server/database.go
@@ -234,150 +234,6 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return nil
})
- g.GET("/database/:databaseID/table", func(c echo.Context) error {
- ctx := c.Request().Context()
- id, err := strconv.Atoi(c.Param("databaseID"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("databaseID"))).SetInternal(err)
- }
-
- tableFind := &api.TableFind{
- DatabaseID: &id,
- }
- tableList, err := s.store.FindTable(ctx, tableFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch table list for database id: %d", id)).SetInternal(err)
- }
-
- for _, table := range tableList {
- columnFind := &api.ColumnFind{
- DatabaseID: &id,
- TableID: &table.ID,
- }
- columnList, err := s.store.FindColumn(ctx, columnFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch column list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
- }
- table.ColumnList = columnList
-
- indexFind := &api.IndexFind{
- DatabaseID: &id,
- TableID: &table.ID,
- }
- indexList, err := s.store.FindIndex(ctx, indexFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch index list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
- }
- table.IndexList = indexList
- }
-
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, tableList); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal fetch table list response: %v", id)).SetInternal(err)
- }
- return nil
- })
-
- g.GET("/database/:databaseID/table/:tableName", func(c echo.Context) error {
- ctx := c.Request().Context()
- id, err := strconv.Atoi(c.Param("databaseID"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("databaseID"))).SetInternal(err)
- }
-
- database, err := s.store.GetDatabase(ctx, &api.DatabaseFind{ID: &id})
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database ID: %v", id)).SetInternal(err)
- }
- if database == nil {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database not found with ID %d", id))
- }
-
- tableName := c.Param("tableName")
- tableFind := &api.TableFind{
- DatabaseID: &id,
- Name: &tableName,
- }
- table, err := s.store.GetTable(ctx, tableFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch table for database id: %d, table name: %s", id, tableName)).SetInternal(err)
- }
- if table == nil {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("table %q not found from database %v", tableName, id)).SetInternal(err)
- }
- table.Database = database
-
- columnFind := &api.ColumnFind{
- DatabaseID: &id,
- TableID: &table.ID,
- }
- columnList, err := s.store.FindColumn(ctx, columnFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch column list for database id: %d, table name: %s", id, tableName)).SetInternal(err)
- }
- table.ColumnList = columnList
-
- indexFind := &api.IndexFind{
- DatabaseID: &id,
- TableID: &table.ID,
- }
- indexList, err := s.store.FindIndex(ctx, indexFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch index list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
- }
- table.IndexList = indexList
-
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, table); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal fetch table response: %v", id)).SetInternal(err)
- }
- return nil
- })
-
- g.GET("/database/:databaseID/view", func(c echo.Context) error {
- ctx := c.Request().Context()
- id, err := strconv.Atoi(c.Param("databaseID"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("databaseID"))).SetInternal(err)
- }
-
- viewFind := &api.ViewFind{
- DatabaseID: &id,
- }
- viewList, err := s.store.FindView(ctx, viewFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch view list for database ID: %d", id)).SetInternal(err)
- }
-
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, viewList); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal fetch view list response: %v", id)).SetInternal(err)
- }
- return nil
- })
-
- g.GET("/database/:databaseID/extension", func(c echo.Context) error {
- ctx := c.Request().Context()
- id, err := strconv.Atoi(c.Param("databaseID"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("databaseID"))).SetInternal(err)
- }
-
- dbExtensionFind := &api.DBExtensionFind{
- DatabaseID: &id,
- }
- dbExtensionList, err := s.store.FindDBExtension(ctx, dbExtensionFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch dbExtension list for database ID: %d", id)).SetInternal(err)
- }
-
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, dbExtensionList); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal fetch dbExtension list response: %v", id)).SetInternal(err)
- }
- return nil
- })
-
// When query metadata is present, we will return the schema metadata. Otherwise, we will return the raw dump.
g.GET("/database/:databaseID/schema", func(c echo.Context) error {
ctx := c.Request().Context()
diff --git a/store/column.go b/store/column.go
deleted file mode 100644
index 2d8c1b5c3d..0000000000
--- a/store/column.go
+++ /dev/null
@@ -1,235 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "strings"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/common"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-// FindColumn retrieves a list of columns based on find.
-func (s *Store) FindColumn(ctx context.Context, find *api.ColumnFind) ([]*api.Column, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findColumnImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- return list, nil
-}
-
-func generateColumnActions(oldColumnList []*api.Column, columnList []db.Column, databaseID, tableID int) ([]*api.ColumnDelete, []*api.ColumnCreate) {
- var columnCreateList []*api.ColumnCreate
- for _, column := range columnList {
- columnCreateList = append(columnCreateList, &api.ColumnCreate{
- CreatorID: api.SystemBotID,
- DatabaseID: databaseID,
- TableID: tableID,
- Name: column.Name,
- Position: column.Position,
- Default: column.Default,
- Nullable: column.Nullable,
- Type: column.Type,
- CharacterSet: column.CharacterSet,
- Collation: column.Collation,
- Comment: column.Comment,
- })
- }
- oldColumnMap := make(map[string]*api.Column)
- for _, c := range oldColumnList {
- oldColumnMap[c.Name] = c
- }
- newColumnMap := make(map[string]*api.ColumnCreate)
- for _, c := range columnCreateList {
- newColumnMap[c.Name] = c
- }
-
- var deletes []*api.ColumnDelete
- var creates []*api.ColumnCreate
- for _, oldValue := range oldColumnList {
- k := oldValue.Name
- newValue, ok := newColumnMap[k]
- if !ok {
- deletes = append(deletes, &api.ColumnDelete{ID: oldValue.ID})
- } else if ok && (oldValue.Position != newValue.Position || oldValue.Default != newValue.Default || oldValue.Nullable != newValue.Nullable || oldValue.Type != newValue.Type || oldValue.CharacterSet != newValue.CharacterSet || oldValue.Collation != newValue.Collation || oldValue.Comment != newValue.Comment) {
- deletes = append(deletes, &api.ColumnDelete{ID: oldValue.ID})
- creates = append(creates, newValue)
- }
- }
- for _, newValue := range columnCreateList {
- k := newValue.Name
- if _, ok := oldColumnMap[k]; !ok {
- creates = append(creates, newValue)
- }
- }
- return deletes, creates
-}
-
-// createColumnImpl creates a new column.
-func (*Store) createColumnImpl(ctx context.Context, tx *Tx, create *api.ColumnCreate) (*api.Column, error) {
- defaultStr := sql.NullString{}
- if create.Default != nil {
- defaultStr = sql.NullString{
- String: *create.Default,
- Valid: true,
- }
- }
-
- // Insert row into column.
- query := `
- INSERT INTO col (
- creator_id,
- updater_id,
- database_id,
- table_id,
- name,
- position,
- "default",
- nullable,
- type,
- character_set,
- "collation",
- comment
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, table_id, name, position, "default", nullable, type, character_set, "collation", comment
- `
- var column api.Column
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatorID,
- create.DatabaseID,
- create.TableID,
- create.Name,
- create.Position,
- defaultStr,
- create.Nullable,
- create.Type,
- create.CharacterSet,
- create.Collation,
- create.Comment,
- ).Scan(
- &column.ID,
- &column.CreatorID,
- &column.CreatedTs,
- &column.UpdaterID,
- &column.UpdatedTs,
- &column.DatabaseID,
- &column.TableID,
- &column.Name,
- &column.Position,
- &defaultStr,
- &column.Nullable,
- &column.Type,
- &column.CharacterSet,
- &column.Collation,
- &column.Comment,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
- if defaultStr.Valid {
- column.Default = &defaultStr.String
- }
- return &column, nil
-}
-
-func (*Store) findColumnImpl(ctx context.Context, tx *Tx, find *api.ColumnFind) ([]*api.Column, error) {
- // Build WHERE clause.
- where, args := []string{"1 = 1"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.DatabaseID; v != nil {
- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.TableID; v != nil {
- where, args = append(where, fmt.Sprintf("table_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Name; v != nil {
- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- table_id,
- name,
- position,
- "default",
- nullable,
- type,
- character_set,
- "collation",
- comment
- FROM col
- WHERE `+strings.Join(where, " AND ")+`
- ORDER BY database_id, table_id, position ASC`,
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into columnList.
- var columnList []*api.Column
- for rows.Next() {
- var column api.Column
- defaultStr := sql.NullString{}
- if err := rows.Scan(
- &column.ID,
- &column.CreatorID,
- &column.CreatedTs,
- &column.UpdaterID,
- &column.UpdatedTs,
- &column.DatabaseID,
- &column.TableID,
- &column.Name,
- &column.Position,
- &defaultStr,
- &column.Nullable,
- &column.Type,
- &column.CharacterSet,
- &column.Collation,
- &column.Comment,
- ); err != nil {
- return nil, FormatError(err)
- }
-
- if defaultStr.Valid {
- column.Default = &defaultStr.String
- }
-
- columnList = append(columnList, &column)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return columnList, nil
-}
-
-// deleteColumnImpl deletes columns.
-func (*Store) deleteColumnImpl(ctx context.Context, tx *Tx, delete *api.ColumnDelete) error {
- if _, err := tx.ExecContext(ctx, `DELETE FROM col WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
-}
diff --git a/store/column_test.go b/store/column_test.go
deleted file mode 100644
index f77580d8d8..0000000000
--- a/store/column_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package store
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-func TestGenerateColumnActions(t *testing.T) {
- databaseID := 198
- tableID := 199
- tests := []struct {
- oldColumnList []*api.Column
- columnList []db.Column
- wantDeletes []*api.ColumnDelete
- wantCreates []*api.ColumnCreate
- }{
- {
- oldColumnList: []*api.Column{
- {ID: 123, Name: "column1", CharacterSet: "def1", Comment: "comment1"},
- {ID: 124, Name: "column2", CharacterSet: "def2", Comment: "comment2"},
- },
- columnList: []db.Column{
- {Name: "column1", CharacterSet: "def1-change", Comment: "comment1"},
- {Name: "column2", CharacterSet: "def2", Comment: "comment2-change"},
- {Name: "column3", CharacterSet: "def3", Comment: "comment3"},
- },
- wantDeletes: []*api.ColumnDelete{
- {ID: 123},
- {ID: 124},
- },
- wantCreates: []*api.ColumnCreate{
- {Name: "column1", CharacterSet: "def1-change", Comment: "comment1", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "column2", CharacterSet: "def2", Comment: "comment2-change", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "column3", CharacterSet: "def3", Comment: "comment3", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- },
- },
- {
- oldColumnList: []*api.Column{
- {ID: 123, Name: "column1", CharacterSet: "def1", Comment: "comment1"},
- },
- columnList: nil,
- wantCreates: nil,
- wantDeletes: []*api.ColumnDelete{
- {ID: 123},
- },
- },
- {
- oldColumnList: nil,
- columnList: []db.Column{
- {Name: "column1", CharacterSet: "def1", Comment: "comment1"},
- {Name: "column2", CharacterSet: "def2", Comment: "comment2"},
- },
- wantDeletes: nil,
- wantCreates: []*api.ColumnCreate{
- {Name: "column1", CharacterSet: "def1", Comment: "comment1", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "column2", CharacterSet: "def2", Comment: "comment2", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- },
- },
- {
- oldColumnList: []*api.Column{
- {ID: 123, Name: "column1", CharacterSet: "def1", Comment: "comment1"},
- },
- columnList: []db.Column{
- {Name: "column1", CharacterSet: "def1", Comment: "comment1"},
- },
- wantDeletes: nil,
- wantCreates: nil,
- },
- }
-
- for _, test := range tests {
- deletes, creates := generateColumnActions(test.oldColumnList, test.columnList, databaseID, tableID)
- require.Equal(t, test.wantDeletes, deletes)
- require.Equal(t, test.wantCreates, creates)
- }
-}
diff --git a/store/extension.go b/store/extension.go
deleted file mode 100644
index 184061efe3..0000000000
--- a/store/extension.go
+++ /dev/null
@@ -1,315 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "strings"
-
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/common"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-// dbExtensionRaw is the store model for an DBExtension.
-// Fields have exactly the same meaning as DBExtension.
-type dbExtensionRaw struct {
- ID int
-
- // Standard fields
- CreatorID int
- CreatedTs int64
- UpdaterID int
- UpdatedTs int64
-
- // Related fields
- DatabaseID int
-
- // Domain specific fields
- Name string
- Version string
- Schema string
- Description string
-}
-
-// toDBExtension creates an instance of DBExtension based on the dbExtensionRaw.
-// This is intended to be called when we need to compose an DBExtension relationship.
-func (raw *dbExtensionRaw) toDBExtension() *api.DBExtension {
- return &api.DBExtension{
- ID: raw.ID,
-
- // Standard fields
- CreatorID: raw.CreatorID,
- CreatedTs: raw.CreatedTs,
- UpdaterID: raw.UpdaterID,
- UpdatedTs: raw.UpdatedTs,
-
- // Related fields
- DatabaseID: raw.DatabaseID,
-
- // Domain specific fields
- Name: raw.Name,
- Version: raw.Version,
- Schema: raw.Schema,
- Description: raw.Description,
- }
-}
-
-// FindDBExtension finds a list of dbExtension instances.
-func (s *Store) FindDBExtension(ctx context.Context, find *api.DBExtensionFind) ([]*api.DBExtension, error) {
- dbExtensionRawList, err := s.findDBExtensionRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to find dbExtension list with dbExtensionFind[%+v]", find)
- }
- var dbExtensionList []*api.DBExtension
- for _, raw := range dbExtensionRawList {
- dbExtension, err := s.composeDBExtension(ctx, raw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose dbExtension with dbExtensionRaw[%+v]", raw)
- }
- dbExtensionList = append(dbExtensionList, dbExtension)
- }
- return dbExtensionList, nil
-}
-
-type extensionKey struct {
- name string
- schema string
-}
-
-// SetDBExtensionList sets the extensions for a database.
-func (s *Store) SetDBExtensionList(ctx context.Context, schema *db.Schema, databaseID int) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return FormatError(err)
- }
- defer tx.Rollback()
-
- oldDBExtensionRawList, err := s.findDBExtensionImpl(ctx, tx, &api.DBExtensionFind{
- DatabaseID: &databaseID,
- })
- if err != nil {
- return FormatError(err)
- }
-
- deletes, creates := generateDBExtensionActions(oldDBExtensionRawList, schema.ExtensionList, databaseID)
- for _, d := range deletes {
- if err := s.deleteDBExtensionImpl(ctx, tx, d); err != nil {
- return err
- }
- }
- for _, c := range creates {
- if _, err := s.createDBExtensionImpl(ctx, tx, c); err != nil {
- return err
- }
- }
-
- if err := tx.Commit(); err != nil {
- return FormatError(err)
- }
-
- return nil
-}
-
-// private functions.
-func generateDBExtensionActions(oldDBExtensionRawList []*dbExtensionRaw, extensionList []db.Extension, databaseID int) ([]*api.DBExtensionDelete, []*api.DBExtensionCreate) {
- var newDBExtensionList []*api.DBExtensionCreate
- for _, dbExtension := range extensionList {
- newDBExtensionList = append(newDBExtensionList, &api.DBExtensionCreate{
- CreatorID: api.SystemBotID,
- DatabaseID: databaseID,
- Name: dbExtension.Name,
- Version: dbExtension.Version,
- Schema: dbExtension.Schema,
- Description: dbExtension.Description,
- })
- }
- oldDBExtensionMap := make(map[extensionKey]*dbExtensionRaw)
- for _, e := range oldDBExtensionRawList {
- oldDBExtensionMap[extensionKey{name: e.Name, schema: e.Schema}] = e
- }
- newDBExtensionMap := make(map[extensionKey]*api.DBExtensionCreate)
- for _, e := range newDBExtensionList {
- newDBExtensionMap[extensionKey{name: e.Name, schema: e.Schema}] = e
- }
-
- var deletes []*api.DBExtensionDelete
- var creates []*api.DBExtensionCreate
- for _, oldValue := range oldDBExtensionRawList {
- k := extensionKey{name: oldValue.Name, schema: oldValue.Schema}
- newValue, ok := newDBExtensionMap[k]
- if !ok {
- deletes = append(deletes, &api.DBExtensionDelete{ID: oldValue.ID})
- } else if ok && (oldValue.Version != newValue.Version || oldValue.Description != newValue.Description) {
- deletes = append(deletes, &api.DBExtensionDelete{ID: oldValue.ID})
- creates = append(creates, newValue)
- }
- }
- for _, newValue := range newDBExtensionList {
- k := extensionKey{name: newValue.Name, schema: newValue.Schema}
- if _, ok := oldDBExtensionMap[k]; !ok {
- creates = append(creates, newValue)
- }
- }
- return deletes, creates
-}
-
-func (s *Store) composeDBExtension(ctx context.Context, raw *dbExtensionRaw) (*api.DBExtension, error) {
- dbExtension := raw.toDBExtension()
-
- creator, err := s.GetPrincipalByID(ctx, dbExtension.CreatorID)
- if err != nil {
- return nil, err
- }
- dbExtension.Creator = creator
-
- updater, err := s.GetPrincipalByID(ctx, dbExtension.UpdaterID)
- if err != nil {
- return nil, err
- }
- dbExtension.Updater = updater
-
- database, err := s.GetDatabase(ctx, &api.DatabaseFind{ID: &dbExtension.DatabaseID})
- if err != nil {
- return nil, err
- }
- dbExtension.Database = database
-
- return dbExtension, nil
-}
-
-// findDBExtensionRaw retrieves a list of DBExtensions based on find.
-func (s *Store) findDBExtensionRaw(ctx context.Context, find *api.DBExtensionFind) ([]*dbExtensionRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findDBExtensionImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- return list, nil
-}
-
-// createDBExtensionImpl creates a new DBExtension.
-func (*Store) createDBExtensionImpl(ctx context.Context, tx *Tx, create *api.DBExtensionCreate) (*dbExtensionRaw, error) {
- // Insert row into db_extension.
- query := `
- INSERT INTO db_extension (
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- name,
- version,
- schema,
- description
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, version, schema, description
- `
- var dbExtensionRaw dbExtensionRaw
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatedTs,
- create.CreatorID,
- create.UpdatedTs,
- create.DatabaseID,
- create.Name,
- create.Version,
- create.Schema,
- create.Description,
- ).Scan(
- &dbExtensionRaw.ID,
- &dbExtensionRaw.CreatorID,
- &dbExtensionRaw.CreatedTs,
- &dbExtensionRaw.UpdaterID,
- &dbExtensionRaw.UpdatedTs,
- &dbExtensionRaw.DatabaseID,
- &dbExtensionRaw.Name,
- &dbExtensionRaw.Version,
- &dbExtensionRaw.Schema,
- &dbExtensionRaw.Description,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
- return &dbExtensionRaw, nil
-}
-
-func (*Store) findDBExtensionImpl(ctx context.Context, tx *Tx, find *api.DBExtensionFind) ([]*dbExtensionRaw, error) {
- // Build WHERE clause.
- where, args := []string{"1 = 1"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.DatabaseID; v != nil {
- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
- }
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- name,
- version,
- schema,
- description
- FROM db_extension
- WHERE `+strings.Join(where, " AND ")+`
- ORDER BY database_id, name ASC`,
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into DBExtensionRawList.
- var dbExtensionRawList []*dbExtensionRaw
- for rows.Next() {
- var dbExtensionRaw dbExtensionRaw
- if err := rows.Scan(
- &dbExtensionRaw.ID,
- &dbExtensionRaw.CreatorID,
- &dbExtensionRaw.CreatedTs,
- &dbExtensionRaw.UpdaterID,
- &dbExtensionRaw.UpdatedTs,
- &dbExtensionRaw.DatabaseID,
- &dbExtensionRaw.Name,
- &dbExtensionRaw.Version,
- &dbExtensionRaw.Schema,
- &dbExtensionRaw.Description,
- ); err != nil {
- return nil, FormatError(err)
- }
-
- dbExtensionRawList = append(dbExtensionRawList, &dbExtensionRaw)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return dbExtensionRawList, nil
-}
-
-// deleteDBExtensionImpl permanently deletes DBExtensions from a database.
-func (*Store) deleteDBExtensionImpl(ctx context.Context, tx *Tx, delete *api.DBExtensionDelete) error {
- // Remove row from database.
- if _, err := tx.ExecContext(ctx, `DELETE FROM db_extension WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
-}
diff --git a/store/extension_test.go b/store/extension_test.go
deleted file mode 100644
index f2b0029919..0000000000
--- a/store/extension_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-package store
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-func TestGenerateDBExtensionActions(t *testing.T) {
- databaseID := 198
- tests := []struct {
- oldDBExtensionRawList []*dbExtensionRaw
- dbExtensionList []db.Extension
- wantDeletes []*api.DBExtensionDelete
- wantCreates []*api.DBExtensionCreate
- }{
- {
- oldDBExtensionRawList: []*dbExtensionRaw{
- {ID: 123, Name: "hstore", Schema: "public", Version: "v1", Description: "desc1"},
- },
- dbExtensionList: []db.Extension{
- {Name: "hstore", Schema: "public", Version: "v2", Description: "desc1"},
- {Name: "hdd", Schema: "ddd", Version: "v3", Description: "desc3"},
- },
- wantDeletes: []*api.DBExtensionDelete{
- {ID: 123},
- },
- wantCreates: []*api.DBExtensionCreate{
- {Name: "hstore", Schema: "public", Version: "v2", Description: "desc1", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- {Name: "hdd", Schema: "ddd", Version: "v3", Description: "desc3", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- },
- },
- {
- oldDBExtensionRawList: []*dbExtensionRaw{
- {ID: 123, Name: "hstore", Schema: "public", Version: "v1", Description: "desc1"},
- },
- dbExtensionList: nil,
- wantDeletes: []*api.DBExtensionDelete{
- {ID: 123},
- },
- wantCreates: nil,
- },
- {
- oldDBExtensionRawList: nil,
- dbExtensionList: []db.Extension{
- {Name: "hstore", Schema: "public", Version: "v2", Description: "desc1"},
- {Name: "hdd", Schema: "ddd", Version: "v3", Description: "desc3"},
- },
- wantDeletes: nil,
- wantCreates: []*api.DBExtensionCreate{
- {Name: "hstore", Schema: "public", Version: "v2", Description: "desc1", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- {Name: "hdd", Schema: "ddd", Version: "v3", Description: "desc3", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- },
- },
- {
- oldDBExtensionRawList: []*dbExtensionRaw{
- {ID: 123, Name: "hstore", Schema: "public", Version: "v1", Description: "desc1"},
- },
- dbExtensionList: []db.Extension{
- {Name: "hstore", Schema: "public", Version: "v1", Description: "desc1"},
- },
- wantDeletes: nil,
- wantCreates: nil,
- },
- }
-
- for _, test := range tests {
- deletes, creates := generateDBExtensionActions(test.oldDBExtensionRawList, test.dbExtensionList, databaseID)
- require.Equal(t, test.wantDeletes, deletes)
- require.Equal(t, test.wantCreates, creates)
- }
-}
diff --git a/store/table.go b/store/table.go
deleted file mode 100644
index aa0eefa568..0000000000
--- a/store/table.go
+++ /dev/null
@@ -1,526 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "strings"
-
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/common"
- "github.com/bytebase/bytebase/common/log"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-// tableRaw is the store model for an Table.
-// Fields have exactly the same meanings as Table.
-type tableRaw struct {
- ID int
-
- // Standard fields
- CreatorID int
- CreatedTs int64
- UpdaterID int
- UpdatedTs int64
-
- // Related fields
- DatabaseID int
-
- // Domain specific fields
- Name string
- Type string
- Engine string
- Collation string
- RowCount int64
- DataSize int64
- IndexSize int64
- DataFree int64
- CreateOptions string
- Comment string
-}
-
-// toTable creates an instance of Table based on the tableRaw.
-// This is intended to be called when we need to compose an Table relationship.
-func (raw *tableRaw) toTable() *api.Table {
- return &api.Table{
- ID: raw.ID,
-
- // Standard fields
- CreatorID: raw.CreatorID,
- CreatedTs: raw.CreatedTs,
- UpdaterID: raw.UpdaterID,
- UpdatedTs: raw.UpdatedTs,
-
- // Related fields
- DatabaseID: raw.DatabaseID,
-
- // Domain specific fields
- Name: raw.Name,
- Type: raw.Type,
- Engine: raw.Engine,
- Collation: raw.Collation,
- RowCount: raw.RowCount,
- DataSize: raw.DataSize,
- IndexSize: raw.IndexSize,
- DataFree: raw.DataFree,
- CreateOptions: raw.CreateOptions,
- Comment: raw.Comment,
- }
-}
-
-// GetTable gets an instance of Table.
-func (s *Store) GetTable(ctx context.Context, find *api.TableFind) (*api.Table, error) {
- tableRaw, err := s.getTableRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to get Table with TableFind[%+v]", find)
- }
- if tableRaw == nil {
- return nil, nil
- }
- table, err := s.composeTable(ctx, tableRaw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose Table with tableRaw[%+v]", tableRaw)
- }
- return table, nil
-}
-
-// FindTable finds a list of Table instances.
-func (s *Store) FindTable(ctx context.Context, find *api.TableFind) ([]*api.Table, error) {
- tableRawList, err := s.findTableRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrap(err, "failed to find Table list")
- }
- var tableList []*api.Table
- for _, raw := range tableRawList {
- table, err := s.composeTable(ctx, raw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose Table with tableRaw[%+v]", raw)
- }
- tableList = append(tableList, table)
- }
- return tableList, nil
-}
-
-// SetTableList sets the tables for a database.
-func (s *Store) SetTableList(ctx context.Context, schema *db.Schema, databaseID int) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return FormatError(err)
- }
- defer tx.Rollback()
-
- oldTableRawList, err := s.findTableImpl(ctx, tx, &api.TableFind{
- DatabaseID: &databaseID,
- })
- if err != nil {
- return FormatError(err)
- }
- creates, patches, deletes := generateTableActions(oldTableRawList, schema.TableList, databaseID)
- for _, d := range deletes {
- if err := s.deleteTableImpl(ctx, tx, d); err != nil {
- return err
- }
- }
- for _, p := range patches {
- if _, err := s.patchTableImpl(ctx, tx, p); err != nil {
- return err
- }
- }
- for _, c := range creates {
- if _, err := s.createTableImpl(ctx, tx, c); err != nil {
- return err
- }
- }
-
- tableRawList, err := s.findTableImpl(ctx, tx, &api.TableFind{
- DatabaseID: &databaseID,
- })
- if err != nil {
- return err
- }
- tableIDMap := make(map[string]int)
- for _, table := range tableRawList {
- tableIDMap[table.Name] = table.ID
- }
-
- for _, table := range schema.TableList {
- tableID, ok := tableIDMap[table.Name]
- if !ok {
- log.Error(fmt.Sprintf("table ID cannot be found for database %v table %s", databaseID, table.Name))
- }
-
- columnList, err := s.findColumnImpl(ctx, tx, &api.ColumnFind{
- TableID: &tableID,
- })
- if err != nil {
- return err
- }
- deletes, creates := generateColumnActions(columnList, table.ColumnList, databaseID, tableID)
- for _, d := range deletes {
- if err := s.deleteColumnImpl(ctx, tx, d); err != nil {
- return err
- }
- }
- for _, c := range creates {
- if _, err := s.createColumnImpl(ctx, tx, c); err != nil {
- return err
- }
- }
-
- indexList, err := s.findIndexImpl(ctx, tx, &api.IndexFind{
- TableID: &tableID,
- })
- if err != nil {
- return err
- }
- idxDeletes, idxCreates := generateIndexActions(indexList, table.IndexList, databaseID, tableID)
- for _, d := range idxDeletes {
- if err := s.deleteIndexImpl(ctx, tx, d); err != nil {
- return err
- }
- }
- for _, c := range idxCreates {
- if _, err := s.createIndexImpl(ctx, tx, c); err != nil {
- return err
- }
- }
- }
-
- if err := tx.Commit(); err != nil {
- return FormatError(err)
- }
-
- return nil
-}
-
-func generateTableActions(oldTableRawList []*tableRaw, tableList []db.Table, databaseID int) ([]*api.TableCreate, []*api.TablePatch, []*api.TableDelete) {
- oldTableMap := make(map[string]*tableRaw)
- for _, t := range oldTableRawList {
- oldTableMap[t.Name] = t
- }
- newTableMap := make(map[string]db.Table)
- for _, t := range tableList {
- newTableMap[t.Name] = t
- }
-
- var creates []*api.TableCreate
- var patches []*api.TablePatch
- var deletes []*api.TableDelete
- for _, oldValue := range oldTableRawList {
- k := oldValue.Name
- newValue, ok := newTableMap[k]
- if !ok {
- deletes = append(deletes, &api.TableDelete{ID: oldValue.ID})
- } else if ok &&
- (oldValue.Type != newValue.Type ||
- oldValue.Engine != newValue.Engine ||
- oldValue.Collation != newValue.Collation ||
- oldValue.RowCount != newValue.RowCount ||
- oldValue.DataSize != newValue.DataSize ||
- oldValue.IndexSize != newValue.IndexSize ||
- oldValue.DataFree != newValue.DataFree ||
- oldValue.CreateOptions != newValue.CreateOptions ||
- oldValue.Comment != newValue.Comment) {
- patches = append(patches,
- &api.TablePatch{
- ID: oldValue.ID,
- UpdaterID: api.SystemBotID,
- Type: newValue.Type,
- Engine: newValue.Engine,
- Collation: newValue.Collation,
- RowCount: newValue.RowCount,
- DataSize: newValue.DataSize,
- IndexSize: newValue.IndexSize,
- DataFree: newValue.DataFree,
- CreateOptions: newValue.CreateOptions,
- Comment: newValue.Comment,
- },
- )
- }
- }
- for _, newValue := range tableList {
- k := newValue.Name
- if _, ok := oldTableMap[k]; !ok {
- creates = append(creates, &api.TableCreate{
- CreatorID: api.SystemBotID,
- CreatedTs: newValue.CreatedTs,
- UpdatedTs: newValue.UpdatedTs,
- DatabaseID: databaseID,
- Name: newValue.Name,
- Type: newValue.Type,
- Engine: newValue.Engine,
- Collation: newValue.Collation,
- RowCount: newValue.RowCount,
- DataSize: newValue.DataSize,
- IndexSize: newValue.IndexSize,
- DataFree: newValue.DataFree,
- CreateOptions: newValue.CreateOptions,
- Comment: newValue.Comment,
- })
- }
- }
- return creates, patches, deletes
-}
-
-//
-// private functions
-//
-
-func (s *Store) composeTable(ctx context.Context, raw *tableRaw) (*api.Table, error) {
- table := raw.toTable()
-
- creator, err := s.GetPrincipalByID(ctx, table.CreatorID)
- if err != nil {
- return nil, err
- }
- table.Creator = creator
-
- updater, err := s.GetPrincipalByID(ctx, table.UpdaterID)
- if err != nil {
- return nil, err
- }
- table.Updater = updater
-
- database, err := s.GetDatabase(ctx, &api.DatabaseFind{ID: &table.DatabaseID})
- if err != nil {
- return nil, err
- }
- table.Database = database
-
- return table, nil
-}
-
-// findTableRaw retrieves a list of tables based on find.
-func (s *Store) findTableRaw(ctx context.Context, find *api.TableFind) ([]*tableRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findTableImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- return list, nil
-}
-
-// getTableRaw retrieves a single table based on find.
-// Returns ECONFLICT if finding more than 1 matching records.
-func (s *Store) getTableRaw(ctx context.Context, find *api.TableFind) (*tableRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findTableImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- if len(list) == 0 {
- return nil, nil
- } else if len(list) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d tables with filter %+v, expect 1", len(list), find)}
- }
- return list[0], nil
-}
-
-// createTableImpl creates a new table.
-func (*Store) createTableImpl(ctx context.Context, tx *Tx, create *api.TableCreate) (*tableRaw, error) {
- // Insert row into table.
- query := `
- INSERT INTO tbl (
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- name,
- type,
- engine,
- "collation",
- row_count,
- data_size,
- index_size,
- data_free,
- create_options,
- comment
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, type, engine, "collation", row_count, data_size, index_size, data_free, create_options, comment
- `
- var tableRaw tableRaw
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatedTs,
- create.CreatorID,
- create.UpdatedTs,
- create.DatabaseID,
- create.Name,
- create.Type,
- create.Engine,
- create.Collation,
- create.RowCount,
- create.DataSize,
- create.IndexSize,
- create.DataFree,
- create.CreateOptions,
- create.Comment,
- ).Scan(
- &tableRaw.ID,
- &tableRaw.CreatorID,
- &tableRaw.CreatedTs,
- &tableRaw.UpdaterID,
- &tableRaw.UpdatedTs,
- &tableRaw.DatabaseID,
- &tableRaw.Name,
- &tableRaw.Type,
- &tableRaw.Engine,
- &tableRaw.Collation,
- &tableRaw.RowCount,
- &tableRaw.DataSize,
- &tableRaw.IndexSize,
- &tableRaw.DataFree,
- &tableRaw.CreateOptions,
- &tableRaw.Comment,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
- return &tableRaw, nil
-}
-
-// patchTableImpl patches a table.
-func (*Store) patchTableImpl(ctx context.Context, tx *Tx, patch *api.TablePatch) (*tableRaw, error) {
- var tableRaw tableRaw
- // Execute update query with RETURNING.
- if err := tx.QueryRowContext(ctx, `
- UPDATE tbl
- SET type=$1, engine=$2, "collation"=$3, row_count=$4, data_size=$5, index_size=$6, data_free=$7, create_options=$8, comment=$9
- WHERE id = $10
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, type, engine, "collation", row_count, data_size, index_size, data_free, create_options, comment`,
- patch.Type,
- patch.Engine,
- patch.Collation,
- patch.RowCount,
- patch.DataSize,
- patch.IndexSize,
- patch.DataFree,
- patch.CreateOptions,
- patch.Comment,
- patch.ID,
- ).Scan(
- &tableRaw.ID,
- &tableRaw.CreatorID,
- &tableRaw.CreatedTs,
- &tableRaw.UpdaterID,
- &tableRaw.UpdatedTs,
- &tableRaw.DatabaseID,
- &tableRaw.Name,
- &tableRaw.Type,
- &tableRaw.Engine,
- &tableRaw.Collation,
- &tableRaw.RowCount,
- &tableRaw.DataSize,
- &tableRaw.IndexSize,
- &tableRaw.DataFree,
- &tableRaw.CreateOptions,
- &tableRaw.Comment,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("table ID not found: %d", patch.ID)}
- }
- return nil, FormatError(err)
- }
- return &tableRaw, nil
-}
-
-func (*Store) findTableImpl(ctx context.Context, tx *Tx, find *api.TableFind) ([]*tableRaw, error) {
- // Build WHERE clause.
- where, args := []string{"1 = 1"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.DatabaseID; v != nil {
- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Name; v != nil {
- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- name,
- type,
- engine,
- "collation",
- row_count,
- data_size,
- index_size,
- data_free,
- create_options,
- comment
- FROM tbl
- WHERE `+strings.Join(where, " AND "),
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into tableRawList.
- var tableRawList []*tableRaw
- for rows.Next() {
- var tableRaw tableRaw
- if err := rows.Scan(
- &tableRaw.ID,
- &tableRaw.CreatorID,
- &tableRaw.CreatedTs,
- &tableRaw.UpdaterID,
- &tableRaw.UpdatedTs,
- &tableRaw.DatabaseID,
- &tableRaw.Name,
- &tableRaw.Type,
- &tableRaw.Engine,
- &tableRaw.Collation,
- &tableRaw.RowCount,
- &tableRaw.DataSize,
- &tableRaw.IndexSize,
- &tableRaw.DataFree,
- &tableRaw.CreateOptions,
- &tableRaw.Comment,
- ); err != nil {
- return nil, FormatError(err)
- }
-
- tableRawList = append(tableRawList, &tableRaw)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return tableRawList, nil
-}
-
-// deleteTableImpl permanently deletes tables from a database.
-func (*Store) deleteTableImpl(ctx context.Context, tx *Tx, delete *api.TableDelete) error {
- // Remove row from database.
- if _, err := tx.ExecContext(ctx, `DELETE FROM tbl WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
-}
diff --git a/store/table_index.go b/store/table_index.go
deleted file mode 100644
index ca5a99e53a..0000000000
--- a/store/table_index.go
+++ /dev/null
@@ -1,238 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "sort"
- "strings"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/common"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-// FindIndex retrieves a list of indices based on find.
-func (s *Store) FindIndex(ctx context.Context, find *api.IndexFind) ([]*api.Index, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findIndexImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- return list, nil
-}
-
-type indexKey struct {
- name string
- position int
-}
-
-func generateIndexActions(oldIndexList []*api.Index, indexList []db.Index, databaseID, tableID int) ([]*api.IndexDelete, []*api.IndexCreate) {
- var indexCreateList []*api.IndexCreate
- for _, index := range indexList {
- indexCreateList = append(indexCreateList, &api.IndexCreate{
- CreatorID: api.SystemBotID,
- DatabaseID: databaseID,
- TableID: tableID,
- Name: index.Name,
- Expression: index.Expression,
- Position: index.Position,
- Type: index.Type,
- Unique: index.Unique,
- Primary: index.Primary,
- Visible: index.Visible,
- Comment: index.Comment,
- })
- }
- oldIndexMap := make(map[indexKey]*api.Index)
- for _, index := range oldIndexList {
- oldIndexMap[indexKey{index.Name, index.Position}] = index
- }
- newIndexMap := make(map[indexKey]*api.IndexCreate)
- for _, index := range indexCreateList {
- newIndexMap[indexKey{index.Name, index.Position}] = index
- }
-
- var deletes []*api.IndexDelete
- var creates []*api.IndexCreate
- for _, oldValue := range oldIndexList {
- k := indexKey{oldValue.Name, oldValue.Position}
- newValue, ok := newIndexMap[k]
- if !ok {
- deletes = append(deletes, &api.IndexDelete{ID: oldValue.ID})
- } else if ok && (oldValue.Expression != newValue.Expression || oldValue.Position != newValue.Position || oldValue.Type != newValue.Type || oldValue.Unique != newValue.Unique || oldValue.Primary != newValue.Primary || oldValue.Visible != newValue.Visible || oldValue.Comment != newValue.Comment) {
- deletes = append(deletes, &api.IndexDelete{ID: oldValue.ID})
- creates = append(creates, newValue)
- }
- }
- for _, newValue := range indexCreateList {
- k := indexKey{newValue.Name, newValue.Position}
- if _, ok := oldIndexMap[k]; !ok {
- creates = append(creates, newValue)
- }
- }
- // The ordering of creates and deletes are not consistently produced because of maps. We need to produce a consistent output
- // for callers such as testing.
- sort.Slice(deletes, func(i, j int) bool {
- return deletes[i].ID < deletes[j].ID
- })
- sort.Slice(creates, func(i, j int) bool {
- return creates[i].Name < creates[j].Name || (creates[i].Name == creates[j].Name && creates[i].Position < creates[j].Position)
- })
-
- return deletes, creates
-}
-
-// createIndexImpl creates a new index.
-func (*Store) createIndexImpl(ctx context.Context, tx *Tx, create *api.IndexCreate) (*api.Index, error) {
- // Insert row into index.
- query := `
- INSERT INTO idx (
- creator_id,
- updater_id,
- database_id,
- table_id,
- name,
- expression,
- position,
- type,
- "unique",
- "primary",
- visible,
- comment
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, table_id, name, expression, position, type, "unique", "primary", visible, comment
- `
- var index api.Index
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatorID,
- create.DatabaseID,
- create.TableID,
- create.Name,
- create.Expression,
- create.Position,
- create.Type,
- create.Unique,
- create.Primary,
- create.Visible,
- create.Comment,
- ).Scan(
- &index.ID,
- &index.CreatorID,
- &index.CreatedTs,
- &index.UpdaterID,
- &index.UpdatedTs,
- &index.DatabaseID,
- &index.TableID,
- &index.Name,
- &index.Expression,
- &index.Position,
- &index.Type,
- &index.Unique,
- &index.Primary,
- &index.Visible,
- &index.Comment,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
-
- return &index, nil
-}
-
-func (*Store) findIndexImpl(ctx context.Context, tx *Tx, find *api.IndexFind) ([]*api.Index, error) {
- // Build WHERE clause.
- where, args := []string{"1 = 1"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.DatabaseID; v != nil {
- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.TableID; v != nil {
- where, args = append(where, fmt.Sprintf("table_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Name; v != nil {
- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Expression; v != nil {
- where, args = append(where, fmt.Sprintf("expression = $%d", len(args)+1)), append(args, *v)
- }
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- table_id,
- name,
- expression,
- position,
- type,
- "unique",
- "primary",
- visible,
- comment
- FROM idx
- WHERE `+strings.Join(where, " AND ")+`
- ORDER BY database_id, table_id, CASE WHEN "primary" THEN 1 ELSE 2 END, name ASC, position ASC`,
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into indexList.
- var indexList []*api.Index
- for rows.Next() {
- var index api.Index
- if err := rows.Scan(
- &index.ID,
- &index.CreatorID,
- &index.CreatedTs,
- &index.UpdaterID,
- &index.UpdatedTs,
- &index.DatabaseID,
- &index.TableID,
- &index.Name,
- &index.Expression,
- &index.Position,
- &index.Type,
- &index.Unique,
- &index.Primary,
- &index.Visible,
- &index.Comment,
- ); err != nil {
- return nil, FormatError(err)
- }
-
- indexList = append(indexList, &index)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return indexList, nil
-}
-
-// deleteIndexImpl deletes an index.
-func (*Store) deleteIndexImpl(ctx context.Context, tx *Tx, delete *api.IndexDelete) error {
- if _, err := tx.ExecContext(ctx, `DELETE FROM idx WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
-}
diff --git a/store/table_index_test.go b/store/table_index_test.go
deleted file mode 100644
index 69a44ac98b..0000000000
--- a/store/table_index_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package store
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-func TestGenerateIndexActions(t *testing.T) {
- databaseID := 198
- tableID := 199
- tests := []struct {
- oldIndexList []*api.Index
- indexList []db.Index
- wantDeletes []*api.IndexDelete
- wantCreates []*api.IndexCreate
- }{
- {
- oldIndexList: []*api.Index{
- {ID: 123, Name: "index1", Expression: "def1", Comment: "comment1"},
- {ID: 124, Name: "index2", Expression: "def2", Position: 1, Comment: "comment2"},
- {ID: 125, Name: "index2", Expression: "def2", Position: 2, Comment: "comment2"},
- },
- indexList: []db.Index{
- {Name: "index1", Expression: "def1-change", Comment: "comment1"},
- {Name: "index2", Expression: "def2", Position: 1, Comment: "comment2"},
- {Name: "index2", Expression: "def2", Position: 2, Comment: "comment2-change"},
- {Name: "index2", Expression: "def2", Position: 3, Comment: "comment2-new"},
- {Name: "index3", Expression: "def3", Comment: "comment3"},
- },
- wantDeletes: []*api.IndexDelete{
- {ID: 123},
- {ID: 125},
- },
- wantCreates: []*api.IndexCreate{
- {Name: "index1", Expression: "def1-change", Comment: "comment1", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "index2", Expression: "def2", Position: 2, Comment: "comment2-change", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "index2", Expression: "def2", Position: 3, Comment: "comment2-new", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "index3", Expression: "def3", Comment: "comment3", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- },
- },
- {
- oldIndexList: []*api.Index{
- {ID: 123, Name: "index1", Expression: "def1", Comment: "comment1"},
- },
- indexList: nil,
- wantCreates: nil,
- wantDeletes: []*api.IndexDelete{
- {ID: 123},
- },
- },
- {
- oldIndexList: nil,
- indexList: []db.Index{
- {Name: "index1", Expression: "def1", Comment: "comment1"},
- {Name: "index2", Expression: "def2", Comment: "comment2"},
- },
- wantDeletes: nil,
- wantCreates: []*api.IndexCreate{
- {Name: "index1", Expression: "def1", Comment: "comment1", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- {Name: "index2", Expression: "def2", Comment: "comment2", CreatorID: api.SystemBotID, DatabaseID: databaseID, TableID: tableID},
- },
- },
- {
- oldIndexList: []*api.Index{
- {ID: 123, Name: "index1", Expression: "def1", Comment: "comment1"},
- },
- indexList: []db.Index{
- {Name: "index1", Expression: "def1", Comment: "comment1"},
- },
- wantDeletes: nil,
- wantCreates: nil,
- },
- }
-
- for _, test := range tests {
- deletes, creates := generateIndexActions(test.oldIndexList, test.indexList, databaseID, tableID)
- require.Equal(t, test.wantDeletes, deletes)
- require.Equal(t, test.wantCreates, creates)
- }
-}
diff --git a/store/view.go b/store/view.go
deleted file mode 100644
index f64b87d96e..0000000000
--- a/store/view.go
+++ /dev/null
@@ -1,307 +0,0 @@
-package store
-
-import (
- "context"
- "database/sql"
- "fmt"
- "strings"
-
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/common"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-// viewRaw is the store model for an View.
-// Fields have exactly the same meanings as View.
-type viewRaw struct {
- ID int
-
- // Standard fields
- CreatorID int
- CreatedTs int64
- UpdaterID int
- UpdatedTs int64
-
- // Related fields
- DatabaseID int
-
- // Domain specific fields
- Name string
- Definition string
- Comment string
-}
-
-// toView creates an instance of View based on the viewRaw.
-// This is intended to be called when we need to compose an View relationship.
-func (raw *viewRaw) toView() *api.View {
- return &api.View{
- ID: raw.ID,
-
- // Standard fields
- CreatorID: raw.CreatorID,
- CreatedTs: raw.CreatedTs,
- UpdaterID: raw.UpdaterID,
- UpdatedTs: raw.UpdatedTs,
-
- // Related fields
- DatabaseID: raw.DatabaseID,
-
- // Domain specific fields
- Name: raw.Name,
- Definition: raw.Definition,
- Comment: raw.Comment,
- }
-}
-
-// FindView finds a list of View instances.
-func (s *Store) FindView(ctx context.Context, find *api.ViewFind) ([]*api.View, error) {
- viewRawList, err := s.findViewRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to find View list with ViewFind[%+v]", find)
- }
- var viewList []*api.View
- for _, raw := range viewRawList {
- view, err := s.composeView(ctx, raw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose View with viewRaw[%+v]", raw)
- }
- viewList = append(viewList, view)
- }
- return viewList, nil
-}
-
-// SetViewList sets the views for a database.
-func (s *Store) SetViewList(ctx context.Context, schema *db.Schema, databaseID int) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return FormatError(err)
- }
- defer tx.Rollback()
-
- oldViewRawList, err := s.findViewImpl(ctx, tx, &api.ViewFind{
- DatabaseID: &databaseID,
- })
- if err != nil {
- return FormatError(err)
- }
-
- deletes, creates := generateViewActions(oldViewRawList, schema.ViewList, databaseID)
- for _, d := range deletes {
- if err := s.deleteViewImpl(ctx, tx, d); err != nil {
- return err
- }
- }
- for _, c := range creates {
- if _, err := s.createViewImpl(ctx, tx, c); err != nil {
- return err
- }
- }
-
- if err := tx.Commit(); err != nil {
- return FormatError(err)
- }
-
- return nil
-}
-
-// private functions.
-func generateViewActions(oldViewRawList []*viewRaw, viewList []db.View, databaseID int) ([]*api.ViewDelete, []*api.ViewCreate) {
- var viewCreateList []*api.ViewCreate
- for _, view := range viewList {
- viewCreateList = append(viewCreateList, &api.ViewCreate{
- CreatorID: api.SystemBotID,
- CreatedTs: view.CreatedTs,
- UpdatedTs: view.UpdatedTs,
- DatabaseID: databaseID,
- Name: view.Name,
- Definition: view.Definition,
- Comment: view.Comment,
- })
- }
- oldViewMap := make(map[string]*viewRaw)
- for _, v := range oldViewRawList {
- oldViewMap[v.Name] = v
- }
- newViewMap := make(map[string]*api.ViewCreate)
- for _, v := range viewCreateList {
- newViewMap[v.Name] = v
- }
-
- var deletes []*api.ViewDelete
- var creates []*api.ViewCreate
- for _, oldValue := range oldViewRawList {
- k := oldValue.Name
- newValue, ok := newViewMap[k]
- if !ok {
- deletes = append(deletes, &api.ViewDelete{ID: oldValue.ID})
- } else if ok && (oldValue.Definition != newValue.Definition || oldValue.Comment != newValue.Comment) {
- deletes = append(deletes, &api.ViewDelete{ID: oldValue.ID})
- creates = append(creates, newValue)
- }
- }
- for _, newValue := range viewCreateList {
- k := newValue.Name
- if _, ok := oldViewMap[k]; !ok {
- creates = append(creates, newValue)
- }
- }
- return deletes, creates
-}
-
-func (s *Store) composeView(ctx context.Context, raw *viewRaw) (*api.View, error) {
- view := raw.toView()
-
- creator, err := s.GetPrincipalByID(ctx, view.CreatorID)
- if err != nil {
- return nil, err
- }
- view.Creator = creator
-
- updater, err := s.GetPrincipalByID(ctx, view.UpdaterID)
- if err != nil {
- return nil, err
- }
- view.Updater = updater
-
- database, err := s.GetDatabase(ctx, &api.DatabaseFind{ID: &view.DatabaseID})
- if err != nil {
- return nil, err
- }
- view.Database = database
-
- return view, nil
-}
-
-// findViewRaw retrieves a list of views based on find.
-func (s *Store) findViewRaw(ctx context.Context, find *api.ViewFind) ([]*viewRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findViewImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- return list, nil
-}
-
-// createViewImpl creates a new view.
-func (*Store) createViewImpl(ctx context.Context, tx *Tx, create *api.ViewCreate) (*viewRaw, error) {
- // Insert row into view.
- query := `
- INSERT INTO vw (
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- name,
- definition,
- comment
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)` +
- "RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, definition, comment" + `
- `
- var viewRaw viewRaw
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatedTs,
- create.CreatorID,
- create.UpdatedTs,
- create.DatabaseID,
- create.Name,
- create.Definition,
- create.Comment,
- ).Scan(
- &viewRaw.ID,
- &viewRaw.CreatorID,
- &viewRaw.CreatedTs,
- &viewRaw.UpdaterID,
- &viewRaw.UpdatedTs,
- &viewRaw.DatabaseID,
- &viewRaw.Name,
- &viewRaw.Definition,
- &viewRaw.Comment,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
- return &viewRaw, nil
-}
-
-func (*Store) findViewImpl(ctx context.Context, tx *Tx, find *api.ViewFind) ([]*viewRaw, error) {
- // Build WHERE clause.
- where, args := []string{"1 = 1"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.DatabaseID; v != nil {
- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Name; v != nil {
- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- database_id,
- name,
- definition,
- comment
- FROM vw
- WHERE `+strings.Join(where, " AND ")+`
- ORDER BY database_id, name ASC`,
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into viewRawList.
- var viewRawList []*viewRaw
- for rows.Next() {
- var viewRaw viewRaw
- if err := rows.Scan(
- &viewRaw.ID,
- &viewRaw.CreatorID,
- &viewRaw.CreatedTs,
- &viewRaw.UpdaterID,
- &viewRaw.UpdatedTs,
- &viewRaw.DatabaseID,
- &viewRaw.Name,
- &viewRaw.Definition,
- &viewRaw.Comment,
- ); err != nil {
- return nil, FormatError(err)
- }
-
- viewRawList = append(viewRawList, &viewRaw)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return viewRawList, nil
-}
-
-// deleteViewImpl permanently deletes views from a database.
-func (*Store) deleteViewImpl(ctx context.Context, tx *Tx, delete *api.ViewDelete) error {
- // Remove row from database.
- if _, err := tx.ExecContext(ctx, `DELETE FROM vw WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
-}
diff --git a/store/view_test.go b/store/view_test.go
deleted file mode 100644
index 9dbb4c57aa..0000000000
--- a/store/view_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package store
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-func TestGenerateViewActions(t *testing.T) {
- databaseID := 198
- tests := []struct {
- oldViewRawList []*viewRaw
- viewList []db.View
- wantDeletes []*api.ViewDelete
- wantCreates []*api.ViewCreate
- }{
- {
- oldViewRawList: []*viewRaw{
- {ID: 123, Name: "view1", Definition: "def1", Comment: "comment1"},
- {ID: 124, Name: "view2", Definition: "def2", Comment: "comment2"},
- },
- viewList: []db.View{
- {Name: "view1", Definition: "def1-change", Comment: "comment1"},
- {Name: "view2", Definition: "def2", Comment: "comment2-change"},
- {Name: "view3", Definition: "def3", Comment: "comment3"},
- },
- wantDeletes: []*api.ViewDelete{
- {ID: 123},
- {ID: 124},
- },
- wantCreates: []*api.ViewCreate{
- {Name: "view1", Definition: "def1-change", Comment: "comment1", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- {Name: "view2", Definition: "def2", Comment: "comment2-change", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- {Name: "view3", Definition: "def3", Comment: "comment3", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- },
- },
- {
- oldViewRawList: []*viewRaw{
- {ID: 123, Name: "view1", Definition: "def1", Comment: "comment1"},
- },
- viewList: nil,
- wantCreates: nil,
- wantDeletes: []*api.ViewDelete{
- {ID: 123},
- },
- },
- {
- oldViewRawList: nil,
- viewList: []db.View{
- {Name: "view1", Definition: "def1", Comment: "comment1"},
- {Name: "view2", Definition: "def2", Comment: "comment2"},
- },
- wantDeletes: nil,
- wantCreates: []*api.ViewCreate{
- {Name: "view1", Definition: "def1", Comment: "comment1", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- {Name: "view2", Definition: "def2", Comment: "comment2", CreatorID: api.SystemBotID, DatabaseID: databaseID},
- },
- },
- {
- oldViewRawList: []*viewRaw{
- {ID: 123, Name: "view1", Definition: "def1", Comment: "comment1"},
- },
- viewList: []db.View{
- {Name: "view1", Definition: "def1", Comment: "comment1"},
- },
- wantDeletes: nil,
- wantCreates: nil,
- },
- }
-
- for _, test := range tests {
- deletes, creates := generateViewActions(test.oldViewRawList, test.viewList, databaseID)
- require.Equal(t, test.wantDeletes, deletes)
- require.Equal(t, test.wantCreates, creates)
- }
-}