Skip to content

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

Allow user to configure SQL console database/table URL

天舟22d8fd7c390c
diff --git a/api/setting.go b/api/setting.go
index 7cad856ad2..0364854d49 100644
--- a/api/setting.go
+++ b/api/setting.go
@@ -9,12 +9,34 @@ type SettingName string
const (
SettingAuthSecret SettingName = "bb.auth.secret"
+ // The console URL for a particular database, it supports following variables
+ // {{DB_NAME}}: the database name
+ // e.g. For a phpmyadmin instance running on http://myphpadmin.example.com:8080, the setting would be:
+ // http://myphpadmin.example.com:8080/index.php?route=/database/sql&db={{DB_NAME}}
+ SettingConsoleDatabase SettingName = "bb.console.database"
+ // The console URL for a particular table, it supports following variables
+ // {{DB_NAME}}: the database name
+ // {{TABLE_NAME}}: the table name
+ // e.g. For a phpmyadmin instance running on http://myphpadmin.example.com:8080, the setting would be:
+ // http://myphpadmin.example.com:8080/index.php?route=/table/sql&db={{DB_NAME}}&table={{TABLE_NAME}}
+ SettingConsoleTable SettingName = "bb.console.table"
)
type Setting struct {
- Name SettingName
- Value string
- Description string
+ ID int `jsonapi:"primary,setting"`
+
+ // 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"`
+
+ // Domain specific fields
+ Name SettingName `jsonapi:"attr,name"`
+ Value string `jsonapi:"attr,value"`
+ Description string `jsonapi:"attr,description"`
}
type SettingCreate struct {
@@ -25,7 +47,16 @@ type SettingCreate struct {
}
type SettingFind struct {
- Name SettingName
+ Name *SettingName
+}
+
+type SettingPatch struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterId int
+
+ Name SettingName
+ Value string `jsonapi:"attr,value"`
}
func (find *SettingFind) String() string {
@@ -39,5 +70,7 @@ func (find *SettingFind) String() string {
type SettingService interface {
// Creates new setting and returns if not exist, returns the existing one otherwise.
CreateSettingIfNotExist(ctx context.Context, create *SettingCreate) (*Setting, error)
+ FindSettingList(ctx context.Context, find *SettingFind) ([]*Setting, error)
FindSetting(ctx context.Context, find *SettingFind) (*Setting, error)
+ PatchSetting(ctx context.Context, patch *SettingPatch) (*Setting, error)
}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 0cdf6597d4..ac9bf59ed7 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -235,6 +235,32 @@ func initSetting(settingService api.SettingService) (*config, error) {
result.secret = config.Value
}
+ {
+ configCreate := &api.SettingCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ Name: api.SettingConsoleDatabase,
+ Value: "",
+ Description: "URL for the external console (e.g. phpMyAdmin) pointing to a particular database.",
+ }
+ _, err := settingService.CreateSettingIfNotExist(context.Background(), configCreate)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ {
+ configCreate := &api.SettingCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ Name: api.SettingConsoleTable,
+ Value: "",
+ Description: "URL for the external console (e.g. phpMyAdmin) pointing to a particular table.",
+ }
+ _, err := settingService.CreateSettingIfNotExist(context.Background(), configCreate)
+ if err != nil {
+ return nil, err
+ }
+ }
+
return result, nil
}
@@ -253,6 +279,7 @@ func (m *main) Run() error {
m.db = db
server := server.NewServer(m.l, version, host, port, m.profile.mode, config.secret, readonly, demo, debug)
+ server.SettingService = settingService
server.PrincipalService = store.NewPrincipalService(m.l, db, server.CacheService)
server.MemberService = store.NewMemberService(m.l, db, server.CacheService)
server.ProjectService = store.NewProjectService(m.l, db, server.CacheService)
diff --git a/frontend/src/components/DatabaseTable.vue b/frontend/src/components/DatabaseTable.vue
index 5753cc6ac6..a0ddb44056 100644
--- a/frontend/src/components/DatabaseTable.vue
+++ b/frontend/src/components/DatabaseTable.vue
@@ -61,6 +61,27 @@
<BBTableCell v-if="showMiscColumn" class="w-16">
{{ humanizeTs(database.lastSuccessfulSyncTs) }}
</BBTableCell>
+ <BBTableCell v-if="showConsoleLink" class="w-4">
+ <button
+ class="btn-icon"
+ @click.stop="window.open(consoleLink(database.name), '_blank')"
+ >
+ <svg
+ class="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
+ ></path>
+ </svg>
+ </button>
+ </BBTableCell>
</template>
</BBTable>
</template>
@@ -69,9 +90,10 @@
import { computed, PropType } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
-import { databaseSlug, isDBAOrOwner } from "../utils";
+import { databaseConsoleLink, databaseSlug, isDBAOrOwner } from "../utils";
import { Database } from "../types";
import { BBTableColumn } from "../bbkit/types";
+import { isEmpty } from "lodash";
type Mode = "ALL" | "ALL_SHORT" | "INSTANCE" | "PROJECT" | "PROJECT_SHORT";
@@ -282,17 +304,46 @@ export default {
});
const columnList = computed(() => {
+ var list: BBTableColumn[] = [];
if (
(props.mode == "ALL" || props.mode == "ALL_SHORT") &&
!showInstanceColumn.value
) {
- return props.mode == "ALL"
- ? columnListMap.get("ALL_HIDE_INSTANCE")
- : columnListMap.get("ALL_HIDE_INSTANCE_SHORT");
+ list =
+ props.mode == "ALL"
+ ? columnListMap.get("ALL_HIDE_INSTANCE")!
+ : columnListMap.get("ALL_HIDE_INSTANCE_SHORT")!;
+ } else {
+ list = columnListMap.get(props.mode)!;
+ }
+ if (showConsoleLink.value) {
+ list.push({ title: "SQL console" });
+ }
+ return list;
+ });
+
+ const showConsoleLink = computed(() => {
+ if (props.mode == "ALL_SHORT" || props.mode == "PROJECT_SHORT") {
+ return false;
}
- return columnListMap.get(props.mode);
+
+ const consoleURL = store.getters["setting/settingByName"](
+ "bb.console.database"
+ ).value;
+ console.log("aaa", consoleURL);
+ return !isEmpty(consoleURL);
});
+ const consoleLink = (databaseName: string) => {
+ const consoleURL = store.getters["setting/settingByName"](
+ "bb.console.database"
+ ).value;
+ if (!isEmpty(consoleURL)) {
+ return databaseConsoleLink(consoleURL, databaseName);
+ }
+ return "";
+ };
+
const clickDatabase = function (section: number, row: number) {
const database = props.databaseList[row];
if (props.customClick) {
@@ -308,6 +359,8 @@ export default {
showInstanceColumn,
showMiscColumn,
columnList,
+ showConsoleLink,
+ consoleLink,
clickDatabase,
};
},
diff --git a/frontend/src/components/TableTable.vue b/frontend/src/components/TableTable.vue
index 9a27444ce1..7424608aed 100644
--- a/frontend/src/components/TableTable.vue
+++ b/frontend/src/components/TableTable.vue
@@ -30,6 +30,29 @@
<BBTableCell class="w-16">
{{ humanizeTs(table.lastSuccessfulSyncTs) }}
</BBTableCell>
+ <BBTableCell v-if="showConsoleLink" class="w-4">
+ <button
+ class="btn-icon"
+ @click.stop="
+ window.open(consoleLink(table.database.name, table.name), '_blank')
+ "
+ >
+ <svg
+ class="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
+ ></path>
+ </svg>
+ </button>
+ </BBTableCell>
</template>
</BBTable>
</template>
@@ -38,8 +61,14 @@
import { computed, PropType } from "vue";
import { BBTableColumn } from "../bbkit/types";
import { Table } from "../types";
-import { bytesToString, databaseSlug } from "../utils";
+import {
+ bytesToString,
+ databaseSlug,
+ databaseTableConsoleLink,
+} from "../utils";
import { useRouter } from "vue-router";
+import { isEmpty } from "lodash";
+import { useStore } from "vuex";
type Mode = "TABLE" | "VIEW";
@@ -100,12 +129,37 @@ export default {
},
},
setup(props, ctx) {
+ const store = useStore();
const router = useRouter();
const columnList = computed(() => {
- return columnListMap.get(props.mode);
+ const list = columnListMap.get(props.mode);
+ if (showConsoleLink.value) {
+ list?.push({ title: "SQL console" });
+ }
+
+ return list;
});
+ const showConsoleLink = computed(() => {
+ if (props.mode != "TABLE") {
+ return false;
+ }
+
+ const consoleURL =
+ store.getters["setting/settingByName"]("bb.console.table").value;
+ return !isEmpty(consoleURL);
+ });
+
+ const consoleLink = (databaseName: string, tableName: string) => {
+ const consoleURL =
+ store.getters["setting/settingByName"]("bb.console.table").value;
+ if (!isEmpty(consoleURL)) {
+ return databaseTableConsoleLink(consoleURL, databaseName, tableName);
+ }
+ return "";
+ };
+
const clickTable = (section: number, row: number) => {
const table = props.tableList[row];
router.push(`/db/${databaseSlug(table.database)}/table/${table.name}`);
@@ -113,6 +167,8 @@ export default {
return {
columnList,
+ showConsoleLink,
+ consoleLink,
bytesToString,
clickTable,
};
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index e671e3776c..b0e8e42b9e 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -124,6 +124,7 @@ axios.interceptors.response.use(
// We use finally because we always want to mount the app regardless of the error.
Promise.all([
store.dispatch("actuator/fetchInfo"),
+ store.dispatch("setting/fetchSetting"),
store.dispatch("plan/fetchCurrentPlan"),
store.dispatch("auth/restoreUser"),
]).finally(() => {
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 1276b9659d..31af8e5bc7 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -250,7 +250,7 @@ const routes: Array<RouteRecordRaw> = [
{
path: "general",
name: "setting.workspace.general",
- meta: { title: () => "Account General" },
+ meta: { title: () => "General" },
component: () => import("../views/SettingWorkspaceGeneral.vue"),
props: true,
},
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 9314088bf5..04959b7b5f 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -23,6 +23,7 @@ import project from "./modules/project";
import repository from "./modules/repository";
// Following states are only stored in memory
import router from "./modules/router";
+import setting from "./modules/setting";
import sql from "./modules/sql";
import stage from "./modules/stage";
import table from "./modules/table";
@@ -56,6 +57,7 @@ export const store: Store<any> = createStore({
project,
repository,
router,
+ setting,
sql,
stage,
table,
diff --git a/frontend/src/store/modules/setting.ts b/frontend/src/store/modules/setting.ts
new file mode 100644
index 0000000000..1f8fdbc4fc
--- /dev/null
+++ b/frontend/src/store/modules/setting.ts
@@ -0,0 +1,81 @@
+import axios from "axios";
+import { ResourceObject, SettingState } from "../../types";
+import { Setting, SettingName } from "../../types/setting";
+
+function convert(setting: ResourceObject, rootGetters: any): Setting {
+ return {
+ ...(setting.attributes as Omit<Setting, "id">),
+ id: parseInt(setting.id),
+ };
+}
+
+const state: () => SettingState = () => ({
+ settingByName: new Map(),
+});
+
+const getters = {
+ settingByName:
+ (state: SettingState) =>
+ (name: SettingName): Setting | undefined => {
+ return state.settingByName.get(name);
+ },
+};
+
+const actions = {
+ async fetchSetting({ commit, rootGetters }: any): Promise<Setting[]> {
+ const settingList = (await axios.get(`/api/setting`)).data.data.map(
+ (setting: ResourceObject) => {
+ return convert(setting, rootGetters);
+ }
+ );
+ for (const setting of settingList) {
+ commit("setSettingByName", { name: setting.name, setting });
+ }
+ return settingList;
+ },
+
+ async updateSettingByName(
+ { commit, rootGetters }: any,
+ { name, value }: { name: SettingName; value: string }
+ ): Promise<Setting> {
+ const data = (
+ await axios.patch(`/api/setting/${name}`, {
+ data: {
+ type: "settingPatch",
+ attributes: {
+ value,
+ },
+ },
+ })
+ ).data.data;
+
+ const setting = convert(data, rootGetters);
+
+ commit("setSettingByName", { name: setting.name, setting });
+
+ return setting;
+ },
+};
+
+const mutations = {
+ setSettingByName(
+ state: SettingState,
+ {
+ name,
+ setting,
+ }: {
+ name: SettingName;
+ setting: Setting;
+ }
+ ) {
+ state.settingByName.set(name, setting);
+ },
+};
+
+export default {
+ namespaced: true,
+ state,
+ getters,
+ actions,
+ mutations,
+};
diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.ts
index 8fb1cd3917..9c665d8e22 100644
--- a/frontend/src/types/id.ts
+++ b/frontend/src/types/id.ts
@@ -9,6 +9,8 @@ export type PrincipalId = IdType;
export type MemberId = IdType;
+export type SettingId = IdType;
+
export type BookmarkId = IdType;
export type ProjectId = IdType;
diff --git a/frontend/src/types/setting.ts b/frontend/src/types/setting.ts
new file mode 100644
index 0000000000..2a6e875e8c
--- /dev/null
+++ b/frontend/src/types/setting.ts
@@ -0,0 +1,19 @@
+import { SettingId } from "./id";
+import { Principal } from "./principal";
+
+export type SettingName = "bb.console.database" | "bb.console.table";
+
+export type Setting = {
+ id: SettingId;
+
+ // Standard fields
+ creator: Principal;
+ createdTs: number;
+ updater: Principal;
+ updatedTs: number;
+
+ // Domain specific fields
+ name: SettingName;
+ value: string;
+ description: string;
+};
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index 1a30728c22..6f3cc3074c 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -25,6 +25,7 @@ import { PlanType } from "./plan";
import { Principal } from "./principal";
import { Project } from "./project";
import { Repository } from "./repository";
+import { Setting, SettingName } from "./setting";
import { Table } from "./table";
import { VCS } from "./vcs";
@@ -36,6 +37,10 @@ export interface AuthState {
currentUser: Principal;
}
+export interface SettingState {
+ settingByName: Map<SettingName, Setting>;
+}
+
export interface PlanState {
plan: PlanType;
}
diff --git a/frontend/src/utils/database.ts b/frontend/src/utils/database.ts
index 368bfd689b..1ca7c1ea3f 100644
--- a/frontend/src/utils/database.ts
+++ b/frontend/src/utils/database.ts
@@ -1,4 +1,3 @@
-
import {
Database,
DataSourceMember,
@@ -70,3 +69,24 @@ export function sortDatabaseList(
return bEnvIndex - aEnvIndex;
});
}
+
+// templateURL corresponds to the "bb.console.database" setting.
+// This method replaces {{DB_NAME}} with the actual database/table name.
+export function databaseConsoleLink(
+ templateURL: string,
+ databaseName: string
+): string {
+ return templateURL.replace("{{DB_NAME}}", databaseName);
+}
+
+// templateURL corresponds to the "bb.console.table" setting.
+// This method replaces {{DB_NAME}}/{{TABLE_NAME}} with the actual database/table name.
+export function databaseTableConsoleLink(
+ templateURL: string,
+ databaseName: string,
+ tableName: string
+): string {
+ return templateURL
+ .replace("{{DB_NAME}}", databaseName)
+ .replace("{{TABLE_NAME}}", tableName);
+}
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index 0b75910a6a..db1d7fae23 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -70,6 +70,31 @@
{{ projectName(database.project) }}
</router-link>
</dd>
+ <dd
+ v-if="consoleLink.length > 0"
+ class="flex items-center text-sm md:mr-4"
+ >
+ <span class="textlabel">SQL Console</span>
+ <button
+ class="ml-1 btn-icon"
+ @click.prevent="window.open(urlfy(consoleLink), '_blank')"
+ >
+ <svg
+ class="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
+ ></path>
+ </svg>
+ </button>
+ </dd>
</dl>
</div>
<button
@@ -349,7 +374,12 @@ import TableTable from "../components/TableTable.vue";
import MigrationHistoryTable from "../components/MigrationHistoryTable.vue";
import MemberSelect from "../components/MemberSelect.vue";
import ProjectSelect from "../components/ProjectSelect.vue";
-import { idFromSlug, instanceSlug, isDBAOrOwner } from "../utils";
+import {
+ databaseConsoleLink,
+ idFromSlug,
+ instanceSlug,
+ isDBAOrOwner,
+} from "../utils";
import {
DataSource,
ProjectId,
@@ -359,7 +389,7 @@ import {
MigrationSchemaStatus,
InstanceMigration,
} from "../types";
-import { cloneDeep, isEqual } from "lodash";
+import { cloneDeep, isEmpty, isEqual } from "lodash";
interface LocalState {
editingDataSource?: DataSource;
@@ -427,6 +457,16 @@ export default {
watchEffect(prepareMigrationHistoryList);
+ const consoleLink = computed(() => {
+ const consoleURL = store.getters["setting/settingByName"](
+ "bb.console.database"
+ ).value;
+ if (!isEmpty(consoleURL)) {
+ return databaseConsoleLink(consoleURL, database.value.name, "");
+ }
+ return "";
+ });
+
const hasDataSourceFeature = computed(() =>
store.getters["plan/feature"]("bb.data-source")
);
@@ -585,6 +625,7 @@ export default {
tableList,
attentionTitle,
migrationHistoryList,
+ consoleLink,
hasDataSourceFeature,
allowChangeProject,
allowViewDataSource,
diff --git a/frontend/src/views/SettingSidebar.vue b/frontend/src/views/SettingSidebar.vue
index c7245f8ab8..8661e6af45 100644
--- a/frontend/src/views/SettingSidebar.vue
+++ b/frontend/src/views/SettingSidebar.vue
@@ -24,7 +24,8 @@
h-6
w-6
text-gray-500
- group-hover:text-gray-500 group-focus:text-gray-600
+ group-hover:text-gray-500
+ group-focus:text-gray-600
"
fill="none"
viewBox="0 0 24 24"
@@ -109,12 +110,12 @@
Workspace
</div>
<div class="space-y-1">
- <!-- <router-link
+ <router-link
to="/setting/general"
class="outline-item group w-full flex items-center pl-11 pr-2 py-2"
>
General
- </router-link> -->
+ </router-link>
<!-- <router-link
to="/setting/agent"
class="outline-item group w-full flex items-center pl-11 pr-2 py-2"
diff --git a/frontend/src/views/SettingWorkspaceGeneral.vue b/frontend/src/views/SettingWorkspaceGeneral.vue
index 107e5494fa..92ae3e2edd 100644
--- a/frontend/src/views/SettingWorkspaceGeneral.vue
+++ b/frontend/src/views/SettingWorkspaceGeneral.vue
@@ -1,11 +1,156 @@
<template>
- <h1>General</h1>
+ <div class="mt-2 space-y-8 divide-y divide-gray-200">
+ <div>
+ <h3 class="text-lg leading-6 font-medium text-main">SQL Console</h3>
+ <p class="mt-1 text-sm text-control-light">
+ If your team use a separate SQL console such as phpMyAdmin, you can
+ provide its URL pattern here, so that Bytebase can surface the console
+ link on the relevant database and table UI.
+ <a
+ href="https://docs.bytebase.com/settings/external-sql-console"
+ target="_blank"
+ class="normal-link"
+ >
+ detailed guide</a
+ >
+ </p>
+
+ <div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
+ <div class="sm:col-span-6">
+ <label for="databaseURL" class="textlabel"> Database URL </label>
+ <label for="databaseURL" class="textinfolabel">
+ use {{ DB_NAME_PLACEHOLDER }} as the placeholder for the actual
+ database name
+ </label>
+ <div class="mt-1">
+ <input
+ type="text"
+ id="databaseURL"
+ placeholder="http://phpmyadmin.example.com:8080/index.php?route=/database/sql&db={{DB_NAME}}"
+ autocomplete="off"
+ class="w-full textfield"
+ :disabled="!allowEdit"
+ v-model="state.databaseConsoleURL"
+ />
+ </div>
+ </div>
+ </div>
+ <div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
+ <div class="sm:col-span-6">
+ <label for="tableURL" class="textlabel"> Table URL </label>
+ <label for="databaseURL" class="textinfolabel">
+ use {{ DB_NAME_PLACEHOLDER }} and {{ TABLE_NAME_PLACEHOLDER }} as
+ the placeholder for the actual database and table name
+ </label>
+ <div class="mt-1">
+ <input
+ type="text"
+ id="tableURL"
+ placeholder="http://phpmyadmin.example.com:8080/index.php?route=/table/sql&db={{DB_NAME}}&table={{TABLE_NAME}}"
+ autocomplete="off"
+ class="w-full textfield"
+ :disabled="!allowEdit"
+ v-model="state.tableConsoleURL"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div v-if="allowEdit" class="pt-5 flex justify-end">
+ <button
+ type="button"
+ class="btn-primary"
+ :disabled="!allowSave"
+ @click.prevent="doSave"
+ >
+ Update
+ </button>
+ </div>
+ </div>
</template>
<script lang="ts">
+import { computed, reactive } from "@vue/runtime-core";
+import { useStore } from "vuex";
+import { isOwner } from "../utils";
+import { Setting } from "../types/setting";
+
+const DB_NAME_PLACEHOLDER = "{{DB_NAME}}";
+const TABLE_NAME_PLACEHOLDER = "{{TABLE_NAME}}";
+
+interface LocalState {
+ databaseConsoleURL: string;
+ tableConsoleURL: string;
+}
+
export default {
name: "SettingWorkspaceGeneral",
props: {},
- setup(props, ctx) {},
+ setup(props, ctx) {
+ const store = useStore();
+
+ const state = reactive<LocalState>({
+ databaseConsoleURL: store.getters["setting/settingByName"](
+ "bb.console.database"
+ ).value,
+ tableConsoleURL:
+ store.getters["setting/settingByName"]("bb.console.table").value,
+ });
+
+ const currentUser = computed(() => store.getters["auth/currentUser"]());
+
+ const allowEdit = computed((): boolean => {
+ return isOwner(currentUser.value.role);
+ });
+
+ const allowSave = computed((): boolean => {
+ return (
+ state.databaseConsoleURL !=
+ store.getters["setting/settingByName"]("bb.console.database").value ||
+ state.tableConsoleURL !=
+ store.getters["setting/settingByName"]("bb.console.table").value
+ );
+ });
+
+ const doSave = () => {
+ if (
+ state.databaseConsoleURL !=
+ store.getters["setting/settingByName"]("bb.console.database").value
+ ) {
+ store
+ .dispatch("setting/updateSettingByName", {
+ name: "bb.console.database",
+ value: state.databaseConsoleURL,
+ })
+ .then((setting: Setting) => {
+ state.databaseConsoleURL = setting.value;
+ });
+ }
+
+ if (
+ state.tableConsoleURL !=
+ store.getters["setting/settingByName"]("bb.console.table").value
+ ) {
+ store
+ .dispatch("setting/updateSettingByName", {
+ name: "bb.console.table",
+ value: state.tableConsoleURL,
+ })
+ .then((setting: Setting) => {
+ state.tableConsoleURL = setting.value;
+ });
+ }
+ };
+
+ return {
+ state,
+ DB_NAME_PLACEHOLDER,
+ TABLE_NAME_PLACEHOLDER,
+ allowEdit,
+ allowSave,
+ doSave,
+ };
+ },
};
</script>
diff --git a/frontend/src/views/TableDetail.vue b/frontend/src/views/TableDetail.vue
index 837859f105..8964bc0005 100644
--- a/frontend/src/views/TableDetail.vue
+++ b/frontend/src/views/TableDetail.vue
@@ -77,6 +77,31 @@
{{ projectName(database.project) }}
</router-link>
</dd>
+ <dd
+ v-if="consoleLink.length > 0"
+ class="flex items-center text-sm md:mr-4"
+ >
+ <span class="textlabel">SQL Console</span>
+ <button
+ class="ml-1 btn-icon"
+ @click.prevent="window.open(urlfy(consoleLink), '_blank')"
+ >
+ <svg
+ class="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
+ ></path>
+ </svg>
+ </button>
+ </dd>
</dl>
</div>
</div>
@@ -186,7 +211,8 @@ 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";
+import { bytesToString, databaseTableConsoleLink, idFromSlug } from "../utils";
+import { isEmpty } from "lodash";
export default {
name: "TableDetail",
@@ -215,9 +241,23 @@ export default {
return table.value.database;
});
+ const consoleLink = computed(() => {
+ const consoleURL =
+ store.getters["setting/settingByName"]("bb.console.table").value;
+ if (!isEmpty(consoleURL)) {
+ return databaseTableConsoleLink(
+ consoleURL,
+ database.value.name,
+ table.value.name
+ );
+ }
+ return "";
+ });
+
return {
table,
database,
+ consoleLink,
bytesToString,
};
},
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index e9d43c7457..a15a348b55 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -54,4 +54,5 @@ p, DBA, /vcs/{id}, PATCH
p, DBA, /vcs/{id}, DELETE
p, DBA, /vcs/{id}/repository, GET
p, DBA, /plan, GET
-p, DBA, /plan, PATCH
\ No newline at end of file
+p, DBA, /plan, PATCH
+p, DBA, /setting, GET
\ No newline at end of file
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index 869c737be5..3166d07db2 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -45,4 +45,5 @@ p, DEVELOPER, /sql/ping, POST
p, DEVELOPER, /vcs, GET
p, DEVELOPER, /vcs/{id}, GET
p, DEVELOPER, /plan, GET
-p, DEVELOPER, /plan, PATCH
\ No newline at end of file
+p, DEVELOPER, /plan, PATCH
+p, DEVELOPER, /setting, GET
\ No newline at end of file
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index ce1134fc51..7425fb4308 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -58,4 +58,6 @@ p, OWNER, /vcs/{id}, PATCH
p, OWNER, /vcs/{id}, DELETE
p, OWNER, /vcs/{id}/repository, GET
p, OWNER, /plan, GET
-p, OWNER, /plan, PATCH
\ No newline at end of file
+p, OWNER, /plan, PATCH
+p, OWNER, /setting, GET
+p, OWNER, /setting/{name}, PATCH
\ No newline at end of file
diff --git a/server/server.go b/server/server.go
index 770a4197ac..66f7d942d2 100644
--- a/server/server.go
+++ b/server/server.go
@@ -24,6 +24,7 @@ type Server struct {
CacheService api.CacheService
+ SettingService api.SettingService
PrincipalService api.PrincipalService
MemberService api.MemberService
ProjectService api.ProjectService
@@ -143,6 +144,7 @@ func NewServer(logger *zap.Logger, version string, host string, port int, mode s
apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return ACLMiddleware(logger, s, ce, next, readonly)
})
+ s.registerSettingRoutes(apiGroup)
s.registerActuatorRoutes(apiGroup)
s.registerAuthRoutes(apiGroup)
s.registerPrincipalRoutes(apiGroup)
diff --git a/server/setting.go b/server/setting.go
new file mode 100644
index 0000000000..c88ed92524
--- /dev/null
+++ b/server/setting.go
@@ -0,0 +1,89 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "github.com/google/jsonapi"
+ "github.com/labstack/echo/v4"
+)
+
+var (
+ // Some settings contain secret info so we only return settings that are needed by the client.
+ whitelistSettings = []api.SettingName{api.SettingConsoleDatabase, api.SettingConsoleTable}
+)
+
+func (s *Server) registerSettingRoutes(g *echo.Group) {
+ g.GET("/setting", func(c echo.Context) error {
+ find := &api.SettingFind{}
+ list, err := s.SettingService.FindSettingList(context.Background(), find)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch setting list").SetInternal(err)
+ }
+
+ filteredList := []*api.Setting{}
+ for _, setting := range list {
+ for _, whitelist := range whitelistSettings {
+ if setting.Name == whitelist {
+ filteredList = append(filteredList, setting)
+ break
+ }
+ }
+ }
+
+ for _, setting := range filteredList {
+ if err := s.ComposeSettingRelationship(context.Background(), setting); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch setting relationship: %v", setting.Name)).SetInternal(err)
+ }
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, filteredList); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal project list response").SetInternal(err)
+ }
+ return nil
+ })
+
+ g.PATCH("/setting/:name", func(c echo.Context) error {
+ settingPatch := &api.SettingPatch{
+ Name: api.SettingName(c.Param("name")),
+ UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
+ }
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, settingPatch); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update setting request").SetInternal(err)
+ }
+
+ setting, err := s.SettingService.PatchSetting(context.Background(), settingPatch)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Setting name not found: %s", settingPatch.Name))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update setting: %v", settingPatch.Name)).SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, setting); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal setting response").SetInternal(err)
+ }
+ return nil
+ })
+}
+
+func (s *Server) ComposeSettingRelationship(ctx context.Context, setting *api.Setting) error {
+ var err error
+
+ setting.Creator, err = s.ComposePrincipalById(ctx, setting.CreatorId)
+ if err != nil {
+ return err
+ }
+
+ setting.Updater, err = s.ComposePrincipalById(context.Background(), setting.UpdaterId)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index b29fad228d..a30d751d51 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -1,4 +1,7 @@
-- For testing, we reset data on each run
+DELETE FROM
+ setting;
+
DELETE FROM
repo;
diff --git a/store/setting.go b/store/setting.go
index 2329b5709d..ed76b3dff1 100644
--- a/store/setting.go
+++ b/store/setting.go
@@ -30,7 +30,7 @@ func (s *SettingService) CreateSettingIfNotExist(ctx context.Context, create *ap
// We do a find followed by a create if NOT found. Though SQLite supports UPSERT ON CONFLICT DO NOTHING syntax, it doesn't
// support RETURNING in such case. So we have to use separate SELECT and INSERT anyway.
find := &api.SettingFind{
- Name: create.Name,
+ Name: &create.Name,
}
setting, err := s.FindSetting(ctx, find)
if err != nil {
@@ -58,6 +58,21 @@ func (s *SettingService) CreateSettingIfNotExist(ctx context.Context, create *ap
return setting, nil
}
+// FindSettingList retrieves a list of settings based on find.
+func (s *SettingService) FindSettingList(ctx context.Context, find *api.SettingFind) ([]*api.Setting, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := findSettingList(ctx, tx, find)
+ if err != nil {
+ return []*api.Setting{}, err
+ }
+ return list, nil
+}
+
// FindSetting retrieves a single setting based on find.
// Returns ENOTFOUND if no matching record.
// Returns ECONFLICT if finding more than 1 matching records.
@@ -79,6 +94,27 @@ func (s *SettingService) FindSetting(ctx context.Context, find *api.SettingFind)
return list[0], nil
}
+// PatchSetting updates an existing setting by name.
+// Returns ENOTFOUND if setting does not exist.
+func (s *SettingService) PatchSetting(ctx context.Context, patch *api.SettingPatch) (*api.Setting, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ setting, err := patchSetting(ctx, tx, patch)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return setting, nil
+}
+
// createSetting creates a new setting.
func createSetting(ctx context.Context, tx *Tx, create *api.SettingCreate) (*api.Setting, error) {
// Insert row into database.
@@ -120,10 +156,17 @@ func createSetting(ctx context.Context, tx *Tx, create *api.SettingCreate) (*api
func findSettingList(ctx context.Context, tx *Tx, find *api.SettingFind) (_ []*api.Setting, err error) {
// Build WHERE clause.
- where, args := []string{"name = ?"}, []interface{}{find.Name}
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.Name; v != nil {
+ where, args = append(where, "name = ?"), append(args, *v)
+ }
rows, err := tx.QueryContext(ctx, `
- SELECT
+ SELECT
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
name,
value,
description
@@ -141,6 +184,10 @@ func findSettingList(ctx context.Context, tx *Tx, find *api.SettingFind) (_ []*a
for rows.Next() {
var setting api.Setting
if err := rows.Scan(
+ &setting.CreatorId,
+ &setting.CreatedTs,
+ &setting.UpdaterId,
+ &setting.UpdatedTs,
&setting.Name,
&setting.Value,
&setting.Description,
@@ -156,3 +203,45 @@ func findSettingList(ctx context.Context, tx *Tx, find *api.SettingFind) (_ []*a
return list, nil
}
+
+// patchSetting updates a setting by name. Returns the new state of the setting after update.
+func patchSetting(ctx context.Context, tx *Tx, patch *api.SettingPatch) (*api.Setting, error) {
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ set, args = append(set, "value = ?"), append(args, patch.Value)
+
+ args = append(args, patch.Name)
+
+ // Execute update query with RETURNING.
+ row, err := tx.QueryContext(ctx, `
+ UPDATE setting
+ SET `+strings.Join(set, ", ")+`
+ WHERE name = ?
+ RETURNING creator_id, created_ts, updater_id, updated_ts, name, value, description
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ var setting api.Setting
+ if err := row.Scan(
+ &setting.CreatorId,
+ &setting.CreatedTs,
+ &setting.UpdaterId,
+ &setting.UpdatedTs,
+ &setting.Name,
+ &setting.Value,
+ &setting.Description,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &setting, nil
+ }
+
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("setting not found: %s", patch.Name)}
+}