Skip to content

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

Store index info and expose it on the table detail page

天舟756b61b46605
diff --git a/api/table.go b/api/table.go
index f60d7ed222..2fd129b2c1 100644
--- a/api/table.go
+++ b/api/table.go
@@ -34,6 +34,7 @@ type Table struct {
CreateOptions string `jsonapi:"attr,createOptions"`
Comment string `jsonapi:"attr,comment"`
ColumnList []*Column `jsonapi:"attr,columnList"`
+ IndexList []*Index `jsonapi:"attr,indexList"`
}
type TableCreate struct {
diff --git a/api/table_index.go b/api/table_index.go
new file mode 100644
index 0000000000..c288bbb081
--- /dev/null
+++ b/api/table_index.go
@@ -0,0 +1,89 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+)
+
+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
+ SyncStatus SyncStatus `json:"syncStatus"`
+ LastSuccessfulSyncTs int64 `json:"lastSuccessfulSyncTs"`
+ Name string `json:"name"`
+ Expression string `json:"expression"`
+ Position int `json:"position"`
+ Type string `json:"type"`
+ Unique bool `json:"unique"`
+ Visible bool `json:"visible"`
+ Comment string `json:"comment"`
+}
+
+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
+ Visible bool
+ Comment string
+}
+
+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)
+}
+
+type IndexPatch 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 IndexService interface {
+ CreateIndex(ctx context.Context, create *IndexCreate) (*Index, error)
+ FindIndexList(ctx context.Context, find *IndexFind) ([]*Index, error)
+ FindIndex(ctx context.Context, find *IndexFind) (*Index, error)
+ PatchIndex(ctx context.Context, patch *IndexPatch) (*Index, error)
+}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 2bf2e5ac65..c0a8520c98 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -263,6 +263,7 @@ func (m *main) Run() error {
server.InstanceService = store.NewInstanceService(m.l, db, server.CacheService, server.DatabaseService, server.DataSourceService)
server.TableService = store.NewTableService(m.l, db)
server.ColumnService = store.NewColumnService(m.l, db)
+ server.IndexService = store.NewIndexService(m.l, db)
server.IssueService = store.NewIssueService(m.l, db, server.CacheService)
server.IssueSubscriberService = store.NewIssueSubscriberService(m.l, db)
server.PipelineService = store.NewPipelineService(m.l, db, server.CacheService)
diff --git a/db/driver.go b/db/driver.go
index 1f8abf1f93..efbea5d5de 100644
--- a/db/driver.go
+++ b/db/driver.go
@@ -25,6 +25,17 @@ func (e Type) String() string {
return "UNKNOWN"
}
+type DBIndex struct {
+ Name string
+ // This could refer to a column or an expression
+ Expression string
+ Position int
+ Type string
+ Unique bool
+ Visible bool
+ Comment string
+}
+
type DBColumn struct {
Name string
Position int
@@ -50,6 +61,7 @@ type DBTable struct {
CreateOptions string
Comment string
ColumnList []DBColumn
+ IndexList []DBIndex
}
type DBSchema struct {
diff --git a/db/mysql.go b/db/mysql.go
index 3ac97ae0ea..ed2347dae8 100644
--- a/db/mysql.go
+++ b/db/mysql.go
@@ -73,6 +73,67 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
"'bytebase'",
}
+ // Query index info
+ indexWhere := fmt.Sprintf("TABLE_SCHEMA NOT IN (%s)", strings.Join(excludedDatabaseList, ", "))
+ indexRows, err := driver.db.QueryContext(ctx, `
+ SELECT
+ TABLE_SCHEMA,
+ TABLE_NAME,
+ INDEX_NAME,
+ COLUMN_NAME,
+ EXPRESSION,
+ SEQ_IN_INDEX,
+ INDEX_TYPE,
+ CASE NON_UNIQUE WHEN 0 THEN 1 ELSE 0 END AS IS_UNIQUE,
+ CASE IS_VISIBLE WHEN 'YES' THEN 1 ELSE 0 END,
+ INDEX_COMMENT
+ FROM information_schema.STATISTICS
+ WHERE `+indexWhere,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ // dbName/tableName -> indexList map
+ indexMap := make(map[string][]DBIndex)
+ for indexRows.Next() {
+ var dbName string
+ var tableName string
+ var columnName sql.NullString
+ var expression sql.NullString
+ var index DBIndex
+ if err := indexRows.Scan(
+ &dbName,
+ &tableName,
+ &index.Name,
+ &columnName,
+ &expression,
+ &index.Position,
+ &index.Type,
+ &index.Unique,
+ &index.Visible,
+ &index.Comment,
+ ); err != nil {
+ return nil, err
+ }
+
+ if columnName.Valid {
+ index.Expression = columnName.String
+ } else if expression.Valid {
+ index.Expression = expression.String
+ }
+
+ key := fmt.Sprintf("%s/%s", dbName, tableName)
+ indexList, ok := indexMap[key]
+ if ok {
+ indexMap[key] = append(indexList, index)
+ } else {
+ list := make([]DBIndex, 0)
+ indexMap[key] = append(list, index)
+ }
+ }
+ indexRows.Close()
+
// Query column info
columnWhere := fmt.Sprintf("TABLE_SCHEMA NOT IN (%s)", strings.Join(excludedDatabaseList, ", "))
columnRows, err := driver.db.QueryContext(ctx, `
@@ -94,7 +155,7 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
return nil, err
}
- // dbName.tableName -> columnList map
+ // dbName/tableName -> columnList map
columnMap := make(map[string][]DBColumn)
for columnRows.Next() {
var dbName string
@@ -121,7 +182,7 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
column.Default = &defaultStr.String
}
- key := fmt.Sprintf("%s.%s", dbName, tableName)
+ key := fmt.Sprintf("%s/%s", dbName, tableName)
tableList, ok := columnMap[key]
if ok {
columnMap[key] = append(tableList, column)
@@ -179,8 +240,9 @@ func (driver *MySQLDriver) SyncSchema(ctx context.Context) ([]*DBSchema, error)
return nil, err
}
- key := fmt.Sprintf("%s.%s", dbName, table.Name)
+ key := fmt.Sprintf("%s/%s", dbName, table.Name)
table.ColumnList = columnMap[key]
+ table.IndexList = indexMap[key]
tableList, ok := tableMap[dbName]
if ok {
diff --git a/frontend/src/components/IndexTable.vue b/frontend/src/components/IndexTable.vue
new file mode 100644
index 0000000000..6a76d3c0ca
--- /dev/null
+++ b/frontend/src/components/IndexTable.vue
@@ -0,0 +1,110 @@
+<template>
+ <BBTable
+ :columnList="COLUMN_LIST"
+ :sectionDataSource="sectionList"
+ :showHeader="true"
+ :compactSection="false"
+ >
+ <template v-slot:header>
+ <BBTableHeaderCell
+ :leftPadding="4"
+ class="w-16"
+ :title="COLUMN_LIST[0].title"
+ />
+ <BBTableHeaderCell class="w-4" :title="COLUMN_LIST[1].title" />
+ <BBTableHeaderCell class="w-4" :title="COLUMN_LIST[2].title" />
+ <BBTableHeaderCell class="w-4" :title="COLUMN_LIST[3].title" />
+ <BBTableHeaderCell class="w-16" :title="COLUMN_LIST[4].title" />
+ <BBTableHeaderCell class="w-8" :title="COLUMN_LIST[5].title" />
+ <BBTableHeaderCell class="w-16" :title="COLUMN_LIST[6].title" />
+ </template>
+ <template v-slot:body="{ rowData: index }">
+ <BBTableCell :leftPadding="4">
+ {{ index.expression }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ index.position }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ index.unique }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ index.visible }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ index.comment }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ index.syncStatus }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ humanizeTs(index.lastSuccessfulSyncTs) }}
+ </BBTableCell>
+ </template>
+ </BBTable>
+</template>
+
+<script lang="ts">
+import { computed, PropType } from "vue";
+import { BBTableColumn, BBTableSectionDataSource } from "../bbkit/types";
+import { TableIndex } from "../types";
+
+const COLUMN_LIST: BBTableColumn[] = [
+ {
+ title: "Expression",
+ },
+ {
+ title: "Position",
+ },
+ {
+ title: "Unique",
+ },
+ {
+ title: "Visible",
+ },
+ {
+ title: "Comment",
+ },
+ {
+ title: "Sync status",
+ },
+ {
+ title: "Last successful sync",
+ },
+];
+
+export default {
+ name: "IndexTable",
+ components: {},
+ props: {
+ indexList: {
+ required: true,
+ type: Object as PropType<TableIndex[]>,
+ },
+ },
+ setup(props, ctx) {
+ const sectionList = computed(() => {
+ const sectionList: BBTableSectionDataSource<TableIndex>[] = [];
+
+ for (const index of props.indexList) {
+ const item = sectionList.find((item) => item.title == index.name);
+ if (item) {
+ item.list.push(index);
+ } else {
+ sectionList.push({
+ title: index.name,
+ list: [index],
+ });
+ }
+ }
+
+ return sectionList;
+ });
+
+ return {
+ COLUMN_LIST,
+ sectionList,
+ };
+ },
+};
+</script>
diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.ts
index a35af1d4b4..8fb1cd3917 100644
--- a/frontend/src/types/id.ts
+++ b/frontend/src/types/id.ts
@@ -39,6 +39,8 @@ export type TableId = IdType;
export type ColumnId = IdType;
+export type TableIndexId = IdType;
+
export type VCSId = IdType;
export type RepositoryId = IdType;
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index a5a2988648..5f2bd1b76d 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -24,4 +24,5 @@ export * from "./repository";
export * from "./sql";
export * from "./store";
export * from "./table";
+export * from "./tableIndex";
export * from "./vcs";
diff --git a/frontend/src/types/tableIndex.ts b/frontend/src/types/tableIndex.ts
new file mode 100644
index 0000000000..64a9a80da3
--- /dev/null
+++ b/frontend/src/types/tableIndex.ts
@@ -0,0 +1,30 @@
+import { DatabaseId, TableId, TableIndexId } from "./id";
+
+// Similar to DatabaseSyncStatus, see comment
+export type IndexSyncStatus = "OK" | "NOT_FOUND";
+
+// Index
+export type TableIndex = {
+ id: TableIndexId;
+
+ // Related fields
+ databaseId: DatabaseId;
+ tableId: TableId;
+
+ // Standard fields
+ creatorId: number;
+ createdTs: number;
+ updaterId: number;
+ updatedTs: number;
+
+ // Domain specific fields
+ syncStatus: IndexSyncStatus;
+ lastSuccessfulSyncTs: number;
+ name: string;
+ expression: string;
+ position: number;
+ type: string;
+ unique: boolean;
+ visible: boolean;
+ comment: string;
+};
diff --git a/frontend/src/views/TableDetail.vue b/frontend/src/views/TableDetail.vue
index 013eb6cff2..837859f105 100644
--- a/frontend/src/views/TableDetail.vue
+++ b/frontend/src/views/TableDetail.vue
@@ -169,8 +169,14 @@
</div>
<div class="mt-6 px-6">
+ <div class="text-lg leading-6 font-medium text-main mb-4">Columns</div>
<ColumnTable :columnList="table.columnList" />
</div>
+
+ <div class="mt-6 px-6">
+ <div class="text-lg leading-6 font-medium text-main mb-4">Indexes</div>
+ <IndexTable :indexList="table.indexList" />
+ </div>
</main>
</div>
</template>
@@ -179,6 +185,7 @@
import { computed } from "@vue/runtime-core";
import { useStore } from "vuex";
import ColumnTable from "../components/ColumnTable.vue";
+import IndexTable from "../components/IndexTable.vue";
import { bytesToString, idFromSlug } from "../utils";
export default {
@@ -193,7 +200,7 @@ export default {
type: String,
},
},
- components: { ColumnTable },
+ components: { ColumnTable, IndexTable },
setup(props, ctx) {
const store = useStore();
@@ -205,7 +212,6 @@ export default {
});
const database = computed(() => {
- console.log("table", table.value);
return table.value.database;
});
diff --git a/server/database.go b/server/database.go
index 4e4121f6c1..58c5846786 100644
--- a/server/database.go
+++ b/server/database.go
@@ -177,6 +177,15 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch colmun list for database id: %d, table name: %s", id, table.Name)).SetInternal(err)
}
+
+ indexFind := &api.IndexFind{
+ DatabaseId: &id,
+ TableId: &table.ID,
+ }
+ table.IndexList, err = s.IndexService.FindIndexList(context.Background(), 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)
+ }
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
@@ -224,6 +233,15 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch colmun list for database id: %d, table name: %s", id, tableName)).SetInternal(err)
}
+ indexFind := &api.IndexFind{
+ DatabaseId: &id,
+ TableId: &table.ID,
+ }
+ table.IndexList, err = s.IndexService.FindIndexList(context.Background(), 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)
+ }
+
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)
diff --git a/server/server.go b/server/server.go
index b6f0b662e4..770a4197ac 100644
--- a/server/server.go
+++ b/server/server.go
@@ -33,6 +33,7 @@ type Server struct {
DatabaseService api.DatabaseService
TableService api.TableService
ColumnService api.ColumnService
+ IndexService api.IndexService
DataSourceService api.DataSourceService
IssueService api.IssueService
IssueSubscriberService api.IssueSubscriberService
diff --git a/server/sql.go b/server/sql.go
index 5456391d8d..0dd29fbd9d 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -127,6 +127,17 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
return nil
}
+ var createIndex = func(database *api.Database, table *api.Table, indexCreate *api.IndexCreate) error {
+ _, err := s.IndexService.CreateIndex(context.Background(), indexCreate)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
+ return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. index and expression already exists: %s(%s)", instance.Name, database.Name, table.Name, indexCreate.Name, indexCreate.Expression)
+ }
+ return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. Failed to import new index and expression: %s(%s). Error %w", instance.Name, database.Name, table.Name, indexCreate.Name, indexCreate.Expression, err)
+ }
+ return nil
+ }
+
// Compare the stored db info with the just synced db schema.
// Case 1: If item appears both in the stored db info and the synced db schema, then we UPDATE the corresponding record in the stored db.
// Case 2: If item only appears in the synced schema and not in the stored db, then we CREATE the record in the stored db.
@@ -169,6 +180,7 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
}
for _, table := range schema.TableList {
+ // Table
tableFind := &api.TableFind{
DatabaseId: &database.ID,
Name: &table.Name,
@@ -214,6 +226,7 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
}
}
+ // Column
for _, column := range table.ColumnList {
columnFind := &api.ColumnFind{
DatabaseId: &database.ID,
@@ -258,6 +271,52 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
}
}
}
+
+ // Index
+ for _, index := range table.IndexList {
+ indexFind := &api.IndexFind{
+ DatabaseId: &database.ID,
+ TableId: &upsertedTable.ID,
+ Name: &index.Name,
+ Expression: &index.Expression,
+ }
+ storedIndex, err := s.IndexService.FindIndex(context.Background(), indexFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ indexCreate := &api.IndexCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ DatabaseId: database.ID,
+ TableId: upsertedTable.ID,
+ Name: index.Name,
+ Expression: index.Expression,
+ Position: index.Position,
+ Type: index.Type,
+ Unique: index.Unique,
+ Visible: index.Visible,
+ Comment: index.Comment,
+ }
+ if err := createIndex(database, upsertedTable, indexCreate); err != nil {
+ return err
+ }
+ } else {
+ return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. Error %w", instance.Name, database.Name, upsertedTable.Name, err)
+ }
+ } else {
+ indexPatch := &api.IndexPatch{
+ ID: storedIndex.ID,
+ UpdaterId: api.SYSTEM_BOT_ID,
+ SyncStatus: &syncStatus,
+ LastSuccessfulSyncTs: &ts,
+ }
+ _, err := s.IndexService.PatchIndex(context.Background(), indexPatch)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. Index not found: %s", instance.Name, database.Name, upsertedTable.Name, storedIndex.Name)
+ }
+ return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. Failed to update index: %s. Error %w", instance.Name, database.Name, upsertedTable.Name, storedIndex.Name, err)
+ }
+ }
+ }
}
} else {
// Case 2
@@ -278,6 +337,7 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
}
for _, table := range schema.TableList {
+ // Table
tableCreate := &api.TableCreate{
CreatorId: api.SYSTEM_BOT_ID,
DatabaseId: database.ID,
@@ -297,6 +357,7 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
return err
}
+ // Column
for _, column := range table.ColumnList {
columnFind := &api.ColumnFind{
DatabaseId: &database.ID,
@@ -327,6 +388,38 @@ func (s *Server) SyncSchema(instance *api.Instance) (rs *api.SqlResultSet) {
}
}
}
+
+ // Index
+ for _, index := range table.IndexList {
+ indexFind := &api.IndexFind{
+ DatabaseId: &database.ID,
+ TableId: &upsertedTable.ID,
+ Name: &index.Name,
+ Expression: &index.Expression,
+ }
+ _, err := s.IndexService.FindIndex(context.Background(), indexFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ indexCreate := &api.IndexCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ DatabaseId: database.ID,
+ TableId: upsertedTable.ID,
+ Name: index.Name,
+ Expression: index.Expression,
+ Position: index.Position,
+ Type: index.Type,
+ Unique: index.Unique,
+ Visible: index.Visible,
+ Comment: index.Comment,
+ }
+ if err := createIndex(database, upsertedTable, indexCreate); err != nil {
+ return err
+ }
+ } else {
+ return fmt.Errorf("failed to sync index for instance: %s, database: %s, table: %s. Error %w", instance.Name, database.Name, upsertedTable.Name, err)
+ }
+ }
+ }
}
}
}
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index f3152fc71f..eef75e49a7 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -418,6 +418,51 @@ WHERE
END;
+-- idx stores the index for a particular table from a particular database
+-- data is synced periodically from the instance
+CREATE TABLE idx (
+ 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),
+ table_id INTEGER NOT NULL REFERENCES tbl (id),
+ sync_status TEXT NOT NULL CHECK (sync_status IN ('OK', 'NOT_FOUND')),
+ last_successful_sync_ts BIGINT NOT NULL,
+ name TEXT NOT NULL,
+ expression TEXT NOT NULL,
+ position INTEGER NOT NULL,
+ `type` TEXT NOT NULL,
+ `unique` INTEGER NOT NULL,
+ visible INTEGER NOT NULL,
+ `comment` TEXT NOT NULL,
+ UNIQUE(database_id, table_id, name, expression)
+);
+
+CREATE INDEX idx_idx_database_id_table_id ON idx(database_id, table_id);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('idx', 100);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_idx_modification_time`
+AFTER
+UPDATE
+ ON `idx` FOR EACH ROW BEGIN
+UPDATE
+ `idx`
+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/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index a8075daac6..b29fad228d 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -32,6 +32,9 @@ DELETE FROM
DELETE FROM
data_source;
+DELETE FROM
+ idx;
+
DELETE FROM
col;
diff --git a/store/seed/test/10073__idx.sql b/store/seed/test/10073__idx.sql
new file mode 100644
index 0000000000..07fe2081f6
--- /dev/null
+++ b/store/seed/test/10073__idx.sql
@@ -0,0 +1,613 @@
+-- Index for database 7002 testdb_dev, table 7101 tbl1
+INSERT INTO
+ idx (
+ id,
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 7301,
+ 101,
+ 101,
+ 7002,
+ 7101,
+ 'OK',
+ 1625075289,
+ 'idx_col1',
+ 'col1',
+ 1,
+ 'BTREE',
+ 0,
+ 1,
+ ''
+ );
+
+-- Index for database 7006 testdb_dev, table 7102 tbl1
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7006,
+ 7102,
+ 'OK',
+ 1625075289,
+ 'idx_col1',
+ 'col1',
+ 1,
+ 'BTREE',
+ 0,
+ 1,
+ ''
+ );
+
+-- Index for database 7010 testdb_dev, table 7103 tbl1
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7010,
+ 7103,
+ 'OK',
+ 1625075289,
+ 'idx_col1',
+ 'col1',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7014 testdb_dev, table 7104 tbl1
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7014,
+ 7104,
+ 'OK',
+ 1625075289,
+ 'idx_col1',
+ 'col1',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7003 shop, table 7105 product
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7003,
+ 7105,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7007 shop, table 7106 product
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7007,
+ 7106,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7004 blog, table 7107 user
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7004,
+ 7107,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7004 blog, table 7108 post
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7004,
+ 7108,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7004 blog, table 7109 comment
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7004,
+ 7109,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7008 blog, table 7110 user
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7008,
+ 7110,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7008 blog, table 7111 post
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7008,
+ 7111,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7008 blog, table 7112 comment
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7008,
+ 7112,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7012 blog, table 7113 user
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7012,
+ 7113,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7012 blog, table 7114 post
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7012,
+ 7114,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7012 blog, table 7115 comment
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7012,
+ 7115,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7016 blog, table 7116 user
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7016,
+ 7116,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7016 blog, table 7117 post
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7016,
+ 7117,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
+
+-- Index for database 7016 blog, table 7118 comment
+INSERT INTO
+ idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `type`,
+ `unique`,
+ visible,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 101,
+ 7016,
+ 7118,
+ 'OK',
+ 1625075289,
+ 'PRIMARY',
+ 'id',
+ 1,
+ 'BTREE',
+ 1,
+ 1,
+ ''
+ );
\ No newline at end of file
diff --git a/store/table_index.go b/store/table_index.go
new file mode 100644
index 0000000000..d9c1d4f3ce
--- /dev/null
+++ b/store/table_index.go
@@ -0,0 +1,307 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.IndexService = (*IndexService)(nil)
+)
+
+// IndexService represents a service for managing index.
+type IndexService struct {
+ l *zap.Logger
+ db *DB
+}
+
+// NewIndexService returns a new instance of IndexService.
+func NewIndexService(logger *zap.Logger, db *DB) *IndexService {
+ return &IndexService{l: logger, db: db}
+}
+
+// CreateIndex creates a new index.
+func (s *IndexService) CreateIndex(ctx context.Context, create *api.IndexCreate) (*api.Index, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ index, err := s.createIndex(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return index, nil
+}
+
+// FindIndexList retrieves a list of indexs based on find.
+func (s *IndexService) FindIndexList(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.findIndexList(ctx, tx, find)
+ if err != nil {
+ return []*api.Index{}, err
+ }
+
+ return list, nil
+}
+
+// FindIndex retrieves a single index based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns ECONFLICT if finding more than 1 matching records.
+func (s *IndexService) 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.findIndexList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("index not found: %+v", find)}
+ } else if len(list) > 1 {
+ return nil, &bytebase.Error{Code: bytebase.ECONFLICT, Message: fmt.Sprintf("found %d indexs with filter %+v, expect 1", len(list), find)}
+ }
+ return list[0], nil
+}
+
+// PatchIndex updates an existing index by ID.
+// Returns ENOTFOUND if index does not exist.
+func (s *IndexService) PatchIndex(ctx context.Context, patch *api.IndexPatch) (*api.Index, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ index, err := s.patchIndex(ctx, tx, patch)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return index, nil
+}
+
+// createIndex creates a new index.
+func (s *IndexService) createIndex(ctx context.Context, tx *Tx, create *api.IndexCreate) (*api.Index, error) {
+ // Insert row into index.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO idx (
+ creator_id,
+ updater_id,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `+"`type`,"+`
+ `+"`unique`,"+`
+ visible,
+ comment
+ )
+ VALUES (?, ?, ?, ?, 'OK', (strftime('%s', 'now')), ?, ?, ?, ?, ?, ?, ?)`+
+ "RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, table_id, sync_status, last_successful_sync_ts, name, expression, position, `type`, `unique`, visible, comment"+`
+ `,
+ create.CreatorId,
+ create.CreatorId,
+ create.DatabaseId,
+ create.TableId,
+ create.Name,
+ create.Expression,
+ create.Position,
+ create.Type,
+ create.Unique,
+ create.Visible,
+ create.Comment,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var index api.Index
+ if err := row.Scan(
+ &index.ID,
+ &index.CreatorId,
+ &index.CreatedTs,
+ &index.UpdaterId,
+ &index.UpdatedTs,
+ &index.DatabaseId,
+ &index.TableId,
+ &index.SyncStatus,
+ &index.LastSuccessfulSyncTs,
+ &index.Name,
+ &index.Expression,
+ &index.Position,
+ &index.Type,
+ &index.Unique,
+ &index.Visible,
+ &index.Comment,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &index, nil
+}
+
+func (s *IndexService) findIndexList(ctx context.Context, tx *Tx, find *api.IndexFind) (_ []*api.Index, 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.TableId; v != nil {
+ where, args = append(where, "table_id = ?"), append(args, *v)
+ }
+ if v := find.Name; v != nil {
+ where, args = append(where, "name = ?"), append(args, *v)
+ }
+ if v := find.Expression; v != nil {
+ where, args = append(where, "expression = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ database_id,
+ table_id,
+ sync_status,
+ last_successful_sync_ts,
+ name,
+ expression,
+ position,
+ `+"`type`,"+`
+ `+"`unique`,"+`
+ visible,
+ comment
+ FROM idx
+ WHERE `+strings.Join(where, " AND ")+`
+ ORDER BY database_id, table_id, CASE name 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 list.
+ list := make([]*api.Index, 0)
+ 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.SyncStatus,
+ &index.LastSuccessfulSyncTs,
+ &index.Name,
+ &index.Expression,
+ &index.Position,
+ &index.Type,
+ &index.Unique,
+ &index.Visible,
+ &index.Comment,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &index)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// patchIndex updates a index by ID. Returns the new state of the index after update.
+func (s *IndexService) patchIndex(ctx context.Context, tx *Tx, patch *api.IndexPatch) (*api.Index, 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 idx
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = ?`+
+ "RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, table_id, sync_status, last_successful_sync_ts, name, expression, position, `type`, `unique`, visible, comment"+`
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ var index api.Index
+ if err := row.Scan(
+ &index.ID,
+ &index.CreatorId,
+ &index.CreatedTs,
+ &index.UpdaterId,
+ &index.UpdatedTs,
+ &index.DatabaseId,
+ &index.TableId,
+ &index.SyncStatus,
+ &index.LastSuccessfulSyncTs,
+ &index.Name,
+ &index.Expression,
+ &index.Position,
+ &index.Type,
+ &index.Unique,
+ &index.Visible,
+ &index.Comment,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &index, nil
+ }
+
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("index ID not found: %d", patch.ID)}
+}