Skip to content

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

Add TableService and support sync table info

天舟e76ae76fd27f
diff --git a/backend/api/table.go b/backend/api/table.go
new file mode 100644
index 0000000000..bf53a55d5a
--- /dev/null
+++ b/backend/api/table.go
@@ -0,0 +1,86 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+)
+
+type Table struct {
+ ID int `jsonapi:"primary,table"`
+
+ // Standard fields
+ CreatorId int
+ Creator *Principal `jsonapi:"attr,creator"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int
+ Updater *Principal `jsonapi:"attr,updater"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Related fields
+ DatabaseId int
+ Database *Database `jsonapi:"relation,database"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ 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"`
+ SyncStatus SyncStatus `jsonapi:"attr,syncStatus"`
+ LastSuccessfulSyncTs int64 `jsonapi:"attr,lastSuccessfulSyncTs"`
+}
+
+type TableCreate struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ CreatorId int
+
+ // Related fields
+ DatabaseId int `jsonapi:"attr,databaseId"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Engine string `jsonapi:"attr,engine"`
+ Collation string `jsonapi:"attr,collation"`
+ RowCount int64
+ DataSize int64
+ IndexSize int64
+}
+
+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)
+}
+
+type TablePatch struct {
+ ID int
+
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterId int
+
+ // Domain specific fields
+ SyncStatus *SyncStatus
+ LastSuccessfulSyncTs *int64
+}
+
+type TableService interface {
+ CreateTable(ctx context.Context, create *TableCreate) (*Table, error)
+ FindTableList(ctx context.Context, find *TableFind) ([]*Table, error)
+ FindTable(ctx context.Context, find *TableFind) (*Table, error)
+ PatchTable(ctx context.Context, patch *TablePatch) (*Table, error)
+}
diff --git a/backend/cmd/echo/main.go b/backend/cmd/echo/main.go
index f654c421e5..bf9919a9d6 100644
--- a/backend/cmd/echo/main.go
+++ b/backend/cmd/echo/main.go
@@ -51,6 +51,7 @@ func (m *Main) Run() error {
server.EnvironmentService = store.NewEnvironmentService(m.l, db)
server.InstanceService = store.NewInstanceService(m.l, db)
server.DatabaseService = store.NewDatabaseService(m.l, db)
+ server.TableService = store.NewTableService(m.l, db)
server.DataSourceService = store.NewDataSourceService(m.l, db)
server.IssueService = store.NewIssueService(m.l, db)
server.PipelineService = store.NewPipelineService(m.l, db)
diff --git a/backend/db/driver.go b/backend/db/driver.go
index e2b09e914b..d46fd0403d 100644
--- a/backend/db/driver.go
+++ b/backend/db/driver.go
@@ -23,10 +23,22 @@ func (e Type) String() string {
return "UNKNOWN"
}
+type DBTable struct {
+ Name string
+ CreatedTs int64
+ UpdatedTs int64
+ Engine string
+ Collation string
+ RowCount int64
+ DataSize int64
+ IndexSize int64
+}
+
type DBSchema struct {
Name string
CharacterSet string
Collation string
+ TableList []DBTable
}
var (
diff --git a/backend/db/mysql.go b/backend/db/mysql.go
index 88c3441098..a1cd2b489c 100644
--- a/backend/db/mysql.go
+++ b/backend/db/mysql.go
@@ -59,8 +59,58 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
"'sys'",
}
- where := fmt.Sprintf("SCHEMA_NAME NOT IN (%s)", strings.Join(excludedDatabaseList, ", "))
+ // Query table info
+ tableWhere := fmt.Sprintf("TABLE_SCHEMA NOT IN (%s)", strings.Join(excludedDatabaseList, ", "))
+ tableRows, err := driver.db.QueryContext(ctx, `
+ SELECT
+ TABLE_SCHEMA,
+ TABLE_NAME,
+ UNIX_TIMESTAMP(CREATE_TIME),
+ IFNULL(UNIX_TIMESTAMP(UPDATE_TIME), 0),
+ ENGINE,
+ TABLE_COLLATION,
+ TABLE_ROWS,
+ DATA_LENGTH,
+ INDEX_LENGTH
+ FROM information_schema.TABLES
+ WHERE `+tableWhere,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ // dbName -> tableList map
+ tableMap := make(map[string][]DBTable)
+ for tableRows.Next() {
+ var dbName string
+ var table DBTable
+ if err := tableRows.Scan(
+ &dbName,
+ &table.Name,
+ &table.CreatedTs,
+ &table.UpdatedTs,
+ &table.Engine,
+ &table.Collation,
+ &table.RowCount,
+ &table.DataSize,
+ &table.IndexSize,
+ ); err != nil {
+ driver.l.Info(fmt.Sprintf("%v", err))
+ return nil, err
+ }
+ tableList, ok := tableMap[dbName]
+ if ok {
+ tableMap[dbName] = append(tableList, table)
+ } else {
+ list := make([]DBTable, 0)
+ tableMap[dbName] = append(list, table)
+ }
+ }
+ tableRows.Close()
+
+ // Query db info
+ where := fmt.Sprintf("SCHEMA_NAME NOT IN (%s)", strings.Join(excludedDatabaseList, ", "))
rows, err := driver.db.QueryContext(ctx, `
SELECT
SCHEMA_NAME,
@@ -85,6 +135,8 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
return nil, err
}
+ schema.TableList = tableMap[schema.Name]
+
list = append(list, &schema)
}
if err := rows.Err(); err != nil {
diff --git a/backend/server/server.go b/backend/server/server.go
index 4cb27dfebe..9059f1ef08 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -33,6 +33,7 @@ type Server struct {
EnvironmentService api.EnvironmentService
InstanceService api.InstanceService
DatabaseService api.DatabaseService
+ TableService api.TableService
DataSourceService api.DataSourceService
IssueService api.IssueService
PipelineService api.PipelineService
diff --git a/backend/server/sql.go b/backend/server/sql.go
index 33ee48b2cf..1b567e6947 100644
--- a/backend/server/sql.go
+++ b/backend/server/sql.go
@@ -56,7 +56,7 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", sync.InstanceId)).SetInternal(err)
}
- db, err := db.Open(db.Mysql, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
+ driver, err := db.Open(db.Mysql, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
Username: instance.Username,
Password: instance.Password,
Host: instance.Host,
@@ -67,52 +67,119 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
}
resultSet := &api.SqlResultSet{}
- schemaList, err := db.SyncSchema(context.Background())
+ schemaList, err := driver.SyncSchema(context.Background())
if err != nil {
resultSet.Error = err.Error()
- }
+ } else {
+ var createTable = func(database *api.Database, tableCreate *api.TableCreate) error {
+ _, err := s.TableService.CreateTable(context.Background(), tableCreate)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
+ return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Failed to sync table for instance: %s, database: %s. Table name already exists: %s", instance.Name, database.Name, tableCreate.Name))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s, database: %s. Failed to import new table: %s", instance.Name, database.Name, tableCreate.Name)).SetInternal(err)
+ }
+ return nil
+ }
- databaseFind := &api.DatabaseFind{
- InstanceId: &instance.ID,
- }
- for _, schema := range schemaList {
- databaseFind.Name = &schema.Name
- database, err := s.DatabaseService.FindDatabase(context.Background(), databaseFind)
- if err != nil {
- if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
- databaseCreate := &api.DatabaseCreate{
- CreatorId: c.Get(GetPrincipalIdContextKey()).(int),
- ProjectId: api.DEFAULT_PROJECT_ID,
- InstanceId: instance.ID,
- Name: schema.Name,
- CharacterSet: schema.CharacterSet,
- Collation: schema.Collation,
+ databaseFind := &api.DatabaseFind{
+ InstanceId: &instance.ID,
+ }
+ for _, schema := range schemaList {
+ databaseFind.Name = &schema.Name
+ database, err := s.DatabaseService.FindDatabase(context.Background(), databaseFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ databaseCreate := &api.DatabaseCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ ProjectId: api.DEFAULT_PROJECT_ID,
+ InstanceId: instance.ID,
+ Name: schema.Name,
+ CharacterSet: schema.CharacterSet,
+ Collation: schema.Collation,
+ }
+ database, err := s.DatabaseService.CreateDatabase(context.Background(), databaseCreate)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
+ return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s. Failed to import new database: %s", instance.Name, databaseCreate.Name)).SetInternal(err)
+ }
+
+ for _, table := range schema.TableList {
+ tableCreate := &api.TableCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ DatabaseId: database.ID,
+ Name: table.Name,
+ Engine: table.Engine,
+ Collation: table.Collation,
+ RowCount: table.RowCount,
+ DataSize: table.DataSize,
+ IndexSize: table.IndexSize,
+ }
+ if err := createTable(database, tableCreate); err != nil {
+ return err
+ }
+ }
+ } else {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s", instance.Name)).SetInternal(err)
+ }
+ } else {
+ syncStatus := api.OK
+ ts := time.Now().Unix()
+ databasePatch := &api.DatabasePatch{
+ ID: database.ID,
+ UpdaterId: api.SYSTEM_BOT_ID,
+ SyncStatus: &syncStatus,
+ LastSuccessfulSyncTs: &ts,
}
- _, err := s.DatabaseService.CreateDatabase(context.Background(), databaseCreate)
+ database, err := s.DatabaseService.PatchDatabase(context.Background(), databasePatch)
if err != nil {
- if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
- return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name))
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to sync database for instance: %s. Database not found: %s", instance.Name, database.Name))
}
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s. Failed to import new database: %s", instance.Name, databaseCreate.Name)).SetInternal(err)
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s. Failed to update database: %s", instance.Name, database.Name)).SetInternal(err)
}
- } else {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s", instance.Name)).SetInternal(err)
- }
- } else {
- syncStatus := api.OK
- ts := time.Now().Unix()
- databasePatch := &api.DatabasePatch{
- ID: database.ID,
- UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
- SyncStatus: &syncStatus,
- LastSuccessfulSyncTs: &ts,
- }
- _, err := s.DatabaseService.PatchDatabase(context.Background(), databasePatch)
- if err != nil {
- if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to sync database for instance: %s. Database not found: %s", instance.Name, database.Name))
+
+ for _, table := range schema.TableList {
+ tableFind := &api.TableFind{
+ DatabaseId: &database.ID,
+ Name: &table.Name,
+ }
+ table, err := s.TableService.FindTable(context.Background(), tableFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ tableCreate := &api.TableCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ DatabaseId: database.ID,
+ Name: table.Name,
+ Engine: table.Engine,
+ Collation: table.Collation,
+ RowCount: table.RowCount,
+ DataSize: table.DataSize,
+ IndexSize: table.IndexSize,
+ }
+ if err := createTable(database, tableCreate); err != nil {
+ return err
+ }
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync table for instance: %s, database: %s", instance.Name, database.Name)).SetInternal(err)
+ } else {
+ tablePatch := &api.TablePatch{
+ ID: table.ID,
+ UpdaterId: api.SYSTEM_BOT_ID,
+ SyncStatus: &syncStatus,
+ LastSuccessfulSyncTs: &ts,
+ }
+ _, err := s.TableService.PatchTable(context.Background(), tablePatch)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to sync table for instance: %s, database: %s. Table not found: %s", instance.Name, database.Name, table.Name))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync table for instance: %s, database: %s. Failed to update table: %s", instance.Name, database.Name, table.Name)).SetInternal(err)
+ }
+ }
}
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to sync database for instance: %s. Failed to update database: %s", instance.Name, database.Name)).SetInternal(err)
}
}
}
diff --git a/backend/store/migration/0001_init_schema.down.sql b/backend/store/migration/0001_init_schema.down.sql
index 9df575d09f..9eb35c75e4 100644
--- a/backend/store/migration/0001_init_schema.down.sql
+++ b/backend/store/migration/0001_init_schema.down.sql
@@ -14,6 +14,8 @@ DROP TABLE pipeline;
DROP TABLE data_source;
+DROP TABLE db_table;
+
DROP TABLE db;
DROP TABLE instance;
diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sql
index 31070d9c3b..61ff384e26 100644
--- a/backend/store/migration/0001_init_schema.up.sql
+++ b/backend/store/migration/0001_init_schema.up.sql
@@ -242,8 +242,8 @@ WHERE
END;
--- db table stores the databases for a particular instance
--- data is sycned periodically from the instance
+-- db stores the databases for a particular instance
+-- data is synced periodically from the instance
CREATE TABLE db (
id INTEGER PRIMARY KEY AUTOINCREMENT,
row_status TEXT NOT NULL CHECK (
@@ -284,6 +284,49 @@ WHERE
END;
+-- db_table stores the table for a particular database
+-- data is synced periodically from the instance
+CREATE TABLE db_table (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ row_status TEXT NOT NULL CHECK (
+ row_status IN ('NORMAL', 'ARCHIVED', 'PENDING_DELETE')
+ ) DEFAULT 'NORMAL',
+ creator_id INTEGER NOT NULL REFERENCES principal (id),
+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ updater_id INTEGER NOT NULL REFERENCES principal (id),
+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ database_id INTEGER NOT NULL REFERENCES db (id),
+ name TEXT NOT NULL,
+ `engine` TEXT NOT NULL,
+ `collation` TEXT NOT NULL,
+ row_count BIGINT NOT NULL,
+ data_size BIGINT NOT NULL,
+ index_size BIGINT NOT NULL,
+ sync_status TEXT NOT NULL CHECK (
+ sync_status IN ('OK', 'DRIFTED', 'NOT_FOUND')
+ ),
+ last_successful_sync_ts BIGINT NOT NULL,
+ UNIQUE(database_id, name)
+);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('db_table', 1000);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_db_table_modification_time`
+AFTER
+UPDATE
+ ON `db_table` FOR EACH ROW BEGIN
+UPDATE
+ `db_table`
+SET
+ updated_ts = (strftime('%s', 'now'))
+WHERE
+ rowid = old.rowid;
+
+END;
+
-- data_source table stores the data source for a particular database
CREATE TABLE data_source (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/backend/store/seed/0070_database.sql b/backend/store/seed/0070_db.sql
similarity index 100%
rename from backend/store/seed/0070_database.sql
rename to backend/store/seed/0070_db.sql
diff --git a/backend/store/seed/0071_db_table.sql b/backend/store/seed/0071_db_table.sql
new file mode 100644
index 0000000000..1467fbe983
--- /dev/null
+++ b/backend/store/seed/0071_db_table.sql
@@ -0,0 +1,2 @@
+-- db_table is populated via schema sync, so no seed data here.
+-- Creating this file just to reduce confusion in case people may wonder whether we miss the file.
\ No newline at end of file
diff --git a/backend/store/table.go b/backend/store/table.go
new file mode 100644
index 0000000000..283d73845c
--- /dev/null
+++ b/backend/store/table.go
@@ -0,0 +1,287 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.TableService = (*TableService)(nil)
+)
+
+// TableService represents a service for managing table.
+type TableService struct {
+ l *zap.Logger
+ db *DB
+}
+
+// NewTableService returns a new instance of TableService.
+func NewTableService(logger *zap.Logger, db *DB) *TableService {
+ return &TableService{l: logger, db: db}
+}
+
+// CreateTable creates a new table.
+func (s *TableService) CreateTable(ctx context.Context, create *api.TableCreate) (*api.Table, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ table, err := s.createTable(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return table, nil
+}
+
+// FindTableList retrieves a list of tables based on find.
+func (s *TableService) FindTableList(ctx context.Context, find *api.TableFind) ([]*api.Table, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findTableList(ctx, tx, find)
+ if err != nil {
+ return []*api.Table{}, err
+ }
+
+ return list, nil
+}
+
+// FindTable retrieves a single table based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns the first matching one and prints a warning if finding more than 1 matching records.
+func (s *TableService) FindTable(ctx context.Context, find *api.TableFind) (*api.Table, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findTableList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("table not found: %v", find)}
+ } else if len(list) > 1 {
+ s.l.Warn(fmt.Sprintf("found %d tables with filter %v, expect 1. ", len(list), find))
+ }
+ return list[0], nil
+}
+
+// PatchTable updates an existing table by ID.
+// Returns ENOTFOUND if table does not exist.
+func (s *TableService) PatchTable(ctx context.Context, patch *api.TablePatch) (*api.Table, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ table, err := s.patchTable(ctx, tx, patch)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return table, nil
+}
+
+// createTable creates a new table.
+func (s *TableService) createTable(ctx context.Context, tx *Tx, create *api.TableCreate) (*api.Table, error) {
+ // Insert row into table.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO db_table (
+ creator_id,
+ updater_id,
+ database_id,
+ name,
+ engine,
+ collation,
+ row_count,
+ data_size,
+ index_size,
+ sync_status,
+ last_successful_sync_ts
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'OK', (strftime('%s', 'now')))
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, engine, collation, row_count, data_size, index_size, sync_status, last_successful_sync_ts
+ `,
+ create.CreatorId,
+ create.CreatorId,
+ create.DatabaseId,
+ create.Name,
+ create.Engine,
+ create.Collation,
+ create.RowCount,
+ create.DataSize,
+ create.IndexSize,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var table api.Table
+ if err := row.Scan(
+ &table.ID,
+ &table.CreatorId,
+ &table.CreatedTs,
+ &table.UpdaterId,
+ &table.UpdatedTs,
+ &table.DatabaseId,
+ &table.Name,
+ &table.Engine,
+ &table.Collation,
+ &table.RowCount,
+ &table.DataSize,
+ &table.IndexSize,
+ &table.SyncStatus,
+ &table.LastSuccessfulSyncTs,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &table, nil
+}
+
+func (s *TableService) findTableList(ctx context.Context, tx *Tx, find *api.TableFind) (_ []*api.Table, err error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
+ if v := find.DatabaseId; v != nil {
+ where, args = append(where, "database_id = ?"), append(args, *v)
+ }
+ if v := find.Name; v != nil {
+ where, args = append(where, "name = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ database_id,
+ name,
+ engine,
+ collation,
+ row_count,
+ data_size,
+ index_size,
+ sync_status,
+ last_successful_sync_ts
+ FROM db_table
+ WHERE `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ list := make([]*api.Table, 0)
+ for rows.Next() {
+ var table api.Table
+ if err := rows.Scan(
+ &table.ID,
+ &table.CreatorId,
+ &table.CreatedTs,
+ &table.UpdaterId,
+ &table.UpdatedTs,
+ &table.DatabaseId,
+ &table.Name,
+ &table.Engine,
+ &table.Collation,
+ &table.RowCount,
+ &table.DataSize,
+ &table.IndexSize,
+ &table.SyncStatus,
+ &table.LastSuccessfulSyncTs,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &table)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// patchTable updates a table by ID. Returns the new state of the table after update.
+func (s *TableService) patchTable(ctx context.Context, tx *Tx, patch *api.TablePatch) (*api.Table, error) {
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ if v := patch.SyncStatus; v != nil {
+ set, args = append(set, "sync_status = ?"), append(args, api.SyncStatus(*v))
+ }
+ if v := patch.LastSuccessfulSyncTs; v != nil {
+ set, args = append(set, "last_successful_sync_ts = ?"), append(args, *v)
+ }
+
+ args = append(args, patch.ID)
+
+ // Execute update query with RETURNING.
+ row, err := tx.QueryContext(ctx, `
+ UPDATE db_table
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = ?
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, engine, collation, row_count, data_size, index_size, sync_status, last_successful_sync_ts
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ var table api.Table
+ if err := row.Scan(
+ &table.ID,
+ &table.CreatorId,
+ &table.CreatedTs,
+ &table.UpdaterId,
+ &table.UpdatedTs,
+ &table.DatabaseId,
+ &table.Name,
+ &table.Engine,
+ &table.Collation,
+ &table.RowCount,
+ &table.DataSize,
+ &table.IndexSize,
+ &table.SyncStatus,
+ &table.LastSuccessfulSyncTs,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ return &table, nil
+ }
+
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("table ID not found: %d", patch.ID)}
+}