refactor: moved table fields informations to vuex

This commit is contained in:
Fabio 2020-08-14 18:07:29 +02:00
parent 6d0724dc90
commit 744728a14f
12 changed files with 193 additions and 33 deletions

View File

@ -1,4 +1,8 @@
'use strict'; /**
export function uidGen () { * @export
return Math.random().toString(36).substr(2, 9).toUpperCase(); * @param {String} [prefix]
* @returns {String} Unique ID
*/
export function uidGen (prefix) {
return (prefix ? `${prefix}:` : '') + Math.random().toString(36).substr(2, 9).toUpperCase();
}; };

View File

@ -25,6 +25,16 @@ export default (connections) => {
} }
}); });
ipcMain.handle('get-key-usage', async (event, { uid, schema, table }) => {
try {
const result = await InformationSchema.getKeyUsage(connections[uid], schema, table);
return { status: 'success', response: result };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
ipcMain.handle('updateTableCell', async (event, params) => { ipcMain.handle('updateTableCell', async (event, params) => {
try { try {
const result = await Tables.updateTableCell(connections[params.uid], params); const result = await Tables.updateTableCell(connections[params.uid], params);

View File

@ -38,4 +38,29 @@ export default class {
}; };
}); });
} }
static async getKeyUsage (connection, schema, table) {
// SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA='fep-gprs' AND TABLE_NAME='struttura_macchine' AND REFERENCED_TABLE_NAME IS NOT NULL;
const { rows } = await connection
.select('*')
.schema('information_schema')
.from('KEY_COLUMN_USAGE')
.where({ TABLE_SCHEMA: `= '${schema}'`, TABLE_NAME: `= '${table}'`, REFERENCED_TABLE_NAME: 'IS NOT NULL' })
.run();
return rows.map(field => {
return {
schema: field.TABLE_SCHEMA,
table: field.TABLE_NAME,
column: field.COLUMN_NAME,
position: field.ORDINAL_POSITION,
constraintPosition: field.POSITION_IN_UNIQUE_CONSTRAINT,
constraintName: field.CONSTRAINT_NAME,
refSchema: field.REFERENCED_TABLE_SCHEMA,
refTable: field.REFERENCED_TABLE_NAME,
refColumn: field.REFERENCED_COLUMN_NAME
};
});
}
} }

View File

