Skip to content

Commit

Permalink
feat(PostgreSQL): ability to switch the database, closes #432
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabio286 committed Jun 13, 2023
1 parent 9d00f58 commit 89815bf
Show file tree
Hide file tree
Showing 15 changed files with 15,113 additions and 33 deletions.
14,939 changes: 14,939 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions src/main/ipc-handlers/database.ts
@@ -0,0 +1,14 @@
import * as antares from 'common/interfaces/antares';
import { ipcMain } from 'electron';

export default (connections: {[key: string]: antares.Client}) => {
ipcMain.handle('get-databases', async (event, uid) => {
try {
const result = await connections[uid].getDatabases();
return { status: 'success', response: result };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
};
2 changes: 2 additions & 0 deletions src/main/ipc-handlers/index.ts
Expand Up @@ -9,6 +9,7 @@ import functions from './functions';
import schedulers from './schedulers';
import updates from './updates';
import application from './application';
import database from './database';
import schema from './schema';
import users from './users';

Expand All @@ -22,6 +23,7 @@ export default () => {
routines(connections);
functions(connections);
schedulers(connections);
database(connections);
schema(connections);
users(connections);
updates();
Expand Down
4 changes: 4 additions & 0 deletions src/main/libs/AntaresCore.ts
Expand Up @@ -162,6 +162,10 @@ export abstract class AntaresCore {
throw new Error('Method "getDbConfig" not implemented');
}

getDatabases () {
throw new Error('Method "getDatabases" not implemented');
}

createSchema (...args: any) {
throw new Error('Method "createSchema" not implemented');
}
Expand Down
14 changes: 13 additions & 1 deletion src/main/libs/clients/PostgreSQLClient.ts
Expand Up @@ -154,7 +154,7 @@ export class PostgreSQLClient extends AntaresCore {
host: this._params.host,
port: this._params.port,
user: this._params.user,
database: undefined as string | undefined,
database: 'postgres' as string,
password: this._params.password,
ssl: null as mysql.SslOptions
};
Expand Down Expand Up @@ -262,6 +262,18 @@ export class PostgreSQLClient extends AntaresCore {
return [];
}

async getDatabases () {
const { rows } = await this.raw('SELECT datname FROM pg_database WHERE datistemplate = false');
if (rows) {
return rows.reduce((acc, cur) => {
acc.push(cur.datname);
return acc;
}, [] as string[]);
}
else
return [];
}

async getStructure (schemas: Set<string>) {
/* eslint-disable camelcase */
interface ShowTableResult {
Expand Down
4 changes: 2 additions & 2 deletions src/main/main.ts
Expand Up @@ -124,8 +124,8 @@ else {
if (isWindows)
mainWindow.show();

if (isDevelopment)
mainWindow.webContents.openDevTools();
// if (isDevelopment)
// mainWindow.webContents.openDevTools();

process.on('uncaughtException', error => {
mainWindow.webContents.send('unhandled-exception', error);
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/components/SettingBarConnectionsFolder.vue
Expand Up @@ -380,7 +380,7 @@ emit('folder-sort');// To apply changes on component key change
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
line-height: 1;
line-height: 1.02;
transition: bottom .2s;
}
}
Expand Down Expand Up @@ -444,7 +444,7 @@ emit('folder-sort');// To apply changes on component key change
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
line-height: 1;
line-height: 1.02;
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/renderer/components/Workspace.vue
Expand Up @@ -565,7 +565,11 @@ const workspace = computed(() => getWorkspace(props.connection.uid));
const draggableTabs = computed<WorkspaceTab[]>({
get () {
return workspace.value.tabs;
if (workspace.value.customizations.database)
return workspace.value.tabs.filter(tab => tab.type === 'query' || tab.database === workspace.value.database);
else
return workspace.value.tabs;
},
set (val) {
updateTabs({ uid: props.connection.uid, tabs: val });
Expand Down
1 change: 1 addition & 0 deletions src/renderer/components/WorkspaceAddConnectionPanel.vue
Expand Up @@ -120,6 +120,7 @@
v-model="connection.database"
class="form-input"
type="text"
:placeholder="clientCustomizations.defaultDatabase"
>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions src/renderer/components/WorkspaceEditConnectionPanel.vue
Expand Up @@ -122,6 +122,7 @@
v-model="localConnection.database"
class="form-input"
type="text"
:placeholder="clientCustomizations.defaultDatabase"
>
</div>
</div>
Expand Down
80 changes: 71 additions & 9 deletions src/renderer/components/WorkspaceExploreBar.vue
Expand Up @@ -10,7 +10,18 @@
@keydown="explorebarSearch"
>
<div class="workspace-explorebar-header">
<span class="workspace-explorebar-title">{{ connectionName }}</span>
<div
v-if="customizations.database"
class="workspace-explorebar-database-switch"
:title="t('message.switchDatabase')"
>
<BaseSelect
v-model="selectedDatabase"
:options="databases"
class="form-select select-sm text-bold my-0"
/>
</div>
<span v-else class="workspace-explorebar-title">{{ connectionName }}</span>
<span v-if="workspace.connectionStatus === 'connected'" class="workspace-explorebar-tools">
<i
v-if="customizations.schemas"
Expand Down Expand Up @@ -124,10 +135,11 @@
</template>

<script setup lang="ts">
import { Component, computed, onMounted, Ref, ref, watch } from 'vue';
import { Component, computed, onMounted, Prop, Ref, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useConnectionsStore } from '@/stores/connections';
import { ConnectionParams } from 'common/interfaces/antares';
import { useNotificationsStore } from '@/stores/notifications';
import { useSettingsStore } from '@/stores/settings';
import { useWorkspacesStore } from '@/stores/workspaces';
Expand All @@ -141,12 +153,14 @@ import TableContext from '@/components/WorkspaceExploreBarTableContext.vue';
import MiscContext from '@/components/WorkspaceExploreBarMiscContext.vue';
import MiscFolderContext from '@/components/WorkspaceExploreBarMiscFolderContext.vue';
import ModalNewSchema from '@/components/ModalNewSchema.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import { useI18n } from 'vue-i18n';
import Databases from '@/ipc-api/Databases';
const { t } = useI18n();
const props = defineProps({
connection: Object,
connection: Object as Prop<ConnectionParams>,
isSelected: Boolean
});
Expand All @@ -160,18 +174,21 @@ const { explorebarSize } = storeToRefs(settingsStore);
const { changeExplorebarSize } = settingsStore;
const {
getWorkspace,
switchConnection,
removeConnected: disconnectWorkspace,
refreshStructure,
newTab,
removeTabs,
setSearchTerm,
setDatabase,
addLoadingElement,
removeLoadingElement
} = workspacesStore;
const searchInput: Ref<HTMLInputElement> = ref(null);
const explorebar: Ref<HTMLInputElement> = ref(null);
const resizer: Ref<HTMLInputElement> = ref(null);
const databases: Ref<string[]> = ref([]);
const schema: Ref<Component & { selectSchema: (name: string) => void; $refs: {schemaAccordion: HTMLDetailsElement} }[]> = ref(null);
const isRefreshing = ref(false);
const isNewDBModal = ref(false);
Expand All @@ -185,6 +202,7 @@ const isMiscFolderContext = ref(false);
const databaseContextEvent = ref(null);
const tableContextEvent = ref(null);
const miscContextEvent = ref(null);
const selectedDatabase = ref(props.connection.database);
const selectedSchema = ref('');
const selectedTable = ref(null);
const selectedMisc = ref(null);
Expand Down Expand Up @@ -230,20 +248,43 @@ watch(searchTerm, () => {
}, 200);
});
watch(selectedDatabase, (val, oldVal) => {
if (oldVal)
switchConnection({ ...props.connection, database: selectedDatabase.value });
});
localWidth.value = explorebarSize.value;
onMounted(() => {
onMounted(async () => {
resizer.value.addEventListener('mousedown', (e: MouseEvent) => {
e.preventDefault();
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
});
if (workspace.value.structure.length === 1) { // Auto-open if juust one schema
if (workspace.value.structure.length === 1) { // Auto-open if just one schema
schema.value[0].selectSchema(workspace.value.structure[0].name);
schema.value[0].$refs.schemaAccordion.open = true;
}
if (customizations.value.database) {
try {
const { status, response } = await Databases.getDatabases(props.connection.uid);
if (status === 'success') {
databases.value = response;
if (selectedDatabase.value === '') {
selectedDatabase.value = response[0];
setDatabase(selectedDatabase.value);
}
}
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
}
});
const refresh = async () => {
Expand All @@ -254,8 +295,11 @@ const refresh = async () => {
}
};
const explorebarSearch = () => {
searchInput.value.focus();
const explorebarSearch = (event: KeyboardEvent) => {
const isLetter = (event.key >= 'a' && event.key <= 'z');
const isNumber = (event.key >= '0' && event.key <= '9');
if (isLetter || isNumber)
searchInput.value.focus();
};
const resize = (e: MouseEvent) => {
Expand Down Expand Up @@ -497,13 +541,31 @@ const toggleSearchMethod = () => {
}
}
.workspace-explorebar-database-switch {
width: 100%;
display: flex;
justify-content: space-between;
z-index: 20;
margin-right: 5px;
margin-left: -4px;
margin-top: -3px;
margin-bottom: -0.5rem;
height: 24px;
.form-select.select-sm {
font-size: 0.6rem;
height: 1.2rem;
line-height: 1rem;
}
}
.workspace-explorebar-search {
width: 100%;
display: flex;
justify-content: space-between;
font-size: 0.6rem;
height: 28px;
margin: 5px 0;
margin: 0 0 5px 0;
z-index: 10;
.has-icon-right {
Expand Down Expand Up @@ -533,7 +595,7 @@ const toggleSearchMethod = () => {
.workspace-explorebar-body {
width: 100%;
height: calc((100vh - 68px) - #{$excluding-size});
height: calc((100vh - 63px) - #{$excluding-size});
overflow: overlay;
padding: 0 0.1rem;
}
Expand Down
8 changes: 5 additions & 3 deletions src/renderer/components/WorkspaceTabQuery.vue
Expand Up @@ -291,6 +291,11 @@ watch(selectedSchema, () => {
changeBreadcrumbs({ schema: selectedSchema.value, query: `Query #${props.tab.index}` });
});
watch(databaseSchemas, () => {
if (!databaseSchemas.value.includes(selectedSchema.value))
selectedSchema.value = null;
}, { deep: true });
const runQuery = async (query: string) => {
if (!query || isQuering.value) return;
isQuering.value = true;
Expand Down Expand Up @@ -496,9 +501,6 @@ defineExpose({ resizeResults });
query.value = props.tab.content as string;
selectedSchema.value = props.tab.schema || breadcrumbsSchema.value;
if (!databaseSchemas.value.includes(selectedSchema.value))
selectedSchema.value = null;
window.addEventListener('resize', onWindowResize);
const reloadListener = () => {
Expand Down
3 changes: 2 additions & 1 deletion src/renderer/i18n/en-US.ts
Expand Up @@ -348,7 +348,8 @@ export const enUS = {
closeAllTabs: 'Close all tabs',
closeOtherTabs: 'Close other tabs',
closeTabsToLeft: 'Close tabs to the left',
closeTabsToRight: 'Close tabs to the right'
closeTabsToRight: 'Close tabs to the right',
switchDatabase: 'Switch the database'
},
faker: {
address: 'Address',
Expand Down
9 changes: 9 additions & 0 deletions src/renderer/ipc-api/Databases.ts
@@ -0,0 +1,9 @@
import { ipcRenderer } from 'electron';
import { unproxify } from '../libs/unproxify';
import { IpcResponse } from 'common/interfaces/antares';

export default class {
static getDatabases (params: string): Promise<IpcResponse> {
return ipcRenderer.invoke('get-databases', unproxify(params));
}
}

0 comments on commit 89815bf

Please sign in to comment.