Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(schema-editor): support PostgreSQL database (#4116)
boojack700f14f1cdd9
diff --git a/api/database.go b/api/database.goindex 4c8b80ec5e..e38bce6df6 100644--- a/api/database.go+++ b/api/database.go@@ -129,10 +129,16 @@ type DatabasePatch struct {type DatabaseEdit struct {DatabaseID int `json:"databaseId"`- CreateTableList []*CreateTableContext `json:"createTableList"`- AlterTableList []*AlterTableContext `json:"alterTableList"`- RenameTableList []*RenameTableContext `json:"renameTableList"`- DropTableList []*DropTableContext `json:"dropTableList"`+ CreateSchemaList []*CreateSchemaContext `json:"createSchemaList"`+ CreateTableList []*CreateTableContext `json:"createTableList"`+ AlterTableList []*AlterTableContext `json:"alterTableList"`+ RenameTableList []*RenameTableContext `json:"renameTableList"`+ DropTableList []*DropTableContext `json:"dropTableList"`+}++// CreateSchemaContext is the edit database context to create a schema.+type CreateSchemaContext struct {+ Schema string `json:"schema"`}// CreateTableContext is the edit database context to create a table.@@ -159,6 +165,7 @@ type AlterTableContext struct {ColumnNameList []string `json:"columnNameList"`AddColumnList []*AddColumnContext `json:"addColumnList"`+ AlterColumnList []*AlterColumnContext `json:"alterColumnList"`ChangeColumnList []*ChangeColumnContext `json:"changeColumnList"`DropColumnList []*DropColumnContext `json:"dropColumnList"`// TODO(steven): diff schemas in backend, so we don't need this flag.@@ -193,7 +200,18 @@ type AddColumnContext struct {Default *string `json:"default"`}-// ChangeColumnContext is the alter table context to change a column.+// AlterColumnContext is the alter table context to alter a column.+type AlterColumnContext struct {+ OldName string `json:"oldName"`+ NewName string `json:"newName"`+ Type *string `json:"type"`+ Comment *string `json:"comment"`+ Nullable *bool `json:"nullable"`+ DefaultChanged bool `json:"defaultChanged"`+ Default *string `json:"default"`+}++// ChangeColumnContext is the alter table context to change a column, mainly used in MySQL.type ChangeColumnContext struct {OldName string `json:"oldName"`NewName string `json:"newName"`diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex 3e93e4c8fb..274068e4e5 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -226,11 +226,7 @@ const project = useProjectStore().getProjectById(const isTenantProject = project.tenantMode === "TENANT";onMounted(() => {- if (- databaseList.length === 0 ||- project.id === UNKNOWN_ID ||- databaseEngineType === "unknown"- ) {+ if (databaseList.length === 0 || project.id === UNKNOWN_ID) {emit("close");return;}@@ -295,11 +291,9 @@ const getDatabaseEditListWithSchemaEditor = () => {const originSchema = databaseSchema.originSchemaList.find((schema) => schema.name === schema.name);- if (!originSchema) {- continue;- }const diffSchemaResult = diffSchema(database.id, originSchema, schema);if (+ diffSchemaResult.createSchemaList.length > 0 ||diffSchemaResult.createTableList.length > 0 ||diffSchemaResult.alterTableList.length > 0 ||diffSchemaResult.renameTableList.length > 0 ||@@ -334,10 +328,12 @@ const fetchDatabaseEditStatementMapWithSchemaEditor = async () => {});return;}- databaseEditMap.set(- databaseEdit.databaseId,+ const previousStatement =+ databaseEditMap.get(databaseEdit.databaseId) || "";+ const statement = `${previousStatement}${previousStatement && "\n"}${databaseEditResult.statement- );+ }`;+ databaseEditMap.set(databaseEdit.databaseId, statement);}}return databaseEditMap;diff --git a/frontend/src/components/SchemaEditor/DatabaseTree.vue b/frontend/src/components/SchemaEditor/DatabaseTree.vueindex f87aab327c..3858d19b6d 100644--- a/frontend/src/components/SchemaEditor/DatabaseTree.vue+++ b/frontend/src/components/SchemaEditor/DatabaseTree.vue@@ -45,6 +45,12 @@:table-id="state.tableNameModalContext.tableId"@close="state.tableNameModalContext = undefined"/>++ <SchemaNameModal+ v-if="state.schemaNameModalContext !== undefined"+ :database-id="state.schemaNameModalContext.databaseId"+ @close="state.schemaNameModalContext = undefined"+ /></template><script lang="ts" setup>@@ -117,6 +123,9 @@ interface TreeContextMenu {interface LocalState {shouldRelocateTreeNode: boolean;+ schemaNameModalContext?: {+ databaseId: DatabaseId;+ };tableNameModalContext?: {databaseId: DatabaseId;schemaName: string;@@ -168,11 +177,26 @@ const contextMenuOptions = computed(() => {key: "create-table",label: t("schema-editor.actions.create-table"),});+ } else if (instanceEngine === "POSTGRES") {+ options.push({+ key: "create-schema",+ label: t("schema-editor.actions.create-schema"),+ });}return options;} else if (treeNode.type === "schema") {const options = [];if (instanceEngine === "POSTGRES") {+ const schema = editorStore.databaseSchemaById+ .get(treeNode.databaseId)+ ?.schemaList.find((schema) => schema.name === treeNode.schemaName);+ if (schema?.status === "created") {+ options.push({+ key: "delete-schema",+ label: t("schema-editor.actions.delete-schema"),+ });+ }+options.push({key: "create-table",label: t("schema-editor.actions.create-table"),@@ -383,6 +407,10 @@ watch(if (!expandedKeysRef.value.includes(databaseTreeNodeKey)) {expandedKeysRef.value.push(databaseTreeNodeKey);}+ const schemaTreeNodeKey = `s-${currentTab.databaseId}-${currentTab.schemaName}`;+ if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {+ expandedKeysRef.value.push(schemaTreeNodeKey);+ }const tableTreeNodeKey = `t-${currentTab.databaseId}-${currentTab.tableId}`;selectedKeysRef.value = [tableTreeNodeKey];}@@ -450,7 +478,15 @@ const renderPrefix = ({ option: treeNode }: { option: TreeNode }) => {const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {const additionalClassList: string[] = ["select-none"];- if (treeNode.type === "table") {+ if (treeNode.type === "schema") {+ const schema = editorStore.databaseSchemaById+ .get(treeNode.databaseId)+ ?.schemaList.find((schema) => schema.name === treeNode.schemaName);++ if (schema && schema.status === "created") {+ additionalClassList.push("text-green-700");+ }+ } else if (treeNode.type === "table") {const table = editorStore.databaseSchemaById.get(treeNode.databaseId)?.schemaList.find((schema) => schema.name === treeNode.schemaName)@@ -493,20 +529,23 @@ const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {// Render a 'menu' icon in the right of the nodeconst renderSuffix = ({ option: treeNode }: { option: TreeNode }) => {+ const icon = h(EllipsisIcon, {+ class: "w-4 h-auto text-gray-600",+ onClick: (e) => {+ handleShowDropdown(e, treeNode);+ },+ });+ const instanceEngine = instanceStore.getInstanceById(+ treeNode.instanceId+ ).engine;if (treeNode.type === "database") {- return h(EllipsisIcon, {- class: "w-4 h-auto text-gray-600",- onClick: (e) => {- handleShowDropdown(e, treeNode);- },- });+ return icon;+ } else if (treeNode.type === "schema") {+ if (instanceEngine === "POSTGRES") {+ return icon;+ }} else if (treeNode.type === "table") {- return h(EllipsisIcon, {- class: "w-4 h-auto text-gray-600",- onClick: (e) => {- handleShowDropdown(e, treeNode);- },- });+ return icon;}return null;};@@ -632,6 +671,10 @@ const handleContextMenuDropdownSelect = async (key: string) => {schemaName: "",tableId: undefined,};+ } else if (key === "create-schema") {+ state.schemaNameModalContext = {+ databaseId: treeNode.databaseId,+ };}} else if (treeNode?.type === "schema") {if (key === "create-table") {@@ -641,6 +684,8 @@ const handleContextMenuDropdownSelect = async (key: string) => {schemaName: treeNode.schemaName,tableId: undefined,};+ } else if (key === "delete-schema") {+ editorStore.deleteCreatedSchema(treeNode.databaseId, treeNode.schemaName);}} else if (treeNode?.type === "table") {const table = editorStore.databaseSchemaByIddiff --git a/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue b/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vueindex 52fa760cdd..45b4081632 100644--- a/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue+++ b/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue@@ -4,8 +4,22 @@class="shadow-inner outline outline-gray-200"@close="dismissModal">+ <div v-if="shouldShowSchemaSelector" class="w-72">+ <p class="mb-2">{{ $t("schema-editor.select-reference-schema") }}</p>+ <BBSelect+ :selected-item="selectedSchema"+ :item-list="schemaList"+ :placeholder="$t('schema-editor.schema.select')"+ :show-prefix-item="true"+ @select-item="(schema: Schema) => state.referencedSchema = schema.name"+ >+ <template #menuItem="{ item }">+ {{ item.name }}+ </template>+ </BBSelect>+ </div><div class="w-72">- <p class="mb-2">{{ $t("schema-editor.select-reference-table") }}</p>+ <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-table") }}</p><BBSelect:selected-item="selectedTable":item-list="tableList"@@ -60,7 +74,7 @@<script lang="ts" setup>import { isUndefined } from "lodash-es";import { computed, onMounted, PropType, reactive, watch } from "vue";-import { DatabaseId, UNKNOWN_ID } from "@/types";+import { DatabaseId, DatabaseSchema, UNKNOWN_ID } from "@/types";import { useSchemaEditorStore } from "@/store";import {Column,@@ -99,6 +113,12 @@ const emit = defineEmits<{}>();const editorStore = useSchemaEditorStore();+const databaseSchema = editorStore.databaseSchemaById.get(+ props.databaseId+) as DatabaseSchema;+const database = databaseSchema.database;+const databaseEngine = database.instance.engine;+const schemaList = databaseSchema.schemaList;const state = reactive<LocalState>({referencedSchema: props.schemaName,});@@ -125,11 +145,18 @@ const foreignKeyList = computed(() => {);});+const shouldShowSchemaSelector = computed(() => {+ return databaseEngine === "POSTGRES";+});++const selectedSchema = computed(() => {+ return schemaList.find((schema) => schema.name === state.referencedSchema);+});+const tableList = computed(() => {- return (- editorStore.getSchema(props.databaseId, state.referencedSchema || "")- ?.tableList || []- ).filter((table: Table) => table.id !== props.tableId);+ return (selectedSchema.value?.tableList || []).filter(+ (table: Table) => table.id !== props.tableId+ );});const selectedTable = computed(() => {diff --git a/frontend/src/components/SchemaEditor/Modals/SchemaNameModal.vue b/frontend/src/components/SchemaEditor/Modals/SchemaNameModal.vuenew file mode 100644index 0000000000..77bba4b51f--- /dev/null+++ b/frontend/src/components/SchemaEditor/Modals/SchemaNameModal.vue@@ -0,0 +1,100 @@+<template>+ <BBModal+ :title="$t('schema-editor.actions.create-schema')"+ class="shadow-inner outline outline-gray-200"+ @close="dismissModal"+ >+ <div class="w-72">+ <p>{{ $t("schema-editor.schema.name") }}</p>+ <BBTextField+ class="my-2 w-full"+ :required="true"+ :focus-on-mount="true"+ :value="state.schemaName"+ @input="handleSchemaNameChange"+ />+ </div>+ <div class="w-full flex items-center justify-end mt-2 space-x-3 pr-1 pb-1">+ <button type="button" class="btn-normal" @click="dismissModal">+ {{ $t("common.cancel") }}+ </button>+ <button class="btn-primary" @click="handleConfirmButtonClick">+ {{ $t("common.create") }}+ </button>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { PropType, reactive } from "vue";+import { useI18n } from "vue-i18n";+import { DatabaseId, UNKNOWN_ID } from "@/types";+import { useSchemaEditorStore, useNotificationStore } from "@/store";+import { SchemaMetadata } from "@/types/proto/store/database";+import { convertSchemaMetadataToSchema } from "@/types/schemaEditor/atomType";++const schemaNameFieldRegexp = /^\S+$/;++interface LocalState {+ schemaName: string;+}++const props = defineProps({+ databaseId: {+ type: Number as PropType<DatabaseId>,+ default: UNKNOWN_ID,+ },+});++const emit = defineEmits<{+ (event: "close"): void;+}>();++const { t } = useI18n();+const editorStore = useSchemaEditorStore();+const notificationStore = useNotificationStore();+const state = reactive<LocalState>({+ schemaName: "",+});++const handleSchemaNameChange = (event: Event) => {+ state.schemaName = (event.target as HTMLInputElement).value;+};++const handleConfirmButtonClick = async () => {+ if (!schemaNameFieldRegexp.test(state.schemaName)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("schema-editor.message.invalid-schema-name"),+ });+ return;+ }++ const databaseId = props.databaseId;+ const databaseSchema = editorStore.databaseSchemaById.get(databaseId);+ if (!databaseSchema) {+ return;+ }+ const schemaNameList =+ databaseSchema.schemaList.map((schema) => schema.name) || [];+ if (schemaNameList.includes(state.schemaName)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("schema-editor.message.duplicated-schema-name"),+ });+ return;+ }++ const schema = convertSchemaMetadataToSchema(SchemaMetadata.fromPartial({}));+ schema.name = state.schemaName;+ schema.status = "created";+ databaseSchema.schemaList.push(schema);+ dismissModal();+};++const dismissModal = () => {+ emit("close");+};+</script>diff --git a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vueindex f52dd343d2..25fd31c9ca 100644--- a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue+++ b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue@@ -36,13 +36,26 @@<!-- List view --><template v-if="state.selectedTab === 'table-list'"><div class="py-2 w-full flex justify-between items-center space-x-2">- <button- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 rounded text-sm hover:bg-gray-100"- @click="handleCreateNewTable"- >- <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />- {{ $t("schema-editor.actions.create-table") }}- </button>+ <div class="flex flex-row justify-start items-center">+ <div+ v-if="shouldShowSchemaSelector"+ class="ml-2 flex flex-row justify-start items-center mr-3 text-sm"+ >+ <span class="mr-1">Schema:</span>+ <n-select+ v-model:value="state.selectedSchema"+ class="min-w-[8rem]"+ :options="schemaSelectorOptionList"+ />+ </div>+ <button+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 rounded text-sm hover:bg-gray-100"+ @click="handleCreateNewTable"+ >+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ {{ $t("schema-editor.actions.create-table") }}+ </button>+ </div></div><!-- table list --><div@@ -159,8 +172,9 @@</template><script lang="ts" setup>+import { head } from "lodash-es";import { NEllipsis } from "naive-ui";-import { computed, reactive, watch } from "vue";+import { computed, onMounted, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import {generateUniqueTabId,@@ -207,11 +221,14 @@ const state = reactive<LocalState>({statement: "",});const currentTab = editorStore.currentTab as DatabaseTabContext;-const databaseSchema = editorStore.databaseSchemaById.get(- currentTab.databaseId-) as DatabaseSchema;-const database = databaseSchema.database;-const schemaList = databaseSchema.schemaList;+const databaseSchema = computed(() => {+ return editorStore.databaseSchemaById.get(+ currentTab.databaseId+ ) as DatabaseSchema;+});+const database = databaseSchema.value.database;+const databaseEngine = database.instance.engine;+const schemaList = databaseSchema.value.schemaList;const tableList = computed(() => {return (schemaList.find((schema) => schema.name === state.selectedSchema)@@ -219,6 +236,21 @@ const tableList = computed(() => {);});+const shouldShowSchemaSelector = computed(() => {+ return databaseEngine === "POSTGRES";+});++const schemaSelectorOptionList = computed(() => {+ const optionList = [];+ for (const schema of schemaList) {+ optionList.push({+ label: schema.name,+ value: schema.name,+ });+ }+ return optionList;+});+const tableHeaderList = computed(() => {return [{@@ -248,21 +280,23 @@ const tableHeaderList = computed(() => {];});+onMounted(() => {+ state.selectedSchema = head(schemaList)?.name || "";+});+watch(() => state.selectedTab,async () => {if (state.selectedTab === "raw-sql") {state.isFetchingDDL = true;const databaseEditList: DatabaseEdit[] = [];- for (const schema of databaseSchema.schemaList) {- const originSchema = databaseSchema.originSchemaList.find(+ for (const schema of databaseSchema.value.schemaList) {+ const originSchema = databaseSchema.value.originSchemaList.find((schema) => schema.name === schema.name);- if (!originSchema) {- continue;- }const diffSchemaResult = diffSchema(database.id, originSchema, schema);if (+ diffSchemaResult.createSchemaList.length > 0 ||diffSchemaResult.createTableList.length > 0 ||diffSchemaResult.alterTableList.length > 0 ||diffSchemaResult.renameTableList.length > 0 ||@@ -296,6 +330,8 @@ watch(statementList.push(databaseEditResult.statement);}state.statement = statementList.join("\n");+ } else {+ state.statement = "";}state.isFetchingDDL = false;}diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vueindex 83034bd7d9..3f3f726fb1 100644--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue+++ b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue@@ -398,6 +398,7 @@ watch();const databaseEdit: DatabaseEdit = {databaseId: currentTab.databaseId,+ createSchemaList: [],createTableList: diffSchemaResult.createTableList.filter((context) => context.name === table.value.name),diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 4605605244..7202574e46 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1439,6 +1439,8 @@"sync-sql-from-schema-editor": "Sync SQL from Schema Editor","raw-sql": "Raw SQL","actions": {+ "create-schema": "Create Schema",+ "delete-schema": "Delete Schema","create-table": "New table","rename": "Rename","drop-table": "Drop table",@@ -1457,6 +1459,10 @@"collation": "Collation","comment": "Comment"},+ "schema": {+ "select": "Select schema",+ "name": "Schema Name"+ },"table-list": "Table List","table": {"select": "Select table",@@ -1474,6 +1480,8 @@},"nothing-changed": "Nothing changed","message": {+ "invalid-schema-name": "Invalid schema name",+ "duplicated-schema-name": "Duplicated schema name","invalid-table-name": "Invalid table name","duplicated-table-name": "Duplicated table name","invalid-column-name": "Invalid column name",@@ -1486,6 +1494,7 @@},"tenant-mode-tips": "Changes will be applied to all selected tenant databases after clicking \"Preview issue\".","edit-foreign-key": "Edit foreign key",+ "select-reference-schema": "Select a schema to reference to","select-reference-table": "Select a table to reference to","select-reference-column": "Select a column to reference to"},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex de1f5b509f..002cd7f27c 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1439,6 +1439,8 @@"sync-sql-from-schema-editor": "从 Schema 编辑器中同步 SQL","raw-sql": "SQL 语句","actions": {+ "create-schema": "新建 Schema",+ "delete-schema": "删除 Schema","create-table": "新建表","rename": "重命名","drop-table": "删除表",@@ -1458,6 +1460,10 @@"collation": "字符排序规则","comment": "注释"},+ "schema": {+ "select": "选择 schema",+ "name": "Schema 名称"+ },"table-list": "表","table": {"select": "选择表",@@ -1475,6 +1481,8 @@},"nothing-changed": "无任何改动","message": {+ "invalid-schema-name": "无效的 Schema 名称",+ "duplicated-schema-name": "重复的 Schema 名称","invalid-table-name": "无效的表名","duplicated-table-name": "重复的表名","invalid-column-name": "无效的列名",@@ -1487,6 +1495,7 @@},"tenant-mode-tips": "点击“预览工单”后,当前更改将会应用于所有选定的租户数据库。","edit-foreign-key": "修改外键",+ "select-reference-schema": "选择外键的 Schema","select-reference-table": "选择外键的表","select-reference-column": "选择外键的列"},diff --git a/frontend/src/store/modules/schemaEditor.ts b/frontend/src/store/modules/schemaEditor.tsindex 8d64322bcd..d18c586fe7 100644--- a/frontend/src/store/modules/schemaEditor.ts+++ b/frontend/src/store/modules/schemaEditor.ts@@ -185,6 +185,16 @@ export const useSchemaEditorStore = defineStore("SchemaEditor", {return this.databaseSchemaById.get(databaseId)!.schemaList;},+ // We only allow to delete the new created schema.+ deleteCreatedSchema(databaseId: DatabaseId, schemaName: string) {+ const databaseSchema = this.databaseSchemaById.get(databaseId);+ if (databaseSchema) {+ databaseSchema.schemaList =+ this.databaseSchemaById+ .get(databaseId)+ ?.schemaList.filter((schema) => schema.name !== schemaName) || [];+ }+ },getSchema(databaseId: DatabaseId, schemaName: string) {return this.databaseSchemaById.get(databaseId)diff --git a/frontend/src/types/schemaEditor/index.ts b/frontend/src/types/schemaEditor/index.tsindex 750b696cfc..79c0d226e5 100644--- a/frontend/src/types/schemaEditor/index.ts+++ b/frontend/src/types/schemaEditor/index.ts@@ -46,13 +46,19 @@ export interface SchemaEditorState {export interface DatabaseEdit {databaseId: DatabaseId;+ createSchemaList: CreateSchemaContext[];createTableList: CreateTableContext[];alterTableList: AlterTableContext[];renameTableList: RenameTableContext[];dropTableList: DropTableContext[];}+export interface CreateSchemaContext {+ schema: string;+}+export interface CreateTableContext {+ schema: string;name: string;engine: string;characterSet: string;@@ -65,9 +71,11 @@ export interface CreateTableContext {}export interface AlterTableContext {+ schema: string;name: string;addColumnList: AddColumnContext[];+ alterColumnList: AlterColumnContext[];changeColumnList: ChangeColumnContext[];dropColumnList: DropColumnContext[];dropPrimaryKey: boolean;@@ -78,11 +86,13 @@ export interface AlterTableContext {}export interface RenameTableContext {+ schema: string;oldName: string;newName: string;}export interface DropTableContext {+ schema: string;name: string;}@@ -96,6 +106,16 @@ export interface AddColumnContext {default?: string;}+export interface AlterColumnContext {+ oldName: string;+ newName: string;+ type?: string;+ comment?: string;+ nullable?: boolean;+ defaultChanged: boolean;+ default?: string;+}+export interface ChangeColumnContext {oldName: string;newName: string;diff --git a/frontend/src/utils/schemaEditor/diffColumn.test.ts b/frontend/src/utils/schemaEditor/diffColumn.test.tsindex 1af5f80549..ae789889cc 100644--- a/frontend/src/utils/schemaEditor/diffColumn.test.ts+++ b/frontend/src/utils/schemaEditor/diffColumn.test.ts@@ -3,6 +3,7 @@ import {AddColumnContext,DropColumnContext,ChangeColumnContext,+ AlterColumnContext,} from "@/types";import { Column } from "@/types/schemaEditor/atomType";import { diffColumnList } from "./diffColumn";@@ -13,6 +14,7 @@ it("diff add column list", () => {columnList: Column[];wanted: {addColumnList: AddColumnContext[];+ alterColumnList: AlterColumnContext[];changeColumnList: ChangeColumnContext[];dropColumnList: DropColumnContext[];};@@ -41,6 +43,7 @@ it("diff add column list", () => {default: undefined,},],+ alterColumnList: [],changeColumnList: [],dropColumnList: [],},@@ -59,6 +62,7 @@ it("diff modify column list", () => {columnList: Column[];wanted: {addColumnList: AddColumnContext[];+ alterColumnList: AlterColumnContext[];changeColumnList: ChangeColumnContext[];dropColumnList: DropColumnContext[];};@@ -86,6 +90,15 @@ it("diff modify column list", () => {],wanted: {addColumnList: [],+ alterColumnList: [+ {+ oldName: "id",+ newName: "id",+ type: "varchar",+ nullable: false,+ defaultChanged: false,+ },+ ],changeColumnList: [{oldName: "id",@@ -115,6 +128,7 @@ it("diff drop column list", () => {columnList: Column[];wanted: {addColumnList: AddColumnContext[];+ alterColumnList: AlterColumnContext[];changeColumnList: ChangeColumnContext[];dropColumnList: DropColumnContext[];};@@ -141,6 +155,7 @@ it("diff drop column list", () => {],wanted: {addColumnList: [],+ alterColumnList: [],changeColumnList: [],dropColumnList: [{diff --git a/frontend/src/utils/schemaEditor/diffColumn.ts b/frontend/src/utils/schemaEditor/diffColumn.tsindex fb66b28c2d..e407e4cd91 100644--- a/frontend/src/utils/schemaEditor/diffColumn.ts+++ b/frontend/src/utils/schemaEditor/diffColumn.ts@@ -3,6 +3,7 @@ import type {AddColumnContext,DropColumnContext,ChangeColumnContext,+ AlterColumnContext,} from "@/types";import { Column } from "@/types/schemaEditor/atomType";import {@@ -24,6 +25,7 @@ export const diffColumnList = (addColumnContextList.push(transformColumnToAddColumnContext(column));}+ const alterColumnContextList: AlterColumnContext[] = [];const changeColumnContextList: ChangeColumnContext[] = [];const changedColumnList = columnList.filter((column) => column.status === "normal"@@ -39,6 +41,26 @@ export const diffColumnList = (changeColumnContextList.push(transformColumnToChangeColumnContext(originColumn, column));++ const alterColumnContext: AlterColumnContext = {+ oldName: originColumn.name,+ newName: column.name,+ defaultChanged: false,+ };+ if (!isEqual(originColumn.type, column.type)) {+ alterColumnContext.type = column.type;+ }+ if (!isEqual(originColumn.comment, column.comment)) {+ alterColumnContext.comment = column.comment;+ }+ if (!isEqual(originColumn.nullable, column.nullable)) {+ alterColumnContext.nullable = column.nullable;+ }+ if (!isEqual(originColumn.default, column.default)) {+ alterColumnContext.defaultChanged = true;+ alterColumnContext.default = column.default;+ }+ alterColumnContextList.push(alterColumnContext);}}@@ -57,6 +79,7 @@ export const diffColumnList = (return {addColumnList: addColumnContextList,+ alterColumnList: alterColumnContextList,changeColumnList: changeColumnContextList,dropColumnList: dropColumnContextList,};diff --git a/frontend/src/utils/schemaEditor/diffSchema.ts b/frontend/src/utils/schemaEditor/diffSchema.tsindex 24393cdb86..f5adc5dec3 100644--- a/frontend/src/utils/schemaEditor/diffSchema.ts+++ b/frontend/src/utils/schemaEditor/diffSchema.ts@@ -1,6 +1,7 @@import { useSchemaEditorStore } from "@/store";import {AlterTableContext,+ CreateSchemaContext,CreateTableContext,DatabaseId,DropTableContext,@@ -13,16 +14,26 @@ import { transformTableToCreateTableContext } from "./transform";export const diffSchema = (databaseId: DatabaseId,- originSchema: Schema,+ originSchema: Schema | undefined,schema: Schema) => {const editorStore = useSchemaEditorStore();+ const createSchemaContextList: CreateSchemaContext[] = [];+ if (schema.status === "created") {+ createSchemaContextList.push({+ schema: schema.name,+ });+ }+const createTableContextList: CreateTableContext[] = [];const createdTableList = schema.tableList.filter((table) => table.status === "created");for (const table of createdTableList) {- const createTableContext = transformTableToCreateTableContext(table);+ const createTableContext = transformTableToCreateTableContext(+ schema.name,+ table+ );const diffColumnListResult = diffColumnList([], table.columnList);createTableContext.addColumnList = diffColumnListResult.addColumnList;for (const columnId of table.primaryKey.columnIdList) {@@ -77,7 +88,7 @@ export const diffSchema = ((table) => table.status === "normal");for (const table of changedTableList) {- const originTable = originSchema.tableList.find(+ const originTable = originSchema?.tableList.find((originTable) => originTable.id === table.id);if (!originTable) {@@ -86,7 +97,7 @@ export const diffSchema = (const originPrimaryKey = originTable.primaryKey;const primaryKey = table.primaryKey;- const originForeignKeyList = originSchema.foreignKeyList.filter(+ const originForeignKeyList = originSchema?.foreignKeyList.filter((fk) => fk.tableId === table.id);const foreignKeyList = schema.foreignKeyList.filter(@@ -100,6 +111,7 @@ export const diffSchema = () {if (originTable.name !== table.name) {renameTableContextList.push({+ schema: schema.name,oldName: originTable.name,newName: table.name,});@@ -117,6 +129,7 @@ export const diffSchema = (columnListDiffResult.dropColumnList.length > 0) {const alterTableContext: AlterTableContext = {+ schema: schema.name,name: table.name,...columnListDiffResult,dropPrimaryKey: false,@@ -166,7 +179,7 @@ export const diffSchema = (// Compose foreign key changes.if (!isEqual(originForeignKeyList, foreignKeyList)) {for (const foreignKey of foreignKeyList) {- const originForeignKey = originForeignKeyList.find(+ const originForeignKey = originForeignKeyList?.find((fk) => fk.name === foreignKey.name);@@ -238,11 +251,13 @@ export const diffSchema = ();for (const table of droppedTableList) {dropTableContextList.push({+ schema: schema.name,name: table.name,});}return {+ createSchemaList: createSchemaContextList,createTableList: createTableContextList,alterTableList: alterTableContextList,renameTableList: renameTableContextList,diff --git a/frontend/src/utils/schemaEditor/index.ts b/frontend/src/utils/schemaEditor/index.tsindex b4a080f6e7..a2abe67a8c 100644--- a/frontend/src/utils/schemaEditor/index.ts+++ b/frontend/src/utils/schemaEditor/index.ts@@ -6,6 +6,7 @@ export const allowUsingSchemaEditor = (databaseList: Database[]): boolean => {return databaseList.every((db) => {return (db.instance.engine === "MYSQL" ||+ // TODO(steven): remove release guard later.(isDev() && db.instance.engine === "POSTGRES"));});@@ -24,6 +25,18 @@ export const getDataTypeSuggestionList = (engineType: EngineType = "MYSQL") => {"JSON","VARCHAR(255)",];+ } else if (engineType === "POSTGRES") {+ return [+ "BOOLEAN",+ "CHAR(1)",+ "DATE",+ "INTEGER",+ "JSON",+ "REAL",+ "SERIAL",+ "TEXT",+ "VARCHAR(255)",+ ];}return [];diff --git a/frontend/src/utils/schemaEditor/transform.ts b/frontend/src/utils/schemaEditor/transform.tsindex 7922dcccdf..ee4870a41f 100644--- a/frontend/src/utils/schemaEditor/transform.ts+++ b/frontend/src/utils/schemaEditor/transform.ts@@ -37,9 +37,11 @@ export const transformColumnToChangeColumnContext = (};export const transformTableToCreateTableContext = (+ schema: string,table: Table): CreateTableContext => {return {+ schema,name: defaultTo(table.name, ""),engine: defaultTo(table.engine, ""),collation: defaultTo(table.collation, ""),diff --git a/plugin/parser/edit/pg/deparse.go b/plugin/parser/edit/pg/deparse.goindex 3471360254..453c0cefd9 100644--- a/plugin/parser/edit/pg/deparse.go+++ b/plugin/parser/edit/pg/deparse.go@@ -24,6 +24,12 @@ func (*SchemaEditor) DeparseDatabaseEdit(databaseEdit *api.DatabaseEdit) (stringNodeList: []ast.Node{},StmtList: []string{},}+ for _, createSchemaContext := range databaseEdit.CreateSchemaList {+ err := transformCreateSchemaContext(ctx, createSchemaContext)+ if err != nil {+ return "", err+ }+ }for _, createTableContext := range databaseEdit.CreateTableList {err := transformCreateTableContext(ctx, createTableContext)if err != nil {@@ -55,6 +61,15 @@ func (*SchemaEditor) DeparseDatabaseEdit(databaseEdit *api.DatabaseEdit) (stringreturn strings.Join(stmtList, "\n"), nil}+func transformCreateSchemaContext(ctx *DeparseContext, createSchemaContext *api.CreateSchemaContext) error {+ createSchemaStmt := &ast.CreateSchemaStmt{+ Name: createSchemaContext.Schema,+ IfNotExists: true,+ }+ ctx.NodeList = append(ctx.NodeList, createSchemaStmt)+ return nil+}+func transformCreateTableContext(ctx *DeparseContext, createTableContext *api.CreateTableContext) error {table := ast.TableDef{Type: ast.TableTypeBaseTable,@@ -76,7 +91,7 @@ func transformCreateTableContext(ctx *DeparseContext, createTableContext *api.Cr// TODO(steven): remove this after our pg parser supports comment stmt.if addColumnContext.Comment != "" {- commemtStmt := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", table.Name, columnDef.ColumnName, addColumnContext.Comment)+ commemtStmt := fmt.Sprintf(`COMMENT ON COLUMN "%s"."%s"."%s" IS '%s';`, createTableContext.Schema, table.Name, columnDef.ColumnName, addColumnContext.Comment)ctx.StmtList = append(ctx.StmtList, commemtStmt)}}@@ -143,55 +158,66 @@ func transformAlterTableContext(ctx *DeparseContext, alterTableContext *api.AlteColumnList: []*ast.ColumnDef{columnDef},})if addColumnContext.Comment != "" {- commemtStmt := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", table.Name, columnDef.ColumnName, addColumnContext.Comment)+ commemtStmt := fmt.Sprintf(`COMMENT ON COLUMN "%s"."%s"."%s" IS '%s';`, table.Schema, table.Name, columnDef.ColumnName, addColumnContext.Comment)ctx.StmtList = append(ctx.StmtList, commemtStmt)}}- for _, changeColumnContext := range alterTableContext.ChangeColumnList {- if changeColumnContext.OldName != changeColumnContext.NewName {- alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.RenameColumnStmt{+ for _, alterColumnContext := range alterTableContext.AlterColumnList {+ if alterColumnContext.OldName != alterColumnContext.NewName {+ renameColumnStmt := &ast.AlterTableStmt{+ Table: table,+ AlterItemList: []ast.Node{},+ }+ renameColumnStmt.AlterItemList = append(renameColumnStmt.AlterItemList, &ast.RenameColumnStmt{Table: table,- ColumnName: changeColumnContext.OldName,- NewName: changeColumnContext.NewName,+ ColumnName: alterColumnContext.OldName,+ NewName: alterColumnContext.NewName,})+ ctx.NodeList = append(ctx.NodeList, renameColumnStmt)}- columnType, err := transformColumnType(changeColumnContext.Type)- if err != nil {- return errors.Wrap(err, "failed to transform column type")- }- alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.AlterColumnTypeStmt{- Table: table,- ColumnName: changeColumnContext.NewName,- Type: columnType,- })- if changeColumnContext.Nullable {- alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropNotNullStmt{- Table: table,- ColumnName: changeColumnContext.NewName,- })- } else {- alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.SetNotNullStmt{+ if alterColumnContext.Type != nil {+ columnType, err := transformColumnType(*alterColumnContext.Type)+ if err != nil {+ return errors.Wrap(err, "failed to transform column type")+ }+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.AlterColumnTypeStmt{Table: table,- ColumnName: changeColumnContext.NewName,+ ColumnName: alterColumnContext.NewName,+ Type: columnType,})}- if changeColumnContext.Default == nil {- alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropDefaultStmt{- Table: table,- ColumnName: changeColumnContext.NewName,- })- } else {- expression := ast.UnconvertedExpressionDef{}- expression.SetText(*changeColumnContext.Default)- alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.SetDefaultStmt{- Table: table,- ColumnName: changeColumnContext.NewName,- Expression: &expression,- })+ if alterColumnContext.Nullable != nil {+ if *alterColumnContext.Nullable {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropNotNullStmt{+ Table: table,+ ColumnName: alterColumnContext.NewName,+ })+ } else {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.SetNotNullStmt{+ Table: table,+ ColumnName: alterColumnContext.NewName,+ })+ }+ }+ if alterColumnContext.DefaultChanged {+ if alterColumnContext.Default == nil {+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.DropDefaultStmt{+ Table: table,+ ColumnName: alterColumnContext.NewName,+ })+ } else {+ expression := ast.UnconvertedExpressionDef{}+ expression.SetText(*alterColumnContext.Default)+ alterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &ast.SetDefaultStmt{+ Table: table,+ ColumnName: alterColumnContext.NewName,+ Expression: &expression,+ })+ }}- if changeColumnContext.Comment != "" {- commemtStmt := fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", table.Name, changeColumnContext.NewName, changeColumnContext.Comment)+ if alterColumnContext.Comment != nil {+ commemtStmt := fmt.Sprintf(`COMMENT ON COLUMN "%s"."%s"."%s" IS '%s';`, table.Schema, table.Name, alterColumnContext.NewName, *alterColumnContext.Comment)ctx.StmtList = append(ctx.StmtList, commemtStmt)}}@@ -249,7 +275,9 @@ func transformAlterTableContext(ctx *DeparseContext, alterTableContext *api.AltealterTableStmt.AlterItemList = append(alterTableStmt.AlterItemList, &addConstraintSmt)}- ctx.NodeList = append(ctx.NodeList, alterTableStmt)+ if len(alterTableStmt.AlterItemList) != 0 {+ ctx.NodeList = append(ctx.NodeList, alterTableStmt)+ }return nil}diff --git a/plugin/parser/edit/pg/deparse_test.go b/plugin/parser/edit/pg/deparse_test.goindex 8be48fc931..0fcb6f65f6 100644--- a/plugin/parser/edit/pg/deparse_test.go+++ b/plugin/parser/edit/pg/deparse_test.go@@ -23,6 +23,11 @@ func TestDeparseCreateTable(t *testing.T) {name: "create table t1",databaseEdit: &api.DatabaseEdit{DatabaseID: api.UnknownID,+ CreateSchemaList: []*api.CreateSchemaContext{+ {+ Schema: "public",+ },+ },CreateTableList: []*api.CreateTableContext{{Schema: "public",@@ -38,7 +43,7 @@ func TestDeparseCreateTable(t *testing.T) {},},},- want: "CREATE TABLE \"public\".\"t1\" (\n \"id\" integer DEFAULT 0 NOT NULL\n);\nCOMMENT ON COLUMN t1.id IS 'ID';",+ want: "CREATE SCHEMA IF NOT EXISTS \"public\";\nCREATE TABLE \"public\".\"t1\" (\n \"id\" integer DEFAULT 0 NOT NULL\n);\nCOMMENT ON COLUMN \"public\".\"t1\".\"id\" IS 'ID';",},{name: "create table t1",@@ -77,7 +82,7 @@ func TestDeparseCreateTable(t *testing.T) {}func TestDeparseAlterTable(t *testing.T) {- var defaultValue = "0"+ var defaultType = "TEXT"tests := []struct {name string@@ -85,41 +90,41 @@ func TestDeparseAlterTable(t *testing.T) {want string}{{- name: "alter table t1 and add column id, id_card",+ name: "alter table t1",databaseEdit: &api.DatabaseEdit{DatabaseID: api.UnknownID,AlterTableList: []*api.AlterTableContext{{Name: "t1",- AddColumnList: []*api.AddColumnContext{+ AlterColumnList: []*api.AlterColumnContext{{- Name: "id",- Type: "int",- },- {- Name: "id_card",- Type: "int",+ OldName: "address",+ NewName: "address",+ Type: &defaultType,},},- DropColumnList: []*api.DropColumnContext{- {- Name: "name",- },- },- ChangeColumnList: []*api.ChangeColumnContext{+ },+ },+ },+ want: "ALTER TABLE \"t1\"\n ALTER COLUMN \"address\" SET DATA TYPE text;",+ },+ {+ name: "alter table t2",+ databaseEdit: &api.DatabaseEdit{+ DatabaseID: api.UnknownID,+ AlterTableList: []*api.AlterTableContext{+ {+ Name: "t2",+ AlterColumnList: []*api.AlterColumnContext{{- OldName: "address",- NewName: "address",- Type: "int",- Nullable: false,- Comment: "Address",- Default: &defaultValue,+ OldName: "address",+ NewName: "home_address",},},},},},- want: "ALTER TABLE \"t1\"\n DROP COLUMN \"name\",\n ADD COLUMN \"id\" integer NOT NULL,\n ADD COLUMN \"id_card\" integer NOT NULL,\n ALTER COLUMN \"address\" SET DATA TYPE integer,\n ALTER COLUMN \"address\" SET NOT NULL,\n ALTER COLUMN \"address\" SET DEFAULT 0;\nCOMMENT ON COLUMN t1.address IS 'Address';",+ want: "ALTER TABLE \"t2\"\n RENAME COLUMN \"address\" TO \"home_address\";",},}