@ -170,7 +170,7 @@ export default {
user: 'root', user: 'root',
password: '', password: '',
ask: false, ask: false,
uid: uidGen() uid: uidGen('C')
}, },
toast: { toast: {
status: '', status: '',

View File

@ -42,6 +42,7 @@
v-for="tab of queryTabs" v-for="tab of queryTabs"
v-show="selectedTab === tab.uid" v-show="selectedTab === tab.uid"
:key="tab.uid" :key="tab.uid"
:tab-uid="tab.uid"
:connection="connection" :connection="connection"
/> />
</div> </div>

View File

@ -27,9 +27,10 @@
<div class="workspace-query-results column col-12"> <div class="workspace-query-results column col-12">
<WorkspaceQueryTable <WorkspaceQueryTable
v-if="results" v-if="results"
v-show="!isQuering"
ref="queryTable" ref="queryTable"
:results="results" :results="results"
:fields="fields" :tab-uid="tabUid"
@updateField="updateField" @updateField="updateField"
@deleteSelected="deleteSelected" @deleteSelected="deleteSelected"
/> />
@ -53,7 +54,8 @@ export default {
}, },
mixins: [tableTabs], mixins: [tableTabs],
props: { props: {
connection: Object connection: Object,
tabUid: String
}, },
data () { data () {
return { return {
@ -61,7 +63,7 @@ export default {
lastQuery: '', lastQuery: '',
isQuering: false, isQuering: false,
results: {}, results: {},
fields: [] selectedFields: []
}; };
}, },
computed: { computed: {
@ -72,37 +74,39 @@ export default {
return this.getWorkspace(this.connection.uid); return this.getWorkspace(this.connection.uid);
}, },
table () { table () {
if (this.results.fields.length) if ('fields' in this.results && this.results.fields.length)
return this.results.fields[0].orgTable; return this.results.fields[0].orgTable;
return ''; return '';
}, },
schema () { schema () {
if (this.results.fields.length) if ('fields' in this.results && this.results.fields.length)
return this.results.fields[0].db; return this.results.fields[0].db;
return ''; return this.workspace.breadcrumbs.schema;
} }
}, },
methods: { methods: {
...mapActions({ ...mapActions({
addNotification: 'notifications/addNotification' addNotification: 'notifications/addNotification',
setTabFields: 'workspaces/setTabFields',
setTabKeyUsage: 'workspaces/setTabKeyUsage'
}), }),
async runQuery (query) { async runQuery (query) {
if (!query) return; if (!query) return;
this.isQuering = true; this.isQuering = true;
this.results = {}; this.results = {};
this.fields = []; this.setTabFields({ cUid: this.connection.uid, tUid: this.tabUid, fields: [] });
let selectedFields = [];
try { try { // Query Data
const params = { const params = {
uid: this.connection.uid, uid: this.connection.uid,
schema: this.schema,
query query
}; };
const { status, response } = await Connection.rawQuery(params); const { status, response } = await Connection.rawQuery(params);
if (status === 'success') { if (status === 'success') {
this.results = response; this.results = response;
selectedFields = response.fields.map(field => field.orgName); this.selectedFields = response.fields.map(field => field.orgName);
} }
else else
this.addNotification({ status: 'error', message: response }); this.addNotification({ status: 'error', message: response });
@ -111,7 +115,7 @@ export default {
this.addNotification({ status: 'error', message: err.stack }); this.addNotification({ status: 'error', message: err.stack });
} }
try { try { // Table data
const params = { const params = {
uid: this.connection.uid, uid: this.connection.uid,
schema: this.schema, schema: this.schema,
@ -119,8 +123,27 @@ export default {
}; };
const { status, response } = await Tables.getTableColumns(params); const { status, response } = await Tables.getTableColumns(params);
if (status === 'success') {
const fields = response.filter(field => this.selectedFields.includes(field.name));
this.setTabFields({ cUid: this.connection.uid, tUid: this.tabUid, fields });
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
try { // Key usage (foreign keys)
const params = {
uid: this.connection.uid,
schema: this.schema,
table: this.table
};
const { status, response } = await Tables.getKeyUsage(params);
if (status === 'success') if (status === 'success')
this.fields = response.filter(field => selectedFields.includes(field.name)); this.setTabKeyUsage({ cUid: this.connection.uid, tUid: this.tabUid, keyUsage: response });
else else
this.addNotification({ status: 'error', message: response }); this.addNotification({ status: 'error', message: response });
} }

View File

@ -53,6 +53,7 @@
:key="row._id" :key="row._id"
:row="row" :row="row"
:fields="fields" :fields="fields"
:key-usage="keyUsage"
class="tr" class="tr"
:class="{'selected': selectedRows.includes(row._id)}" :class="{'selected': selectedRows.includes(row._id)}"
@selectRow="selectRow($event, row._id)" @selectRow="selectRow($event, row._id)"
@ -70,7 +71,7 @@ import { uidGen } from 'common/libs/uidGen';
import BaseVirtualScroll from '@/components/BaseVirtualScroll'; import BaseVirtualScroll from '@/components/BaseVirtualScroll';
import WorkspaceQueryTableRow from '@/components/WorkspaceQueryTableRow'; import WorkspaceQueryTableRow from '@/components/WorkspaceQueryTableRow';
import TableContext from '@/components/WorkspaceQueryTableContext'; import TableContext from '@/components/WorkspaceQueryTableContext';
import { mapActions } from 'vuex'; import { mapActions, mapGetters } from 'vuex';
export default { export default {
name: 'WorkspaceQueryTable', name: 'WorkspaceQueryTable',
@ -81,7 +82,7 @@ export default {
}, },
props: { props: {
results: Object, results: Object,
fields: Array tabUid: [String, Number]
}, },
data () { data () {
return { return {
@ -96,6 +97,9 @@ export default {
}; };
}, },
computed: { computed: {
...mapGetters({
getWorkspaceTab: 'workspaces/getWorkspaceTab'
}),
primaryField () { primaryField () {
return this.fields.filter(field => ['pri', 'uni'].includes(field.key))[0] || false; return this.fields.filter(field => ['pri', 'uni'].includes(field.key))[0] || false;
}, },
@ -114,6 +118,12 @@ export default {
else else
return this.localResults; return this.localResults;
}, },
fields () {
return this.getWorkspaceTab(this.tabUid) ? this.getWorkspaceTab(this.tabUid).fields : [];
},
keyUsage () {
return this.getWorkspaceTab(this.tabUid) ? this.getWorkspaceTab(this.tabUid).keyUsage : [];
},
scrollElement () { scrollElement () {
return this.$refs.tableWrapper; return this.$refs.tableWrapper;
} }

View File

@ -178,7 +178,8 @@ export default {
}, },
props: { props: {
row: Object, row: Object,
fields: Array fields: Array,
keyUsage: Array
}, },
data () { data () {
return { return {
@ -318,7 +319,7 @@ export default {
editOFF () { editOFF () {
this.isInlineEditor[this.editingField] = false; this.isInlineEditor[this.editingField] = false;
let content; let content;
if (!['blob', 'mediumblob', 'longblob'].includes(this.editingType)) { if (!BLOB.includes(this.editingType)) {
if (this.editingContent === this.$options.filters.typeFormat(this.originalContent, this.editingType)) return;// If not changed if (this.editingContent === this.$options.filters.typeFormat(this.originalContent, this.editingType)) return;// If not changed
content = this.editingContent; content = this.editingContent;
} }

View File

@ -33,9 +33,10 @@
<div class="workspace-query-results column col-12"> <div class="workspace-query-results column col-12">
<WorkspaceQueryTable <WorkspaceQueryTable
v-if="results" v-if="results"
v-show="!isQuering"
ref="queryTable" ref="queryTable"
:results="results" :results="results"
:fields="fields" :tab-uid="tabUid"
@updateField="updateField" @updateField="updateField"
@deleteSelected="deleteSelected" @deleteSelected="deleteSelected"
/> />
@ -56,6 +57,7 @@ import WorkspaceQueryTable from '@/components/WorkspaceQueryTable';
import ModalNewTableRow from '@/components/ModalNewTableRow'; import ModalNewTableRow from '@/components/ModalNewTableRow';
import { mapGetters, mapActions } from 'vuex'; import { mapGetters, mapActions } from 'vuex';
import tableTabs from '@/mixins/tableTabs'; import tableTabs from '@/mixins/tableTabs';
// import { TEXT, LONG_TEXT } from 'common/fieldTypes';
export default { export default {
name: 'WorkspaceTableTab', name: 'WorkspaceTableTab',
@ -70,9 +72,11 @@ export default {
}, },
data () { data () {
return { return {
tabUid: 1,
isQuering: false, isQuering: false,
results: {}, results: {},
fields: [], fields: [],
keyUsage: [],
lastTable: null, lastTable: null,
isAddModal: false isAddModal: false
}; };
@ -86,6 +90,13 @@ export default {
}, },
isSelected () { isSelected () {
return this.workspace.selected_tab === 1; return this.workspace.selected_tab === 1;
},
firstTextField () { // TODO: move inside new row modal and row components
if (this.fields.length) {
const textField = this.fields.find(field => [...TEXT, ...LONG_TEXT].includes(field.type));
return textField ? textField.name : '';
}
return '';
} }
}, },
watch: { watch: {
@ -107,12 +118,15 @@ export default {
}, },
methods: { methods: {
...mapActions({ ...mapActions({
addNotification: 'notifications/addNotification' addNotification: 'notifications/addNotification',
setTabFields: 'workspaces/setTabFields',
setTabKeyUsage: 'workspaces/setTabKeyUsage'
}), }),
async getTableData () { async getTableData () {
if (!this.table) return; if (!this.table) return;
this.isQuering = true; this.isQuering = true;
this.results = {}; this.results = {};
this.setTabFields({ cUid: this.connection.uid, tUid: this.tabUid, fields: [] });
const params = { const params = {
uid: this.connection.uid, uid: this.connection.uid,
@ -120,10 +134,12 @@ export default {
table: this.workspace.breadcrumbs.table table: this.workspace.breadcrumbs.table
}; };
try { try { // Columns data
const { status, response } = await Tables.getTableColumns(params); const { status, response } = await Tables.getTableColumns(params);
if (status === 'success') if (status === 'success') {
this.fields = response; this.fields = response;// Needed to add new rows
this.setTabFields({ cUid: this.connection.uid, tUid: this.tabUid, fields: response });
}
else else
this.addNotification({ status: 'error', message: response }); this.addNotification({ status: 'error', message: response });
} }
@ -131,7 +147,7 @@ export default {
this.addNotification({ status: 'error', message: err.stack }); this.addNotification({ status: 'error', message: err.stack });
} }
try { try { // Table data
const { status, response } = await Tables.getTableData(params); const { status, response } = await Tables.getTableData(params);
if (status === 'success') if (status === 'success')
@ -143,6 +159,19 @@ export default {
this.addNotification({ status: 'error', message: err.stack }); this.addNotification({ status: 'error', message: err.stack });
} }
try { // Key usage (foreign keys)
const { status, response } = await Tables.getKeyUsage(params);
if (status === 'success') {
this.keyUsage = response;// Needed to add new rows
this.setTabKeyUsage({ cUid: this.connection.uid, tUid: this.tabUid, keyUsage: response });
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false; this.isQuering = false;
}, },
reloadTable () { reloadTable () {

View File

@ -10,6 +10,10 @@ export default class {
return ipcRenderer.invoke('getTableData', params); return ipcRenderer.invoke('getTableData', params);
} }
static getKeyUsage (params) {
return ipcRenderer.invoke('get-key-usage', params);
}
static updateTableCell (params) { static updateTableCell (params) {
return ipcRenderer.invoke('updateTableCell', params); return ipcRenderer.invoke('updateTableCell', params);
} }

View File

@ -20,7 +20,7 @@ export default {
}, },
actions: { actions: {
addNotification ({ commit }, payload) { addNotification ({ commit }, payload) {
payload.uid = uidGen(); payload.uid = uidGen('N');
commit('ADD_NOTIFICATION', payload); commit('ADD_NOTIFICATION', payload);
}, },
removeNotification ({ commit }, uid) { removeNotification ({ commit }, uid) {

View File

@ -28,8 +28,14 @@ export default {
return null; return null;
}, },
getWorkspace: state => uid => { getWorkspace: state => uid => {
const workspace = state.workspaces.filter(workspace => workspace.uid === uid); return state.workspaces.find(workspace => workspace.uid === uid);
return workspace.length ? workspace[0] : {}; },
getWorkspaceTab: (state, getters) => tUid => {
if (!getters.getSelected) return;
const workspace = state.workspaces.find(workspace => workspace.uid === getters.getSelected);
if ('tabs' in workspace)
return workspace.tabs.find(tab => tab.uid === tUid);
return {};
}, },
getConnected: state => { getConnected: state => {
return state.workspaces return state.workspaces
@ -58,9 +64,11 @@ export default {
}, },
NEW_TAB (state, uid) { NEW_TAB (state, uid) {
const newTab = { const newTab = {
uid: uidGen(), uid: uidGen('T'),
selected: false, selected: false,
type: 'query' type: 'query',
fields: [],
keyUsage: []
}; };
state.workspaces = state.workspaces.map(workspace => { state.workspaces = state.workspaces.map(workspace => {
if (workspace.uid === uid) { if (workspace.uid === uid) {
@ -75,6 +83,40 @@ export default {
}, },
SELECT_TAB (state, { uid, tab }) { SELECT_TAB (state, { uid, tab }) {
state.workspaces = state.workspaces.map(workspace => workspace.uid === uid ? { ...workspace, selected_tab: tab } : workspace); state.workspaces = state.workspaces.map(workspace => workspace.uid === uid ? { ...workspace, selected_tab: tab } : workspace);
},
SET_TAB_FIELDS (state, { cUid, tUid, fields }) {
state.workspaces = state.workspaces.map(workspace => {
if (workspace.uid === cUid) {
return {
...workspace,
tabs: workspace.tabs.map(tab => {
if (tab.uid === tUid)
return { ...tab, fields };
else
return tab;
})
};
}
else
return workspace;
});
},
SET_TAB_KEY_USAGE (state, { cUid, tUid, keyUsage }) {
state.workspaces = state.workspaces.map(workspace => {
if (workspace.uid === cUid) {
return {
...workspace,
tabs: workspace.tabs.map(tab => {
if (tab.uid === tUid)
return { ...tab, keyUsage };
else
return tab;
})
};
}
else
return workspace;
});
} }
}, },
actions: { actions: {
@ -115,7 +157,12 @@ export default {
uid, uid,
connected: false, connected: false,
selected_tab: 0, selected_tab: 0,
tabs: [{ uid: 1, type: 'table' }], tabs: [{
uid: 1,
type: 'table',
fields: [],
keyUsage: []
}],
structure: {}, structure: {},
breadcrumbs: {} breadcrumbs: {}
}; };
@ -133,6 +180,12 @@ export default {
}, },
selectTab ({ commit }, payload) { selectTab ({ commit }, payload) {
commit('SELECT_TAB', payload); commit('SELECT_TAB', payload);
},
setTabFields ({ commit }, payload) {
commit('SET_TAB_FIELDS', payload);
},
setTabKeyUsage ({ commit }, payload) {
commit('SET_TAB_KEY_USAGE', payload);
} }
} }
}; };