create table in multi-schema

This commit is contained in:
Jan Prochazka
2024-09-19 09:24:08 +02:00
parent 55db98fe1b
commit 5f23b29c4e
7 changed files with 44 additions and 24 deletions

View File

@@ -24,11 +24,13 @@ describe('Schema tests', () => {
await baseStructure(conn, driver); await baseStructure(conn, driver);
const structure1 = await driver.analyseFull(conn); const structure1 = await driver.analyseFull(conn);
expect(structure1.schemas.find(x => x.schemaName == 'myschema')).toBeFalsy(); expect(structure1.schemas.find(x => x.schemaName == 'myschema')).toBeFalsy();
const count = structure1.schemas.length;
expect(structure1.tables.length).toEqual(2); expect(structure1.tables.length).toEqual(2);
await runCommandOnDriver(conn, driver, dmp => dmp.createSchema('myschema')); await runCommandOnDriver(conn, driver, dmp => dmp.createSchema('myschema'));
const structure2 = await driver.analyseIncremental(conn, structure1); const structure2 = await driver.analyseIncremental(conn, structure1);
expect(structure2.schemas.find(x => x.schemaName == 'myschema')).toBeTruthy(); expect(structure2.schemas.find(x => x.schemaName == 'myschema')).toBeTruthy();
expect(structure2.tables.length).toEqual(2); expect(structure2.tables.length).toEqual(2);
expect(structure2.schemas.length).toEqual(count + 1);
const structure3 = await driver.analyseIncremental(conn, structure2); const structure3 = await driver.analyseIncremental(conn, structure2);
expect(structure3).toBeNull(); expect(structure3).toBeNull();
@@ -53,6 +55,20 @@ describe('Schema tests', () => {
expect(structure3).toBeNull(); expect(structure3).toBeNull();
}) })
); );
test.each(engines.filter(x => x.supportSchemas).map(engine => [engine.label, engine]))(
'Create table - keep schemas - %s',
testWrapper(async (conn, driver, engine) => {
await baseStructure(conn, driver);
const structure1 = await driver.analyseFull(conn);
const count = structure1.schemas.length;
expect(structure1.tables.length).toEqual(2);
await driver.query(conn, `create table t3 (id int not null primary key)`);
const structure2 = await driver.analyseIncremental(conn, structure1);
expect(structure2.tables.length).toEqual(3);
expect(structure2.schemas.length).toEqual(count);
})
);
}); });
describe('Base analyser test', () => { describe('Base analyser test', () => {

View File

@@ -132,7 +132,10 @@ export class DatabaseAnalyser {
this.modifications = structureModifications; this.modifications = structureModifications;
if (structureUpdated) this.structure = structureUpdated; if (structureUpdated) this.structure = structureUpdated;
logger.info({ modifications: this.modifications }, 'DB modifications detected:'); logger.info({ modifications: this.modifications }, 'DB modifications detected:');
return this.addEngineField(this.mergeAnalyseResult(await this._runAnalysis())); return {
...this.addEngineField(this.mergeAnalyseResult(await this._runAnalysis())),
schemas,
};
} }
mergeAnalyseResult(newlyAnalysed) { mergeAnalyseResult(newlyAnalysed) {

View File

@@ -4,8 +4,6 @@
import FormArgumentList from '../forms/FormArgumentList.svelte'; import FormArgumentList from '../forms/FormArgumentList.svelte';
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import FormProviderCore from '../forms/FormProviderCore.svelte'; import FormProviderCore from '../forms/FormProviderCore.svelte';
import createRef from '../utility/createRef';
import FormSchemaSelect from '../impexp/FormSchemaSelect.svelte';
import FormTextField from '../forms/FormTextField.svelte'; import FormTextField from '../forms/FormTextField.svelte';
import FormSelectField from '../forms/FormSelectField.svelte'; import FormSelectField from '../forms/FormSelectField.svelte';
@@ -39,6 +37,7 @@
<FormProviderCore values={valuesStore}> <FormProviderCore values={valuesStore}>
{#if schemaList?.length > 0} {#if schemaList?.length > 0}
<FormSelectField <FormSelectField
isNative
name="schemaName" name="schemaName"
label="Schema" label="Schema"
options={schemaList.map(x => ({ label: x.schemaName, value: x.schemaName }))} options={schemaList.map(x => ({ label: x.schemaName, value: x.schemaName }))}

View File

@@ -148,6 +148,7 @@ export const loadingPluginStore = writable({
loadingPackageName: null, loadingPackageName: null,
}); });
export const activeDbKeysStore = writableWithStorage({}, 'activeDbKeysStore'); export const activeDbKeysStore = writableWithStorage({}, 'activeDbKeysStore');
export const appliedCurrentSchema = writable<string>(null);
export const currentThemeDefinition = derived([currentTheme, extensions], ([$currentTheme, $extensions]) => export const currentThemeDefinition = derived([currentTheme, extensions], ([$currentTheme, $extensions]) =>
$extensions.themes.find(x => x.themeClassName == $currentTheme) $extensions.themes.find(x => x.themeClassName == $currentTheme)
@@ -311,3 +312,9 @@ appUpdaterActive.subscribe(value => {
appUpdaterActiveValue = value; appUpdaterActiveValue = value;
}); });
export const getAppUpdaterActive = () => appUpdaterActiveValue; export const getAppUpdaterActive = () => appUpdaterActiveValue;
let appliedCurrentSchemaValue = null;
appliedCurrentSchema.subscribe(value => {
appliedCurrentSchemaValue = value;
});
export const getAppliedCurrentSchema = () => appliedCurrentSchemaValue;

View File

@@ -1,7 +1,7 @@
import _ from 'lodash'; import _ from 'lodash';
import openNewTab from '../utility/openNewTab'; import openNewTab from '../utility/openNewTab';
import { findEngineDriver, getConnectionLabel } from 'dbgate-tools'; import { findEngineDriver, getConnectionLabel } from 'dbgate-tools';
import { getExtensions } from '../stores'; import { getAppliedCurrentSchema, getExtensions } from '../stores';
export default function newTable(connection, database) { export default function newTable(connection, database) {
const tooltip = `${getConnectionLabel(connection)}\n${database}`; const tooltip = `${getConnectionLabel(connection)}\n${database}`;
@@ -21,7 +21,7 @@ export default function newTable(connection, database) {
editor: { editor: {
current: { current: {
pureName: 'new_table', pureName: 'new_table',
schemaName: driver?.dialect?.defaultSchemaName, schemaName: getAppliedCurrentSchema() ?? driver?.dialect?.defaultSchemaName,
columns: [ columns: [
{ {
columnName: 'id', columnName: 'id',

View File

@@ -9,34 +9,30 @@
import ConfirmModal from '../modals/ConfirmModal.svelte'; import ConfirmModal from '../modals/ConfirmModal.svelte';
import { runOperationOnDatabase } from '../modals/ConfirmSqlModal.svelte'; import { runOperationOnDatabase } from '../modals/ConfirmSqlModal.svelte';
import InputTextModal from '../modals/InputTextModal.svelte'; import InputTextModal from '../modals/InputTextModal.svelte';
import { appliedCurrentSchema } from '../stores';
export let dbinfo: DatabaseInfo; export let dbinfo: DatabaseInfo;
export let selectedSchema; export let selectedSchema;
export let objectList; export let objectList;
export let onApplySelectedSchema;
export let valueStorageKey; export let valueStorageKey;
export let conid; export let conid;
export let database; export let database;
let appliedSchema;
$: { $: {
if (selectedSchema != null) { if (selectedSchema != null) {
appliedSchema = selectedSchema; $appliedCurrentSchema = selectedSchema;
} else { } else {
const usedSchemas = Object.keys(countBySchema); const usedSchemas = Object.keys(countBySchema);
if (usedSchemas.length == 1) { if (usedSchemas.length == 1) {
appliedSchema = usedSchemas[0]; $appliedCurrentSchema = usedSchemas[0];
} else { } else {
appliedSchema = null; $appliedCurrentSchema = null;
} }
} }
} }
$: onApplySelectedSchema(appliedSchema);
function computeCountBySchema(list) { function computeCountBySchema(list) {
const res = {}; const res = {};
for (const item of list) { for (const item of list) {
@@ -63,18 +59,20 @@
type: 'createSchema', type: 'createSchema',
schemaName: name, schemaName: name,
}); });
if (selectedSchema) {
selectedSchema = name; selectedSchema = name;
}
}, },
}); });
} }
function handleDropSchema() { function handleDropSchema() {
showModal(ConfirmModal, { showModal(ConfirmModal, {
message: `Really drop schema ${appliedSchema}?`, message: `Really drop schema ${$appliedCurrentSchema}?`,
onConfirm: async () => { onConfirm: async () => {
const dbid = { conid, database }; const dbid = { conid, database };
runOperationOnDatabase(dbid, { runOperationOnDatabase(dbid, {
type: 'dropSchema', type: 'dropSchema',
schemaName: appliedSchema, schemaName: $appliedCurrentSchema,
}); });
selectedSchema = null; selectedSchema = null;
}, },
@@ -95,7 +93,7 @@
// ...schemaList.filter(x => countBySchema[x]).map(x => ({ label: `${x} (${countBySchema[x] ?? 0})`, value: x })), // ...schemaList.filter(x => countBySchema[x]).map(x => ({ label: `${x} (${countBySchema[x] ?? 0})`, value: x })),
// ...schemaList.filter(x => !countBySchema[x]).map(x => ({ label: `${x} (${countBySchema[x] ?? 0})`, value: x })), // ...schemaList.filter(x => !countBySchema[x]).map(x => ({ label: `${x} (${countBySchema[x] ?? 0})`, value: x })),
]} ]}
value={selectedSchema ?? appliedSchema ?? ''} value={selectedSchema ?? $appliedCurrentSchema ?? ''}
on:change={e => { on:change={e => {
selectedSchema = e.detail; selectedSchema = e.detail;
localStorage.setItem(valueStorageKey, e.detail); localStorage.setItem(valueStorageKey, e.detail);
@@ -116,7 +114,7 @@
<InlineButton on:click={handleCreateSchema} title="Add new schema" square> <InlineButton on:click={handleCreateSchema} title="Add new schema" square>
<FontIcon icon="icon plus-thick" /> <FontIcon icon="icon plus-thick" />
</InlineButton> </InlineButton>
<InlineButton on:click={handleDropSchema} title="Delete schema" square disabled={!appliedSchema}> <InlineButton on:click={handleDropSchema} title="Delete schema" square disabled={!$appliedCurrentSchema}>
<FontIcon icon="icon minus-thick" /> <FontIcon icon="icon minus-thick" />
</InlineButton> </InlineButton>
</div> </div>

View File

@@ -36,13 +36,13 @@
import { apiCall } from '../utility/api'; import { apiCall } from '../utility/api';
import { filterAppsForDatabase } from '../utility/appTools'; import { filterAppsForDatabase } from '../utility/appTools';
import SchemaSelector from './SchemaSelector.svelte'; import SchemaSelector from './SchemaSelector.svelte';
import { appliedCurrentSchema } from '../stores';
export let conid; export let conid;
export let database; export let database;
let filter = ''; let filter = '';
let selectedSchema = null; let selectedSchema = null;
let appliedSelectedSchema = null;
$: objects = useDatabaseInfo({ conid, database }); $: objects = useDatabaseInfo({ conid, database });
$: status = useDatabaseStatus({ conid, database }); $: status = useDatabaseStatus({ conid, database });
@@ -147,9 +147,6 @@
dbinfo={$objects} dbinfo={$objects}
bind:selectedSchema bind:selectedSchema
objectList={flatFilteredList} objectList={flatFilteredList}
onApplySelectedSchema={x => {
appliedSelectedSchema = x;
}}
valueStorageKey={`sql-object-list-schema-${conid}-${database}`} valueStorageKey={`sql-object-list-schema-${conid}-${database}`}
{conid} {conid}
{database} {database}
@@ -161,7 +158,7 @@
{:else} {:else}
<AppObjectList <AppObjectList
list={objectList list={objectList
.filter(x => (appliedSelectedSchema ? x.schemaName == appliedSelectedSchema : true)) .filter(x => ($appliedCurrentSchema ? x.schemaName == $appliedCurrentSchema : true))
.map(x => ({ ...x, conid, database }))} .map(x => ({ ...x, conid, database }))}
module={databaseObjectAppObject} module={databaseObjectAppObject}
groupFunc={data => getObjectTypeFieldLabel(data.objectTypeField, driver)} groupFunc={data => getObjectTypeFieldLabel(data.objectTypeField, driver)}
@@ -173,7 +170,7 @@
passProps={{ passProps={{
showPinnedInsteadOfUnpin: true, showPinnedInsteadOfUnpin: true,
connection: $connection, connection: $connection,
hideSchemaName: !!appliedSelectedSchema, hideSchemaName: !!$appliedCurrentSchema,
}} }}
/> />
{/if} {/if}