1
1
mirror of https://github.com/Fabio286/antares.git synced 2025-03-10 00:10:16 +01:00

refactor: ts and composition api on missing components

This commit is contained in:
Fabio Di Stasio 2022-06-21 17:54:47 +02:00
parent 89e8d9fcdb
commit a103617ce8
38 changed files with 4553 additions and 4846 deletions

View File

@ -92,13 +92,15 @@ export interface TableInfos {
collation: string; collation: string;
} }
export type TableOptions = Partial<TableInfos>;
export interface TableField { export interface TableField {
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
_antares_id?: string; _antares_id?: string;
name: string; name: string;
key: string;
type: string; type: string;
schema: string; schema: string;
table?: string;
numPrecision?: number; numPrecision?: number;
numLength?: number; numLength?: number;
datePrecision?: number; datePrecision?: number;
@ -109,6 +111,7 @@ export interface TableField {
zerofill?: boolean; zerofill?: boolean;
order?: number; order?: number;
default?: string; default?: string;
defaultType?: string;
enumValues?: string; enumValues?: string;
charset?: string; charset?: string;
collation?: string; collation?: string;
@ -118,7 +121,11 @@ export interface TableField {
comment?: string; comment?: string;
after?: string; after?: string;
orgName?: string; orgName?: string;
length?: number; length?: number | false;
alias: string;
tableAlias: string;
orgTable: string;
key?: 'pri' | 'uni';
} }
export interface TableIndex { export interface TableIndex {
@ -136,6 +143,8 @@ export interface TableIndex {
} }
export interface TableForeign { export interface TableForeign {
// eslint-disable-next-line camelcase
_antares_id?: string;
constraintName: string; constraintName: string;
refSchema: string; refSchema: string;
table: string; table: string;
@ -147,15 +156,6 @@ export interface TableForeign {
oldName?: string; oldName?: string;
} }
export interface TableOptions {
name: string;
type?: 'table' | 'view';
engine?: string;
comment?: string;
collation?: string;
autoIncrement?: number;
}
export interface CreateTableParams { export interface CreateTableParams {
/** Connection UID */ /** Connection UID */
uid?: string; uid?: string;
@ -236,15 +236,12 @@ export interface CreateTriggerParams {
export interface AlterTriggerParams extends CreateTriggerParams { export interface AlterTriggerParams extends CreateTriggerParams {
oldName?: string; oldName?: string;
} }
export interface TriggerFunctionInfos {
name: string;
type: string;
security: string;
}
// Routines & Functions // Routines & Functions
export interface FunctionParam { export interface FunctionParam {
// eslint-disable-next-line camelcase
_antares_id: string;
context: string; context: string;
name: string; name: string;
type: string; type: string;
@ -267,9 +264,11 @@ export interface RoutineInfos {
parameters?: FunctionParam[]; parameters?: FunctionParam[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
returns?: any; returns?: any;
returnsLength?: number;
} }
export type FunctionInfos = RoutineInfos export type FunctionInfos = RoutineInfos
export type TriggerFunctionInfos = FunctionInfos
export interface CreateRoutineParams { export interface CreateRoutineParams {
name: string; name: string;
@ -309,29 +308,6 @@ export interface AlterFunctionParams extends CreateFunctionParams {
// Events // Events
export interface EventInfos { export interface EventInfos {
name: string;
definition: string;
type: string;
definer: string;
body: string;
starts: string;
ends: string;
enabled: boolean;
executeAt: string;
intervalField: string;
intervalValue: string;
onCompletion: string;
originator: string;
sqlMode: string;
created: string;
updated: string;
lastExecuted: string;
comment: string;
charset: string;
timezone: string;
}
export interface CreateEventParams {
definer?: string; definer?: string;
schema: string; schema: string;
name: string; name: string;
@ -340,12 +316,15 @@ export interface CreateEventParams {
starts: string; starts: string;
ends: string; ends: string;
at: string; at: string;
preserve: string; preserve: boolean;
state: string; state: string;
comment: string; comment: string;
enabled?: boolean;
sql: string; sql: string;
} }
export type CreateEventParams = EventInfos;
export interface AlterEventParams extends CreateEventParams { export interface AlterEventParams extends CreateEventParams {
oldName?: string; oldName?: string;
} }
@ -397,17 +376,10 @@ export interface QueryParams {
tabUid?: string; tabUid?: string;
} }
export interface QueryField { /**
name: string; * @deprecated Use TableFIeld
alias: string; */
orgName: string; export type QueryField = TableField
schema: string;
table: string;
tableAlias: string;
orgTable: string;
type: string;
length: number;
}
export interface QueryForeign { export interface QueryForeign {
schema: string; schema: string;

View File

@ -1,5 +1,34 @@
import { UsableLocale } from '@faker-js/faker'; import { UsableLocale } from '@faker-js/faker';
export interface TableUpdateParams {
uid: string;
schema: string;
table: string;
primary?: string;
id: number | string;
content: number | string | boolean | Date | Blob | null;
type: string;
field: string;
}
export interface TableDeleteParams {
uid: string;
schema: string;
table: string;
primary?: string;
field: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
rows: {[key: string]: any};
}
export interface TableFilterClausole {
active: boolean;
field: string;
op: '=' | '!=' | '>' | '<' | '>=' | '<=' | 'IN' | 'NOT IN' | 'LIKE' | 'BETWEEN' | 'IS NULL' | 'IS NOT NULL';
value: '';
value2: '';
}
export interface InsertRowsParams { export interface InsertRowsParams {
uid: string; uid: string;
schema: string; schema: string;

View File

@ -381,25 +381,18 @@ export class MySQLClient extends AntaresCore {
const remappedSchedulers: antares.EventInfos[] = schedulers.filter(scheduler => scheduler.Db === db.Database).map(scheduler => { const remappedSchedulers: antares.EventInfos[] = schedulers.filter(scheduler => scheduler.Db === db.Database).map(scheduler => {
return { return {
name: scheduler.EVENT_NAME, name: scheduler.EVENT_NAME,
definition: scheduler.EVENT_DEFINITION, schema: scheduler.Db,
type: scheduler.EVENT_TYPE, sql: scheduler.EVENT_DEFINITION,
execution: scheduler.EVENT_TYPE === 'RECURRING' ? 'EVERY' : 'ONCE',
definer: scheduler.DEFINER, definer: scheduler.DEFINER,
body: scheduler.EVENT_BODY,
starts: scheduler.STARTS, starts: scheduler.STARTS,
ends: scheduler.ENDS, ends: scheduler.ENDS,
state: scheduler.STATUS === 'ENABLED' ? 'ENABLE' : scheduler.STATE === 'DISABLED' ? 'DISABLE' : 'DISABLE ON SLAVE',
enabled: scheduler.STATUS === 'ENABLED', enabled: scheduler.STATUS === 'ENABLED',
executeAt: scheduler.EXECUTE_AT, at: scheduler.EXECUTE_AT,
intervalField: scheduler.INTERVAL_FIELD, every: [scheduler.INTERVAL_FIELD, scheduler.INTERVAL_VALUE],
intervalValue: scheduler.INTERVAL_VALUE, preserve: scheduler.ON_COMPLETION.includes('PRESERVE'),
onCompletion: scheduler.ON_COMPLETION, comment: scheduler.EVENT_COMMENT
originator: scheduler.ORIGINATOR,
sqlMode: scheduler.SQL_MODE,
created: scheduler.CREATED,
updated: scheduler.LAST_ALTERED,
lastExecuted: scheduler.LAST_EXECUTED,
comment: scheduler.EVENT_COMMENT,
charset: scheduler.CHARACTER_SET_CLIENT,
timezone: scheduler.TIME_ZONE
}; };
}); });
@ -930,19 +923,22 @@ export class MySQLClient extends AntaresCore {
} }
async getViewInformations ({ schema, view }: { schema: string; view: string }) { async getViewInformations ({ schema, view }: { schema: string; view: string }) {
const sql = `SHOW CREATE VIEW \`${schema}\`.\`${view}\``; const { rows: algorithm } = await this.raw(`SHOW CREATE VIEW \`${schema}\`.\`${view}\``);
const results = await this.raw(sql); const { rows: viewInfo } = await this.raw(`
SELECT *
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA = '${schema}'
AND TABLE_NAME = '${view}'
`);
return results.rows.map(row => { return {
return { algorithm: algorithm[0]['Create View'].match(/(?<=CREATE ALGORITHM=).*?(?=\s)/gs)[0],
algorithm: row['Create View'].match(/(?<=CREATE ALGORITHM=).*?(?=\s)/gs)[0], definer: viewInfo[0].DEFINER,
definer: row['Create View'].match(/(?<=DEFINER=).*?(?=\s)/gs)[0], security: viewInfo[0].SECURITY_TYPE,
security: row['Create View'].match(/(?<=SQL SECURITY ).*?(?=\s)/gs)[0], updateOption: viewInfo[0].CHECK_OPTION === 'NONE' ? '' : viewInfo[0].CHECK_OPTION,
updateOption: row['Create View'].match(/(?<=WITH ).*?(?=\s)/gs) ? row['Create View'].match(/(?<=WITH ).*?(?=\s)/gs)[0] : '', sql: viewInfo[0].VIEW_DEFINITION,
sql: row['Create View'].match(/(?<=AS ).*?$/gs)[0], name: viewInfo[0].TABLE_NAME
name: row.View };
};
})[0];
} }
async dropView (params: { schema: string; view: string }) { async dropView (params: { schema: string; view: string }) {
@ -955,7 +951,7 @@ export class MySQLClient extends AntaresCore {
USE \`${view.schema}\`; USE \`${view.schema}\`;
ALTER ALGORITHM = ${view.algorithm}${view.definer ? ` DEFINER=${view.definer}` : ''} ALTER ALGORITHM = ${view.algorithm}${view.definer ? ` DEFINER=${view.definer}` : ''}
SQL SECURITY ${view.security} SQL SECURITY ${view.security}
params \`${view.schema}\`.\`${view.oldName}\` AS ${view.sql} ${view.updateOption ? `WITH ${view.updateOption} CHECK OPTION` : ''} VIEW \`${view.schema}\`.\`${view.oldName}\` AS ${view.sql} ${view.updateOption ? `WITH ${view.updateOption} CHECK OPTION` : ''}
`; `;
if (view.name !== view.oldName) if (view.name !== view.oldName)

View File

@ -50,14 +50,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, PropType, Ref, ref } from 'vue'; import { computed, PropType, Ref, ref } from 'vue';
import { NUMBER, FLOAT } from 'common/fieldTypes'; import { NUMBER, FLOAT } from 'common/fieldTypes';
import { FunctionParam } from 'common/interfaces/antares'; import { FunctionInfos, RoutineInfos } from 'common/interfaces/antares';
import ConfirmModal from '@/components/BaseConfirmModal.vue'; import ConfirmModal from '@/components/BaseConfirmModal.vue';
// eslint-disable-next-line camelcase
type LocalRoutineParams = FunctionParam & {_antares_id: string};
const props = defineProps({ const props = defineProps({
localRoutine: Object as PropType<{name: string; parameters: LocalRoutineParams[]}>, localRoutine: Object as PropType<RoutineInfos | FunctionInfos>,
client: String client: String
}); });

View File

@ -7,7 +7,7 @@
<div class="modal-title h6"> <div class="modal-title h6">
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-history mr-1" /> <i class="mdi mdi-24px mdi-history mr-1" />
<span class="cut-text">{{ $t('word.history') }}: {{ connectionName }}</span> <span class="cut-text">{{ t('word.history') }}: {{ connectionName }}</span>
</div> </div>
</div> </div>
<a class="btn btn-clear c-hand" @click.stop="closeModal" /> <a class="btn btn-clear c-hand" @click.stop="closeModal" />
@ -22,7 +22,7 @@
v-model="searchTerm" v-model="searchTerm"
class="form-input" class="form-input"
type="text" type="text"
:placeholder="$t('message.searchForQueries')" :placeholder="t('message.searchForQueries')"
> >
<i v-if="!searchTerm" class="form-icon mdi mdi-magnify mdi-18px pr-4" /> <i v-if="!searchTerm" class="form-icon mdi mdi-magnify mdi-18px pr-4" />
<i <i
@ -67,13 +67,13 @@
<small class="tile-subtitle">{{ query.schema }} · {{ formatDate(query.date) }}</small> <small class="tile-subtitle">{{ query.schema }} · {{ formatDate(query.date) }}</small>
<div class="tile-history-buttons"> <div class="tile-history-buttons">
<button class="btn btn-link pl-1" @click.stop="$emit('select-query', query.sql)"> <button class="btn btn-link pl-1" @click.stop="$emit('select-query', query.sql)">
<i class="mdi mdi-open-in-app pr-1" /> {{ $t('word.select') }} <i class="mdi mdi-open-in-app pr-1" /> {{ t('word.select') }}
</button> </button>
<button class="btn btn-link pl-1" @click="copyQuery(query.sql)"> <button class="btn btn-link pl-1" @click="copyQuery(query.sql)">
<i class="mdi mdi-content-copy pr-1" /> {{ $t('word.copy') }} <i class="mdi mdi-content-copy pr-1" /> {{ t('word.copy') }}
</button> </button>
<button class="btn btn-link pl-1" @click="deleteQuery(query)"> <button class="btn btn-link pl-1" @click="deleteQuery(query)">
<i class="mdi mdi-delete-forever pr-1" /> {{ $t('word.delete') }} <i class="mdi mdi-delete-forever pr-1" /> {{ t('word.delete') }}
</button> </button>
</div> </div>
</div> </div>
@ -88,7 +88,7 @@
<i class="mdi mdi-history mdi-48px" /> <i class="mdi mdi-history mdi-48px" />
</div> </div>
<p class="empty-title h5"> <p class="empty-title h5">
{{ $t('message.thereIsNoQueriesYet') }} {{ t('message.thereIsNoQueriesYet') }}
</p> </p>
</div> </div>
</div> </div>
@ -99,12 +99,15 @@
<script setup lang="ts"> <script setup lang="ts">
import { Component, computed, ComputedRef, onBeforeUnmount, onMounted, onUpdated, Prop, Ref, ref, watch } from 'vue'; import { Component, computed, ComputedRef, onBeforeUnmount, onMounted, onUpdated, Prop, Ref, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import * as moment from 'moment'; import * as moment from 'moment';
import { ConnectionParams } from 'common/interfaces/antares'; import { ConnectionParams } from 'common/interfaces/antares';
import { HistoryRecord, useHistoryStore } from '@/stores/history'; import { HistoryRecord, useHistoryStore } from '@/stores/history';
import { useConnectionsStore } from '@/stores/connections'; import { useConnectionsStore } from '@/stores/connections';
import BaseVirtualScroll from '@/components/BaseVirtualScroll.vue'; import BaseVirtualScroll from '@/components/BaseVirtualScroll.vue';
const { t } = useI18n();
const { getHistoryByWorkspace, deleteQueryFromHistory } = useHistoryStore(); const { getHistoryByWorkspace, deleteQueryFromHistory } = useHistoryStore();
const { getConnectionName } = useConnectionsStore(); const { getConnectionName } = useConnectionsStore();

View File

@ -11,27 +11,27 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
<div class="divider-vert py-3" /> <div class="divider-vert py-3" />
<button class="btn btn-dark btn-sm" @click="showParamsModal"> <button class="btn btn-dark btn-sm" @click="showParamsModal">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" /> <i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span>{{ $t('word.parameters') }}</span> <span>{{ t('word.parameters') }}</span>
</button> </button>
</div> </div>
<div class="workspace-query-info"> <div class="workspace-query-info">
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -42,7 +42,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<input <input
ref="firstInput" ref="firstInput"
@ -55,7 +55,7 @@
<div v-if="customizations.languages" class="column col-auto"> <div v-if="customizations.languages" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.language') }} {{ t('word.language') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.language" v-model="localFunction.language"
@ -67,11 +67,11 @@
<div v-if="customizations.definer" class="column col-auto"> <div v-if="customizations.definer" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.definer') }} {{ t('word.definer') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.definer" v-model="localFunction.definer"
:options="[{value: '', name:$t('message.currentUser')}, ...workspace.users]" :options="[{value: '', name:t('message.currentUser')}, ...workspace.users]"
:option-label="(user: any) => user.value === '' ? user.name : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? user.name : `${user.name}@${user.host}`"
:option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
@ -81,7 +81,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.returns') }} {{ t('word.returns') }}
</label> </label>
<div class="input-group"> <div class="input-group">
<BaseSelect <BaseSelect
@ -101,7 +101,7 @@
class="form-input" class="form-input"
type="number" type="number"
min="0" min="0"
:placeholder="$t('word.length')" :placeholder="t('word.length')"
> >
</div> </div>
</div> </div>
@ -109,7 +109,7 @@
<div v-if="customizations.comment" class="column"> <div v-if="customizations.comment" class="column">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.comment') }} {{ t('word.comment') }}
</label> </label>
<input <input
v-model="localFunction.comment" v-model="localFunction.comment"
@ -121,7 +121,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('message.sqlSecurity') }} {{ t('message.sqlSecurity') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.security" v-model="localFunction.security"
@ -133,7 +133,7 @@
<div v-if="customizations.functionDataAccess" class="column col-auto"> <div v-if="customizations.functionDataAccess" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('message.dataAccess') }} {{ t('message.dataAccess') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.dataAccess" v-model="localFunction.dataAccess"
@ -146,7 +146,7 @@
<div class="form-group"> <div class="form-group">
<label class="form-label d-invisible">.</label> <label class="form-label d-invisible">.</label>
<label class="form-checkbox form-inline"> <label class="form-checkbox form-inline">
<input v-model="localFunction.deterministic" type="checkbox"><i class="form-icon" /> {{ $t('word.deterministic') }} <input v-model="localFunction.deterministic" type="checkbox"><i class="form-icon" /> {{ t('word.deterministic') }}
</label> </label>
</div> </div>
</div> </div>
@ -154,7 +154,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.functionBody') }}</label> <label class="form-label ml-2">{{ t('message.functionBody') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -186,6 +186,9 @@ import QueryEditor from '@/components/QueryEditor.vue';
import WorkspaceTabPropsFunctionParamsModal from '@/components/WorkspaceTabPropsFunctionParamsModal.vue'; import WorkspaceTabPropsFunctionParamsModal from '@/components/WorkspaceTabPropsFunctionParamsModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { FunctionInfos, FunctionParam } from 'common/interfaces/antares'; import { FunctionInfos, FunctionParam } from 'common/interfaces/antares';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const props = defineProps({ const props = defineProps({
tabUid: String, tabUid: String,

View File

@ -201,7 +201,7 @@ const {
changeBreadcrumbs changeBreadcrumbs
} = workspacesStore; } = workspacesStore;
const indexTable: Ref<Component & {$refs: { tableWrapper: HTMLDivElement }}> = ref(null); const indexTable: Ref<Component & { tableWrapper: HTMLDivElement }> = ref(null);
const firstInput: Ref<HTMLInputElement> = ref(null); const firstInput: Ref<HTMLInputElement> = ref(null);
const isLoading = ref(false); const isLoading = ref(false);
const isSaving = ref(false); const isSaving = ref(false);
@ -336,7 +336,7 @@ const addField = () => {
}); });
setTimeout(() => { setTimeout(() => {
const scrollable = indexTable.value.$refs.tableWrapper; const scrollable = indexTable.value.tableWrapper;
scrollable.scrollTop = scrollable.scrollHeight + 30; scrollable.scrollTop = scrollable.scrollHeight + 30;
}, 20); }, 20);
}; };
@ -364,7 +364,7 @@ const duplicateField = (uid: string) => {
localFields.value = [...localFields.value, fieldToClone]; localFields.value = [...localFields.value, fieldToClone];
setTimeout(() => { setTimeout(() => {
const scrollable = indexTable.value.$refs.tableWrapper; const scrollable = indexTable.value.tableWrapper;
scrollable.scrollTop = scrollable.scrollHeight + 30; scrollable.scrollTop = scrollable.scrollHeight + 30;
}, 20); }, 20);
}; };

View File

@ -85,12 +85,12 @@
/> />
<div v-if="customizations.triggerMultipleEvents" class="px-4"> <div v-if="customizations.triggerMultipleEvents" class="px-4">
<label <label
v-for="event in Object.keys(localEvents)" v-for="event in Object.keys(localEvents) as ('INSERT' | 'UPDATE' | 'DELETE')[]"
:key="event" :key="event"
class="form-checkbox form-inline" class="form-checkbox form-inline"
@change.prevent="changeEvents(event as 'INSERT' | 'UPDATE' | 'DELETE')" @change.prevent="changeEvents(event)"
> >
<input :checked="localEvents[event as 'INSERT' | 'UPDATE' | 'DELETE']" type="checkbox"><i class="form-icon" /> {{ event }} <input :checked="localEvents[event]" type="checkbox"><i class="form-icon" /> {{ event }}
</label> </label>
</div> </div>
</div> </div>

View File

@ -144,17 +144,9 @@ const originalView = ref(null);
const localView = ref(null); const localView = ref(null);
const editorHeight = ref(300); const editorHeight = ref(300);
const workspace = computed(() => { const workspace = computed(() => getWorkspace(props.connection.uid));
return getWorkspace(props.connection.uid); const isChanged = computed(() => JSON.stringify(originalView.value) !== JSON.stringify(localView.value));
}); const isDefinerInUsers = computed(() => originalView.value ? workspace.value.users.some(user => originalView.value.definer === `\`${user.name}\`@\`${user.host}\``) : true);
const isChanged = computed(() => {
return JSON.stringify(originalView.value) !== JSON.stringify(localView.value);
});
const isDefinerInUsers = computed(() => {
return originalView.value ? workspace.value.users.some(user => originalView.value.definer === `\`${user.name}\`@\`${user.host}\``) : true;
});
const users = computed(() => { const users = computed(() => {
const users = [{ value: '' }, ...workspace.value.users]; const users = [{ value: '' }, ...workspace.value.users];

View File

@ -11,16 +11,16 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
<div class="divider-vert py-3" /> <div class="divider-vert py-3" />
@ -31,15 +31,15 @@
@click="runFunctionCheck" @click="runFunctionCheck"
> >
<i class="mdi mdi-24px mdi-play mr-1" /> <i class="mdi mdi-24px mdi-play mr-1" />
<span>{{ $t('word.run') }}</span> <span>{{ t('word.run') }}</span>
</button> </button>
<button class="btn btn-dark btn-sm" @click="showParamsModal"> <button class="btn btn-dark btn-sm" @click="showParamsModal">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" /> <i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span>{{ $t('word.parameters') }}</span> <span>{{ t('word.parameters') }}</span>
</button> </button>
</div> </div>
<div class="workspace-query-info"> <div class="workspace-query-info">
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -50,7 +50,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<input <input
ref="firstInput" ref="firstInput"
@ -64,7 +64,7 @@
<div v-if="customizations.languages" class="column col-auto"> <div v-if="customizations.languages" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.language') }} {{ t('word.language') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.language" v-model="localFunction.language"
@ -76,13 +76,13 @@
<div v-if="customizations.definer" class="column col-auto"> <div v-if="customizations.definer" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.definer') }} {{ t('word.definer') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.definer" v-model="localFunction.definer"
:options="[{value: '', name:$t('message.currentUser')}, ...workspace.users]" :options="[{value: '', name:t('message.currentUser')}, ...workspace.users]"
:option-label="(user) => user.value === '' ? user.name : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? user.name : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
/> />
</div> </div>
@ -90,13 +90,13 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.returns') }} {{ t('word.returns') }}
</label> </label>
<div class="input-group"> <div class="input-group">
<BaseSelect <BaseSelect
v-model="localFunction.returns" v-model="localFunction.returns"
class="form-select text-uppercase" class="form-select text-uppercase"
:options="[{ name: 'VOID' }, ...workspace.dataTypes]" :options="[{ name: 'VOID' }, ...(workspace.dataTypes as any)]"
group-label="group" group-label="group"
group-values="types" group-values="types"
option-label="name" option-label="name"
@ -110,7 +110,7 @@
class="form-input" class="form-input"
type="number" type="number"
min="0" min="0"
:placeholder="$t('word.length')" :placeholder="t('word.length')"
> >
</div> </div>
</div> </div>
@ -118,7 +118,7 @@
<div v-if="customizations.comment" class="column"> <div v-if="customizations.comment" class="column">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.comment') }} {{ t('word.comment') }}
</label> </label>
<input <input
v-model="localFunction.comment" v-model="localFunction.comment"
@ -130,7 +130,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('message.sqlSecurity') }} {{ t('message.sqlSecurity') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.security" v-model="localFunction.security"
@ -142,7 +142,7 @@
<div v-if="customizations.functionDataAccess" class="column col-auto"> <div v-if="customizations.functionDataAccess" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('message.dataAccess') }} {{ t('message.dataAccess') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.dataAccess" v-model="localFunction.dataAccess"
@ -155,7 +155,7 @@
<div class="form-group"> <div class="form-group">
<label class="form-label d-invisible">.</label> <label class="form-label d-invisible">.</label>
<label class="form-checkbox form-inline"> <label class="form-checkbox form-inline">
<input v-model="localFunction.deterministic" type="checkbox"><i class="form-icon" /> {{ $t('word.deterministic') }} <input v-model="localFunction.deterministic" type="checkbox"><i class="form-icon" /> {{ t('word.deterministic') }}
</label> </label>
</div> </div>
</div> </div>
@ -163,7 +163,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.functionBody') }}</label> <label class="form-label ml-2">{{ t('message.functionBody') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -191,300 +191,273 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onBeforeUnmount, onMounted, onUnmounted, Ref, ref, watch } from 'vue';
import { Ace } from 'ace-builds';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import { uidGen } from 'common/libs/uidGen'; import { uidGen } from 'common/libs/uidGen';
import BaseLoader from '@/components/BaseLoader'; import BaseLoader from '@/components/BaseLoader.vue';
import QueryEditor from '@/components/QueryEditor'; import QueryEditor from '@/components/QueryEditor.vue';
import WorkspaceTabPropsFunctionParamsModal from '@/components/WorkspaceTabPropsFunctionParamsModal'; import WorkspaceTabPropsFunctionParamsModal from '@/components/WorkspaceTabPropsFunctionParamsModal.vue';
import ModalAskParameters from '@/components/ModalAskParameters'; import ModalAskParameters from '@/components/ModalAskParameters.vue';
import Functions from '@/ipc-api/Functions'; import Functions from '@/ipc-api/Functions';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { useI18n } from 'vue-i18n';
import { AlterFunctionParams, FunctionInfos, FunctionParam } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsFunction',
components: {
BaseLoader,
QueryEditor,
WorkspaceTabPropsFunctionParamsModal,
ModalAskParameters,
BaseSelect
},
props: {
tabUid: String,
connection: Object,
function: String,
isSelected: Boolean,
schema: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
tabUid: String,
connection: Object,
function: String,
isSelected: Boolean,
schema: String
});
const { const { addNotification } = useNotificationsStore();
getWorkspace, const workspacesStore = useWorkspacesStore();
refreshStructure,
renameTabs,
newTab,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
return { const {
addNotification, getWorkspace,
selectedWorkspace, refreshStructure,
getWorkspace, renameTabs,
refreshStructure, newTab,
renameTabs, changeBreadcrumbs,
newTab, setUnsavedChanges
changeBreadcrumbs, } = workspacesStore;
setUnsavedChanges
};
},
data () {
return {
isLoading: false,
isSaving: false,
isParamsModal: false,
isAskingParameters: false,
originalFunction: null,
localFunction: { sql: '' },
lastFunction: null,
sqlProxy: '',
editorHeight: 300
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
customizations () {
return this.workspace.customizations;
},
isChanged () {
return JSON.stringify(this.originalFunction) !== JSON.stringify(this.localFunction);
},
isDefinerInUsers () {
return this.originalFunction
? this.workspace.users.some(user => this.originalFunction.definer === `\`${user.name}\`@\`${user.host}\``)
: true;
},
isTableNameValid () {
return this.localFunction.name !== '';
},
isInDataTypes () {
let typeNames = [];
for (const group of this.workspace.dataTypes) {
typeNames = group.types.reduce((acc, curr) => {
acc.push(curr.name);
return acc;
}, []);
}
return typeNames.includes(this.localFunction.returns);
},
schemaTables () {
const schemaTables = this.workspace.structure
.filter(schema => schema.name === this.schema)
.map(schema => schema.tables);
return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : []; const queryEditor: Ref<Component & {editor: Ace.Editor; $el: HTMLElement}> = ref(null);
const firstInput: Ref<HTMLInputElement> = ref(null);
const isLoading = ref(false);
const isSaving = ref(false);
const isParamsModal = ref(false);
const isAskingParameters = ref(false);
const originalFunction: Ref<FunctionInfos> = ref(null);
const localFunction: Ref<FunctionInfos> = ref({ name: '', sql: '', definer: null });
const lastFunction = ref(null);
const sqlProxy = ref('');
const editorHeight = ref(300);
const workspace = computed(() => {
return getWorkspace(props.connection.uid);
});
const customizations = computed(() => {
return workspace.value.customizations;
});
const isChanged = computed(() => {
return JSON.stringify(originalFunction.value) !== JSON.stringify(localFunction.value);
});
const isTableNameValid = computed(() => {
return localFunction.value.name !== '';
});
const getFunctionData = async () => {
if (!props.function) return;
isLoading.value = true;
localFunction.value = { name: '', sql: '', definer: null };
lastFunction.value = props.function;
const params = {
uid: props.connection.uid,
schema: props.schema,
func: props.function
};
try {
const { status, response } = await Functions.getFunctionInformations(params);
if (status === 'success') {
originalFunction.value = response;
originalFunction.value.parameters = [...originalFunction.value.parameters.map(param => {
param._antares_id = uidGen();
return param;
})];
localFunction.value = JSON.parse(JSON.stringify(originalFunction.value));
sqlProxy.value = localFunction.value.sql;
} }
}, else
watch: { addNotification({ status: 'error', message: response });
async schema () { }
if (this.isSelected) { catch (err) {
await this.getFunctionData(); addNotification({ status: 'error', message: err.stack });
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql); }
this.lastFunction = this.function;
resizeQueryEditor();
isLoading.value = false;
};
const saveChanges = async () => {
if (isSaving.value) return;
isSaving.value = true;
const params = {
uid: props.connection.uid,
func: {
...localFunction.value,
schema: props.schema,
oldName: originalFunction.value.name
} as AlterFunctionParams
};
try {
const { status, response } = await Functions.alterFunction(params);
if (status === 'success') {
const oldName = originalFunction.value.name;
await refreshStructure(props.connection.uid);
if (oldName !== localFunction.value.name) {
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: oldName,
elementNewName: localFunction.value.name,
elementType: 'function'
});
changeBreadcrumbs({ schema: props.schema, function: localFunction.value.name });
} }
},
async function () {
if (this.isSelected) {
await this.getFunctionData();
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql);
this.lastFunction = this.function;
}
},
async isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, function: this.function });
setTimeout(() => {
this.resizeQueryEditor();
}, 200);
if (this.lastFunction !== this.function)
this.getRoutineData();
}
},
isChanged (val) {
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
}
},
async created () {
await this.getFunctionData();
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql);
window.addEventListener('keydown', this.onKey);
},
mounted () {
window.addEventListener('resize', this.resizeQueryEditor);
},
unmounted () {
window.removeEventListener('resize', this.resizeQueryEditor);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getFunctionData () {
if (!this.function) return;
this.isLoading = true;
this.localFunction = { sql: '' };
this.lastFunction = this.function;
const params = {
uid: this.connection.uid,
schema: this.schema,
func: this.function
};
try {
const { status, response } = await Functions.getFunctionInformations(params);
if (status === 'success') {
this.originalFunction = response;
this.originalFunction.parameters = [...this.originalFunction.parameters.map(param => {
param._antares_id = uidGen();
return param;
})];
this.localFunction = JSON.parse(JSON.stringify(this.originalFunction));
this.sqlProxy = this.localFunction.sql;
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor();
this.isLoading = false;
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
const params = {
uid: this.connection.uid,
func: {
...this.localFunction,
schema: this.schema,
oldName: this.originalFunction.name
}
};
try {
const { status, response } = await Functions.alterFunction(params);
if (status === 'success') {
const oldName = this.originalFunction.name;
await this.refreshStructure(this.connection.uid);
if (oldName !== this.localFunction.name) {
this.renameTabs({
uid: this.connection.uid,
schema: this.schema,
elementName: oldName,
elementNewName: this.localFunction.name,
elementType: 'function'
});
this.changeBreadcrumbs({ schema: this.schema, function: this.localFunction.name });
}
else
this.getFunctionData();
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false;
},
clearChanges () {
this.localFunction = JSON.parse(JSON.stringify(this.originalFunction));
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql);
},
resizeQueryEditor () {
if (this.$refs.queryEditor) {
const footer = document.getElementById('footer');
const size = window.innerHeight - this.$refs.queryEditor.$el.getBoundingClientRect().top - footer.offsetHeight;
this.editorHeight = size;
this.$refs.queryEditor.editor.resize();
}
},
optionsUpdate (options) {
this.localFunction = options;
},
parametersUpdate (parameters) {
this.localFunction = { ...this.localFunction, parameters };
},
runFunctionCheck () {
if (this.localFunction.parameters.length)
this.showAskParamsModal();
else else
this.runFunction(); getFunctionData();
}, }
runFunction (params) { else
if (!params) params = []; addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
let sql; isSaving.value = false;
switch (this.connection.client) { // TODO: move in a better place };
case 'maria':
case 'mysql':
sql = `SELECT \`${this.originalFunction.name}\` (${params.join(',')})`;
break;
case 'pg':
sql = `SELECT ${this.originalFunction.name}(${params.join(',')})`;
break;
case 'mssql':
sql = `SELECT ${this.originalFunction.name} ${params.join(',')}`;
break;
default:
sql = `SELECT \`${this.originalFunction.name}\` (${params.join(',')})`;
}
this.newTab({ uid: this.connection.uid, content: sql, type: 'query', autorun: true }); const clearChanges = () => {
}, localFunction.value = JSON.parse(JSON.stringify(originalFunction.value));
showParamsModal () { queryEditor.value.editor.session.setValue(localFunction.value.sql);
this.isParamsModal = true; };
},
hideParamsModal () { const resizeQueryEditor = () => {
this.isParamsModal = false; if (queryEditor.value) {
}, const footer = document.getElementById('footer');
showAskParamsModal () { const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
this.isAskingParameters = true; editorHeight.value = size;
}, queryEditor.value.editor.resize();
hideAskParamsModal () { }
this.isAskingParameters = false; };
},
onKey (e) { const parametersUpdate = (parameters: FunctionParam[]) => {
if (this.isSelected) { localFunction.value = { ...localFunction.value, parameters };
e.stopPropagation(); };
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (this.isChanged) const runFunctionCheck = () => {
this.saveChanges(); if (localFunction.value.parameters.length)
} showAskParamsModal();
} else
runFunction();
};
const runFunction = (params?: string[]) => {
if (!params) params = [];
let sql;
switch (props.connection.client) { // TODO: move in a better place
case 'maria':
case 'mysql':
sql = `SELECT \`${originalFunction.value.name}\` (${params.join(',')})`;
break;
case 'pg':
sql = `SELECT ${originalFunction.value.name}(${params.join(',')})`;
break;
case 'mssql':
sql = `SELECT ${originalFunction.value.name} ${params.join(',')}`;
break;
default:
sql = `SELECT \`${originalFunction.value.name}\` (${params.join(',')})`;
}
newTab({ uid: props.connection.uid, content: sql, type: 'query', autorun: true });
};
const showParamsModal = () => {
isParamsModal.value = true;
};
const hideParamsModal = () => {
isParamsModal.value = false;
};
const showAskParamsModal = () => {
isAskingParameters.value = true;
};
const hideAskParamsModal = () => {
isAskingParameters.value = false;
};
const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (isChanged.value)
saveChanges();
} }
} }
}; };
watch(() => props.schema, async () => {
if (props.isSelected) {
await getFunctionData();
queryEditor.value.editor.session.setValue(localFunction.value.sql);
lastFunction.value = props.function;
}
});
watch(() => props.function, async () => {
if (props.isSelected) {
await getFunctionData();
queryEditor.value.editor.session.setValue(localFunction.value.sql);
lastFunction.value = props.function;
}
});
watch(() => props.isSelected, async (val) => {
if (val) {
changeBreadcrumbs({ schema: props.schema, function: props.function });
setTimeout(() => {
resizeQueryEditor();
}, 200);
if (lastFunction.value !== props.function)
getFunctionData();
}
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
(async () => {
await getFunctionData();
queryEditor.value.editor.session.setValue(localFunction.value.sql);
window.addEventListener('keydown', onKey);
})();
onMounted(() => {
window.addEventListener('resize', resizeQueryEditor);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeQueryEditor);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script> </script>

View File

@ -1,6 +1,6 @@
<template> <template>
<ConfirmModal <ConfirmModal
:confirm-text="$t('word.confirm')" :confirm-text="t('word.confirm')"
size="medium" size="medium"
class="options-modal" class="options-modal"
@confirm="confirmParametersChange" @confirm="confirmParametersChange"
@ -9,7 +9,7 @@
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" /> <i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span class="cut-text">{{ $t('word.parameters') }} "{{ func }}"</span> <span class="cut-text">{{ t('word.parameters') }} "{{ func }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -20,16 +20,16 @@
<div class="d-flex"> <div class="d-flex">
<button class="btn btn-dark btn-sm d-flex" @click="addParameter"> <button class="btn btn-dark btn-sm d-flex" @click="addParameter">
<i class="mdi mdi-24px mdi-plus mr-1" /> <i class="mdi mdi-24px mdi-plus mr-1" />
<span>{{ $t('word.add') }}</span> <span>{{ t('word.add') }}</span>
</button> </button>
<button <button
class="btn btn-dark btn-sm d-flex ml-2 mr-0" class="btn btn-dark btn-sm d-flex ml-2 mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
:disabled="!isChanged" :disabled="!isChanged"
@click.prevent="clearChanges" @click.prevent="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
</div> </div>
@ -55,7 +55,7 @@
<div class="tile-action"> <div class="tile-action">
<button <button
class="btn btn-link remove-field p-0 mr-2" class="btn btn-link remove-field p-0 mr-2"
:title="$t('word.delete')" :title="t('word.delete')"
@click.prevent="removeParameter(param._antares_id)" @click.prevent="removeParameter(param._antares_id)"
> >
<i class="mdi mdi-close" /> <i class="mdi mdi-close" />
@ -74,7 +74,7 @@
> >
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -86,7 +86,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.type') }} {{ t('word.type') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
@ -102,7 +102,7 @@
</div> </div>
<div v-if="customizations.parametersLength" class="form-group"> <div v-if="customizations.parametersLength" class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.length') }} {{ t('word.length') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -115,7 +115,7 @@
</div> </div>
<div v-if="customizations.functionContext" class="form-group"> <div v-if="customizations.functionContext" class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.context') }} {{ t('word.context') }}
</label> </label>
<div class="column"> <div class="column">
<label class="form-radio"> <label class="form-radio">
@ -150,11 +150,11 @@
<i class="mdi mdi-dots-horizontal mdi-48px" /> <i class="mdi mdi-dots-horizontal mdi-48px" />
</div> </div>
<p class="empty-title h5"> <p class="empty-title h5">
{{ $t('message.thereAreNoParameters') }} {{ t('message.thereAreNoParameters') }}
</p> </p>
<div class="empty-action"> <div class="empty-action">
<button class="btn btn-primary" @click="addParameter"> <button class="btn btn-primary" @click="addParameter">
{{ $t('message.createNewParameter') }} {{ t('message.createNewParameter') }}
</button> </button>
</div> </div>
</div> </div>
@ -164,113 +164,118 @@
</ConfirmModal> </ConfirmModal>
</template> </template>
<script> <script setup lang="ts">
import { computed, onMounted, onUnmounted, Ref, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { uidGen } from 'common/libs/uidGen'; import { uidGen } from 'common/libs/uidGen';
import ConfirmModal from '@/components/BaseConfirmModal'; import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsFunctionParamsModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
localParameters: {
type: Array,
default: () => []
},
func: String,
workspace: Object
},
emits: ['hide', 'parameters-update'],
data () {
return {
parametersProxy: [],
isOptionsChanging: false,
selectedParam: '',
modalInnerHeight: 400,
i: 1
};
},
computed: {
selectedParamObj () {
return this.parametersProxy.find(param => param._antares_id === this.selectedParam);
},
isChanged () {
return JSON.stringify(this.localParameters) !== JSON.stringify(this.parametersProxy);
},
customizations () {
return this.workspace.customizations;
}
},
mounted () {
this.parametersProxy = JSON.parse(JSON.stringify(this.localParameters));
this.i = this.parametersProxy.length + 1;
if (this.parametersProxy.length) const props = defineProps({
this.resetSelectedID(); localParameters: {
type: Array,
this.getModalInnerHeight(); default: () => []
window.addEventListener('resize', this.getModalInnerHeight);
}, },
unmounted () { func: String,
window.removeEventListener('resize', this.getModalInnerHeight); workspace: Object
}, });
methods: {
typeClass (type) {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
},
confirmParametersChange () {
this.$emit('parameters-update', this.parametersProxy);
},
selectParameter (event, uid) {
if (this.selectedParam !== uid && !event.target.classList.contains('remove-field'))
this.selectedParam = uid;
},
getModalInnerHeight () {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
this.modalInnerHeight = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
},
addParameter () {
const newUid = uidGen();
this.parametersProxy = [...this.parametersProxy, {
_antares_id: newUid,
name: `param${this.i++}`,
type: this.workspace.dataTypes[0].types[0].name,
context: 'IN',
length: ''
}];
if (this.parametersProxy.length === 1) const emit = defineEmits(['hide', 'parameters-update']);
this.resetSelectedID();
setTimeout(() => { const parametersPanel: Ref<HTMLDivElement> = ref(null);
this.$refs.parametersPanel.scrollTop = this.$refs.parametersPanel.scrollHeight + 60; const parametersProxy = ref([]);
this.selectedParam = newUid; const selectedParam = ref('');
}, 20); const modalInnerHeight = ref(400);
}, const i = ref(1);
removeParameter (uid) {
this.parametersProxy = this.parametersProxy.filter(param => param._antares_id !== uid);
if (this.parametersProxy.length && this.selectedParam === uid) const selectedParamObj = computed(() => {
this.resetSelectedID(); return parametersProxy.value.find(param => param._antares_id === selectedParam.value);
}, });
clearChanges () {
this.parametersProxy = JSON.parse(JSON.stringify(this.localParameters));
this.i = this.parametersProxy.length + 1;
if (!this.parametersProxy.some(param => param.name === this.selectedParam)) const isChanged = computed(() => {
this.resetSelectedID(); return JSON.stringify(props.localParameters) !== JSON.stringify(parametersProxy.value);
}, });
resetSelectedID () {
this.selectedParam = this.parametersProxy.length ? this.parametersProxy[0]._antares_id : ''; const customizations = computed(() => {
} return props.workspace.customizations;
} });
const typeClass = (type: string) => {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
}; };
const confirmParametersChange = () => {
emit('parameters-update', parametersProxy.value);
};
const selectParameter = (event: MouseEvent, uid: string) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (selectedParam.value !== uid && !(event.target as any).classList.contains('remove-field'))
selectedParam.value = uid;
};
const getModalInnerHeight = () => {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
modalInnerHeight.value = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
};
const addParameter = () => {
const newUid = uidGen();
parametersProxy.value = [...parametersProxy.value, {
_antares_id: newUid,
name: `param${i.value++}`,
type: props.workspace.dataTypes[0].types[0].name,
context: 'IN',
length: ''
}];
if (parametersProxy.value.length === 1)
resetSelectedID();
setTimeout(() => {
parametersPanel.value.scrollTop = parametersPanel.value.scrollHeight + 60;
selectedParam.value = newUid;
}, 20);
};
const removeParameter = (uid: string) => {
parametersProxy.value = parametersProxy.value.filter(param => param._antares_id !== uid);
if (parametersProxy.value.length && selectedParam.value === uid)
resetSelectedID();
};
const clearChanges = () => {
parametersProxy.value = JSON.parse(JSON.stringify(props.localParameters));
i.value = parametersProxy.value.length + 1;
if (!parametersProxy.value.some(param => param.name === selectedParam.value))
resetSelectedID();
};
const resetSelectedID = () => {
selectedParam.value = parametersProxy.value.length ? parametersProxy.value[0]._antares_id : '';
};
onMounted(() => {
parametersProxy.value = JSON.parse(JSON.stringify(props.localParameters));
i.value = parametersProxy.value.length + 1;
if (parametersProxy.value.length)
resetSelectedID();
getModalInnerHeight();
window.addEventListener('resize', getModalInnerHeight);
});
onUnmounted(() => {
window.removeEventListener('resize', getModalInnerHeight);
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -11,16 +11,16 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
<div class="divider-vert py-3" /> <div class="divider-vert py-3" />
@ -31,15 +31,15 @@
@click="runRoutineCheck" @click="runRoutineCheck"
> >
<i class="mdi mdi-24px mdi-play mr-1" /> <i class="mdi mdi-24px mdi-play mr-1" />
<span>{{ $t('word.run') }}</span> <span>{{ t('word.run') }}</span>
</button> </button>
<button class="btn btn-dark btn-sm" @click="showParamsModal"> <button class="btn btn-dark btn-sm" @click="showParamsModal">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" /> <i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span>{{ $t('word.parameters') }}</span> <span>{{ t('word.parameters') }}</span>
</button> </button>
</div> </div>
<div class="workspace-query-info"> <div class="workspace-query-info">
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -50,7 +50,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<input <input
ref="firstInput" ref="firstInput"
@ -64,7 +64,7 @@
<div v-if="customizations.languages" class="column col-auto"> <div v-if="customizations.languages" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.language') }} {{ t('word.language') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localRoutine.language" v-model="localRoutine.language"
@ -76,13 +76,13 @@
<div v-if="customizations.definer" class="column col-auto"> <div v-if="customizations.definer" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.definer') }} {{ t('word.definer') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localRoutine.definer" v-model="localRoutine.definer"
:options="[{value: '', name:$t('message.currentUser')}, ...workspace.users]" :options="[{value: '', name: t('message.currentUser')}, ...workspace.users]"
:option-label="(user) => user.value === '' ? user.name : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? user.name : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
/> />
</div> </div>
@ -90,7 +90,7 @@
<div v-if="customizations.comment" class="column"> <div v-if="customizations.comment" class="column">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.comment') }} {{ t('word.comment') }}
</label> </label>
<input <input
v-model="localRoutine.comment" v-model="localRoutine.comment"
@ -102,7 +102,7 @@
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('message.sqlSecurity') }} {{ t('message.sqlSecurity') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localRoutine.security" v-model="localRoutine.security"
@ -114,7 +114,7 @@
<div v-if="customizations.procedureDataAccess" class="column col-auto"> <div v-if="customizations.procedureDataAccess" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('message.dataAccess') }} {{ t('message.dataAccess') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localRoutine.dataAccess" v-model="localRoutine.dataAccess"
@ -127,7 +127,7 @@
<div class="form-group"> <div class="form-group">
<label class="form-label d-invisible">.</label> <label class="form-label d-invisible">.</label>
<label class="form-checkbox form-inline"> <label class="form-checkbox form-inline">
<input v-model="localRoutine.deterministic" type="checkbox"><i class="form-icon" /> {{ $t('word.deterministic') }} <input v-model="localRoutine.deterministic" type="checkbox"><i class="form-icon" /> {{ t('word.deterministic') }}
</label> </label>
</div> </div>
</div> </div>
@ -135,7 +135,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.routineBody') }}</label> <label class="form-label ml-2">{{ t('message.routineBody') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -163,286 +163,272 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onUnmounted, onBeforeUnmount, onMounted, Ref, ref, watch } from 'vue';
import { AlterRoutineParams, FunctionParam, RoutineInfos } from 'common/interfaces/antares';
import { Ace } from 'ace-builds';
import { useI18n } from 'vue-i18n';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import { uidGen } from 'common/libs/uidGen'; import { uidGen } from 'common/libs/uidGen';
import QueryEditor from '@/components/QueryEditor';
import BaseLoader from '@/components/BaseLoader';
import WorkspaceTabPropsRoutineParamsModal from '@/components/WorkspaceTabPropsRoutineParamsModal';
import ModalAskParameters from '@/components/ModalAskParameters';
import Routines from '@/ipc-api/Routines'; import Routines from '@/ipc-api/Routines';
import QueryEditor from '@/components/QueryEditor.vue';
import BaseLoader from '@/components/BaseLoader.vue';
import WorkspaceTabPropsRoutineParamsModal from '@/components/WorkspaceTabPropsRoutineParamsModal.vue';
import ModalAskParameters from '@/components/ModalAskParameters.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsRoutine',
components: {
QueryEditor,
BaseLoader,
WorkspaceTabPropsRoutineParamsModal,
ModalAskParameters,
BaseSelect
},
props: {
tabUid: String,
connection: Object,
routine: String,
isSelected: Boolean,
schema: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
tabUid: String,
connection: Object,
routine: String,
isSelected: Boolean,
schema: String
});
const { const { addNotification } = useNotificationsStore();
getWorkspace, const workspacesStore = useWorkspacesStore();
refreshStructure,
renameTabs,
newTab,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
return { const {
addNotification, getWorkspace,
selectedWorkspace, refreshStructure,
getWorkspace, renameTabs,
refreshStructure, newTab,
renameTabs, changeBreadcrumbs,
newTab, setUnsavedChanges
changeBreadcrumbs, } = workspacesStore;
setUnsavedChanges
};
},
data () {
return {
isLoading: false,
isSaving: false,
isParamsModal: false,
isAskingParameters: false,
originalRoutine: null,
localRoutine: { sql: '' },
lastRoutine: null,
sqlProxy: '',
editorHeight: 300
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
customizations () {
return this.workspace.customizations;
},
isChanged () {
return JSON.stringify(this.originalRoutine) !== JSON.stringify(this.localRoutine);
},
isDefinerInUsers () {
return this.originalRoutine ? this.workspace.users.some(user => this.originalRoutine.definer === `\`${user.name}\`@\`${user.host}\``) : true;
},
isTableNameValid () {
return this.localRoutine.name !== '';
},
schemaTables () {
const schemaTables = this.workspace.structure
.filter(schema => schema.name === this.schema)
.map(schema => schema.tables);
return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : []; const queryEditor: Ref<Component & {editor: Ace.Editor; $el: HTMLElement}> = ref(null);
const firstInput: Ref<HTMLInputElement> = ref(null);
const isLoading = ref(false);
const isSaving = ref(false);
const isParamsModal = ref(false);
const isAskingParameters = ref(false);
const originalRoutine: Ref<RoutineInfos> = ref(null);
const localRoutine: Ref<RoutineInfos> = ref(null);
const lastRoutine = ref(null);
const sqlProxy = ref('');
const editorHeight = ref(300);
const workspace = computed(() => {
return getWorkspace(props.connection.uid);
});
const customizations = computed(() => {
return workspace.value.customizations;
});
const isChanged = computed(() => {
return JSON.stringify(originalRoutine.value) !== JSON.stringify(localRoutine.value);
});
const isTableNameValid = computed(() => {
return localRoutine.value.name !== '';
});
const getRoutineData = async () => {
if (!props.routine) return;
localRoutine.value = { name: '', sql: '', definer: null };
isLoading.value = true;
lastRoutine.value = props.routine;
const params = {
uid: props.connection.uid,
schema: props.schema,
routine: props.routine
};
try {
const { status, response } = await Routines.getRoutineInformations(params);
if (status === 'success') {
originalRoutine.value = response;
originalRoutine.value.parameters = [...originalRoutine.value.parameters.map(param => {
param._antares_id = uidGen();
return param;
})];
localRoutine.value = JSON.parse(JSON.stringify(originalRoutine.value));
sqlProxy.value = localRoutine.value.sql;
} }
}, else
watch: { addNotification({ status: 'error', message: response });
async schema () { }
if (this.isSelected) { catch (err) {
await this.getRoutineData(); addNotification({ status: 'error', message: err.stack });
this.$refs.queryEditor.editor.session.setValue(this.localRoutine.sql); }
this.lastRoutine = this.routine;
resizeQueryEditor();
isLoading.value = false;
};
const saveChanges = async () => {
if (isSaving.value) return;
isSaving.value = true;
const params = {
uid: props.connection.uid as string,
routine: {
...localRoutine.value,
schema: props.schema,
oldName: originalRoutine.value.name
} as AlterRoutineParams
};
try {
const { status, response } = await Routines.alterRoutine(params);
if (status === 'success') {
const oldName = originalRoutine.value.name;
await refreshStructure(props.connection.uid);
if (oldName !== localRoutine.value.name) {
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: oldName,
elementNewName: localRoutine.value.name,
elementType: 'procedure'
});
changeBreadcrumbs({ schema: props.schema, routine: localRoutine.value.name });
} }
},
async routine () {
if (this.isSelected) {
await this.getRoutineData();
this.$refs.queryEditor.editor.session.setValue(this.localRoutine.sql);
this.lastRoutine = this.routine;
}
},
async isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, routine: this.routine });
setTimeout(() => {
this.resizeQueryEditor();
}, 200);
if (this.lastRoutine !== this.routine)
this.getRoutineData();
}
},
isChanged (val) {
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
}
},
async created () {
await this.getRoutineData();
this.$refs.queryEditor.editor.session.setValue(this.localRoutine.sql);
window.addEventListener('keydown', this.onKey);
},
mounted () {
window.addEventListener('resize', this.resizeQueryEditor);
},
unmounted () {
window.removeEventListener('resize', this.resizeQueryEditor);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getRoutineData () {
if (!this.routine) return;
this.localRoutine = { sql: '' };
this.isLoading = true;
this.lastRoutine = this.routine;
const params = {
uid: this.connection.uid,
schema: this.schema,
routine: this.routine
};
try {
const { status, response } = await Routines.getRoutineInformations(params);
if (status === 'success') {
this.originalRoutine = response;
this.originalRoutine.parameters = [...this.originalRoutine.parameters.map(param => {
param._antares_id = uidGen();
return param;
})];
this.localRoutine = JSON.parse(JSON.stringify(this.originalRoutine));
this.sqlProxy = this.localRoutine.sql;
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor();
this.isLoading = false;
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
const params = {
uid: this.connection.uid,
routine: {
...this.localRoutine,
schema: this.schema,
oldName: this.originalRoutine.name
}
};
try {
const { status, response } = await Routines.alterRoutine(params);
if (status === 'success') {
const oldName = this.originalRoutine.name;
await this.refreshStructure(this.connection.uid);
if (oldName !== this.localRoutine.name) {
this.renameTabs({
uid: this.connection.uid,
schema: this.schema,
elementName: oldName,
elementNewName: this.localRoutine.name,
elementType: 'procedure'
});
this.changeBreadcrumbs({ schema: this.schema, procedure: this.localRoutine.name });
}
else
this.getRoutineData();
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false;
},
clearChanges () {
this.localRoutine = JSON.parse(JSON.stringify(this.originalRoutine));
this.$refs.queryEditor.editor.session.setValue(this.localRoutine.sql);
},
resizeQueryEditor () {
if (this.$refs.queryEditor) {
const footer = document.getElementById('footer');
const size = window.innerHeight - this.$refs.queryEditor.$el.getBoundingClientRect().top - footer.offsetHeight;
this.editorHeight = size;
this.$refs.queryEditor.editor.resize();
}
},
optionsUpdate (options) {
this.localRoutine = options;
},
parametersUpdate (parameters) {
this.localRoutine = { ...this.localRoutine, parameters };
},
runRoutineCheck () {
if (this.localRoutine.parameters.length)
this.showAskParamsModal();
else else
this.runRoutine(); getRoutineData();
}, }
runRoutine (params) { else
if (!params) params = []; addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
let sql; isSaving.value = false;
switch (this.connection.client) { // TODO: move in a better place };
case 'maria':
case 'mysql':
case 'pg':
sql = `CALL ${this.originalRoutine.name}(${params.join(',')})`;
break;
case 'mssql':
sql = `EXEC ${this.originalRoutine.name} ${params.join(',')}`;
break;
default:
sql = `CALL \`${this.originalRoutine.name}\`(${params.join(',')})`;
}
this.newTab({ uid: this.connection.uid, content: sql, type: 'query', autorun: true }); const clearChanges = () => {
}, localRoutine.value = JSON.parse(JSON.stringify(originalRoutine.value));
showParamsModal () { queryEditor.value.editor.session.setValue(localRoutine.value.sql);
this.isParamsModal = true; };
},
hideParamsModal () { const resizeQueryEditor = () => {
this.isParamsModal = false; if (queryEditor.value) {
}, const footer = document.getElementById('footer');
showAskParamsModal () { const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
this.isAskingParameters = true; editorHeight.value = size;
}, queryEditor.value.editor.resize();
hideAskParamsModal () { }
this.isAskingParameters = false; };
},
onKey (e) { const parametersUpdate = (parameters: FunctionParam[]) => {
if (this.isSelected) { localRoutine.value = { ...localRoutine.value, parameters };
e.stopPropagation(); };
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (this.isChanged) const runRoutineCheck = () => {
this.saveChanges(); if (localRoutine.value.parameters.length)
} showAskParamsModal();
} else
runRoutine();
};
const runRoutine = (params?: string[]) => {
if (!params) params = [];
let sql;
switch (props.connection.client) { // TODO: move in a better place
case 'maria':
case 'mysql':
case 'pg':
sql = `CALL ${originalRoutine.value.name}(${params.join(',')})`;
break;
case 'mssql':
sql = `EXEC ${originalRoutine.value.name} ${params.join(',')}`;
break;
default:
sql = `CALL \`${originalRoutine.value.name}\`(${params.join(',')})`;
}
newTab({ uid: props.connection.uid, content: sql, type: 'query', autorun: true });
};
const showParamsModal = () => {
isParamsModal.value = true;
};
const hideParamsModal = () => {
isParamsModal.value = false;
};
const showAskParamsModal = () => {
isAskingParameters.value = true;
};
const hideAskParamsModal = () => {
isAskingParameters.value = false;
};
const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.key === 's') { // CTRL + S
if (isChanged.value)
saveChanges();
} }
} }
}; };
watch(() => props.schema, async () => {
if (props.isSelected) {
await getRoutineData();
queryEditor.value.editor.session.setValue(localRoutine.value.sql);
lastRoutine.value = props.routine;
}
});
watch(() => props.routine, async () => {
if (props.isSelected) {
await getRoutineData();
queryEditor.value.editor.session.setValue(localRoutine.value.sql);
lastRoutine.value = props.routine;
}
});
watch(() => props.isSelected, async (val) => {
if (val) {
changeBreadcrumbs({ schema: props.schema, routine: props.routine });
setTimeout(() => {
resizeQueryEditor();
}, 200);
if (lastRoutine.value !== props.routine)
getRoutineData();
}
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
(async () => {
await getRoutineData();
queryEditor.value.editor.session.setValue(localRoutine.value.sql);
window.addEventListener('keydown', onKey);
})();
onMounted(() => {
window.addEventListener('resize', resizeQueryEditor);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeQueryEditor);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script> </script>

View File

@ -1,6 +1,6 @@
<template> <template>
<ConfirmModal <ConfirmModal
:confirm-text="$t('word.confirm')" :confirm-text="t('word.confirm')"
size="medium" size="medium"
class="options-modal" class="options-modal"
@confirm="confirmParametersChange" @confirm="confirmParametersChange"
@ -9,7 +9,7 @@
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" /> <i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span class="cut-text">{{ $t('word.parameters') }} "{{ routine }}"</span> <span class="cut-text">{{ t('word.parameters') }} "{{ routine }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -20,16 +20,16 @@
<div class="d-flex"> <div class="d-flex">
<button class="btn btn-dark btn-sm d-flex" @click="addParameter"> <button class="btn btn-dark btn-sm d-flex" @click="addParameter">
<i class="mdi mdi-24px mdi-plus mr-1" /> <i class="mdi mdi-24px mdi-plus mr-1" />
<span>{{ $t('word.add') }}</span> <span>{{ t('word.add') }}</span>
</button> </button>
<button <button
class="btn btn-dark btn-sm d-flex ml-2 mr-0" class="btn btn-dark btn-sm d-flex ml-2 mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
:disabled="!isChanged" :disabled="!isChanged"
@click.prevent="clearChanges" @click.prevent="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
</div> </div>
@ -55,7 +55,7 @@
<div class="tile-action"> <div class="tile-action">
<button <button
class="btn btn-link remove-field p-0 mr-2" class="btn btn-link remove-field p-0 mr-2"
:title="$t('word.delete')" :title="t('word.delete')"
@click.prevent="removeParameter(param._antares_id)" @click.prevent="removeParameter(param._antares_id)"
> >
<i class="mdi mdi-close" /> <i class="mdi mdi-close" />
@ -74,7 +74,7 @@
> >
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -86,7 +86,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.type') }} {{ t('word.type') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
@ -102,7 +102,7 @@
</div> </div>
<div v-if="customizations.parametersLength" class="form-group"> <div v-if="customizations.parametersLength" class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.length') }} {{ t('word.length') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -115,7 +115,7 @@
</div> </div>
<div v-if="customizations.procedureContext" class="form-group"> <div v-if="customizations.procedureContext" class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.context') }} {{ t('word.context') }}
</label> </label>
<div class="column"> <div class="column">
<label class="form-radio"> <label class="form-radio">
@ -150,11 +150,11 @@
<i class="mdi mdi-dots-horizontal mdi-48px" /> <i class="mdi mdi-dots-horizontal mdi-48px" />
</div> </div>
<p class="empty-title h5"> <p class="empty-title h5">
{{ $t('message.thereAreNoParameters') }} {{ t('message.thereAreNoParameters') }}
</p> </p>
<div class="empty-action"> <div class="empty-action">
<button class="btn btn-primary" @click="addParameter"> <button class="btn btn-primary" @click="addParameter">
{{ $t('message.createNewParameter') }} {{ t('message.createNewParameter') }}
</button> </button>
</div> </div>
</div> </div>
@ -164,113 +164,118 @@
</ConfirmModal> </ConfirmModal>
</template> </template>
<script> <script setup lang="ts">
import { computed, onMounted, onUnmounted, Ref, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { uidGen } from 'common/libs/uidGen'; import { uidGen } from 'common/libs/uidGen';
import ConfirmModal from '@/components/BaseConfirmModal'; import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsRoutineParamsModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
localParameters: {
type: Array,
default: () => []
},
routine: String,
workspace: Object
},
emits: ['parameters-update', 'hide'],
data () {
return {
parametersProxy: [],
isOptionsChanging: false,
selectedParam: '',
modalInnerHeight: 400,
i: 1
};
},
computed: {
selectedParamObj () {
return this.parametersProxy.find(param => param._antares_id === this.selectedParam);
},
isChanged () {
return JSON.stringify(this.localParameters) !== JSON.stringify(this.parametersProxy);
},
customizations () {
return this.workspace.customizations;
}
},
mounted () {
this.parametersProxy = JSON.parse(JSON.stringify(this.localParameters));
this.i = this.parametersProxy.length + 1;
if (this.parametersProxy.length) const props = defineProps({
this.resetSelectedID(); localParameters: {
type: Array,
this.getModalInnerHeight(); default: () => []
window.addEventListener('resize', this.getModalInnerHeight);
}, },
unmounted () { routine: String,
window.removeEventListener('resize', this.getModalInnerHeight); workspace: Object
}, });
methods: {
typeClass (type) {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
},
confirmParametersChange () {
this.$emit('parameters-update', this.parametersProxy);
},
selectParameter (event, uid) {
if (this.selectedParam !== uid && !event.target.classList.contains('remove-field'))
this.selectedParam = uid;
},
getModalInnerHeight () {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
this.modalInnerHeight = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
},
addParameter () {
const newUid = uidGen();
this.parametersProxy = [...this.parametersProxy, {
_antares_id: newUid,
name: `param${this.i++}`,
type: this.workspace.dataTypes[0].types[0].name,
context: 'IN',
length: ''
}];
if (this.parametersProxy.length === 1) const emit = defineEmits(['hide', 'parameters-update']);
this.resetSelectedID();
setTimeout(() => { const parametersPanel: Ref<HTMLDivElement> = ref(null);
this.$refs.parametersPanel.scrollTop = this.$refs.parametersPanel.scrollHeight + 60; const parametersProxy = ref([]);
this.selectedParam = newUid; const selectedParam = ref('');
}, 20); const modalInnerHeight = ref(400);
}, const i = ref(1);
removeParameter (uid) {
this.parametersProxy = this.parametersProxy.filter(param => param._antares_id !== uid);
if (this.parametersProxy.length && this.selectedParam === uid) const selectedParamObj = computed(() => {
this.resetSelectedID(); return parametersProxy.value.find(param => param._antares_id === selectedParam.value);
}, });
clearChanges () {
this.parametersProxy = JSON.parse(JSON.stringify(this.localParameters));
this.i = this.parametersProxy.length + 1;
if (!this.parametersProxy.some(param => param.name === this.selectedParam)) const isChanged = computed(() => {
this.resetSelectedID(); return JSON.stringify(props.localParameters) !== JSON.stringify(parametersProxy.value);
}, });
resetSelectedID () {
this.selectedParam = this.parametersProxy.length ? this.parametersProxy[0]._antares_id : ''; const customizations = computed(() => {
} return props.workspace.customizations;
} });
const typeClass = (type: string) => {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
}; };
const confirmParametersChange = () => {
emit('parameters-update', parametersProxy.value);
};
const selectParameter = (event: MouseEvent, uid: string) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (selectedParam.value !== uid && !(event.target as any).classList.contains('remove-field'))
selectedParam.value = uid;
};
const getModalInnerHeight = () => {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
modalInnerHeight.value = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
};
const addParameter = () => {
const newUid = uidGen();
parametersProxy.value = [...parametersProxy.value, {
_antares_id: newUid,
name: `param${i.value++}`,
type: props.workspace.dataTypes[0].types[0].name,
context: 'IN',
length: ''
}];
if (parametersProxy.value.length === 1)
resetSelectedID();
setTimeout(() => {
parametersPanel.value.scrollTop = parametersPanel.value.scrollHeight + 60;
selectedParam.value = newUid;
}, 20);
};
const removeParameter = (uid: string) => {
parametersProxy.value = parametersProxy.value.filter(param => param._antares_id !== uid);
if (parametersProxy.value.length && selectedParam.value === uid)
resetSelectedID();
};
const clearChanges = () => {
parametersProxy.value = JSON.parse(JSON.stringify(props.localParameters));
i.value = parametersProxy.value.length + 1;
if (!parametersProxy.value.some(param => param.name === selectedParam.value))
resetSelectedID();
};
const resetSelectedID = () => {
selectedParam.value = parametersProxy.value.length ? parametersProxy.value[0]._antares_id : '';
};
onMounted(() => {
parametersProxy.value = JSON.parse(JSON.stringify(props.localParameters));
i.value = parametersProxy.value.length + 1;
if (parametersProxy.value.length)
resetSelectedID();
getModalInnerHeight();
window.addEventListener('resize', getModalInnerHeight);
});
onUnmounted(() => {
window.removeEventListener('resize', getModalInnerHeight);
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -11,26 +11,26 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
<div class="divider-vert py-3" /> <div class="divider-vert py-3" />
<button class="btn btn-dark btn-sm" @click="showTimingModal"> <button class="btn btn-dark btn-sm" @click="showTimingModal">
<i class="mdi mdi-24px mdi-timer mr-1" /> <i class="mdi mdi-24px mdi-timer mr-1" />
<span>{{ $t('word.timing') }}</span> <span>{{ t('word.timing') }}</span>
</button> </button>
</div> </div>
<div class="workspace-query-info"> <div class="workspace-query-info">
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -40,7 +40,7 @@
<div class="columns"> <div class="columns">
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.name') }}</label> <label class="form-label">{{ t('word.name') }}</label>
<input <input
v-model="localScheduler.name" v-model="localScheduler.name"
class="form-input" class="form-input"
@ -50,19 +50,19 @@
</div> </div>
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.definer') }}</label> <label class="form-label">{{ t('word.definer') }}</label>
<BaseSelect <BaseSelect
v-model="localScheduler.definer" v-model="localScheduler.definer"
:options="users" :options="users"
:option-label="(user) => user.value === '' ? $t('message.currentUser') : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? t('message.currentUser') : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
/> />
</div> </div>
</div> </div>
<div class="column"> <div class="column">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.comment') }}</label> <label class="form-label">{{ t('word.comment') }}</label>
<input <input
v-model="localScheduler.comment" v-model="localScheduler.comment"
class="form-input" class="form-input"
@ -72,7 +72,7 @@
</div> </div>
<div class="column"> <div class="column">
<div class="form-group"> <div class="form-group">
<label class="form-label mr-2">{{ $t('word.state') }}</label> <label class="form-label mr-2">{{ t('word.state') }}</label>
<label class="form-radio form-inline"> <label class="form-radio form-inline">
<input <input
v-model="localScheduler.state" v-model="localScheduler.state"
@ -103,7 +103,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.schedulerBody') }}</label> <label class="form-label ml-2">{{ t('message.schedulerBody') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -122,245 +122,231 @@
/> />
</div> </div>
</template> </template>
<script setup lang="ts">
<script> import { AlterEventParams, EventInfos } from 'common/interfaces/antares';
import { storeToRefs } from 'pinia'; import { Component, computed, onBeforeUnmount, onMounted, onUnmounted, Ref, ref, watch } from 'vue';
import { Ace } from 'ace-builds';
import { useI18n } from 'vue-i18n';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import BaseLoader from '@/components/BaseLoader'; import BaseLoader from '@/components/BaseLoader.vue';
import QueryEditor from '@/components/QueryEditor'; import QueryEditor from '@/components/QueryEditor.vue';
import WorkspaceTabPropsSchedulerTimingModal from '@/components/WorkspaceTabPropsSchedulerTimingModal'; import WorkspaceTabPropsSchedulerTimingModal from '@/components/WorkspaceTabPropsSchedulerTimingModal.vue';
import Schedulers from '@/ipc-api/Schedulers';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import Schedulers from '@/ipc-api/Schedulers';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsScheduler',
components: {
BaseLoader,
QueryEditor,
WorkspaceTabPropsSchedulerTimingModal,
BaseSelect
},
props: {
tabUid: String,
connection: Object,
scheduler: String,
isSelected: Boolean,
schema: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
tabUid: String,
connection: Object,
scheduler: String,
isSelected: Boolean,
schema: String
});
const { const { addNotification } = useNotificationsStore();
getWorkspace, const workspacesStore = useWorkspacesStore();
refreshStructure,
renameTabs,
newTab,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
return { const {
addNotification, getWorkspace,
selectedWorkspace, refreshStructure,
getWorkspace, renameTabs,
refreshStructure, changeBreadcrumbs,
renameTabs, setUnsavedChanges
newTab, } = workspacesStore;
changeBreadcrumbs,
setUnsavedChanges
};
},
data () {
return {
isLoading: false,
isSaving: false,
isTimingModal: false,
originalScheduler: null,
localScheduler: { sql: '' },
lastScheduler: null,
sqlProxy: '',
editorHeight: 300
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
isChanged () {
return JSON.stringify(this.originalScheduler) !== JSON.stringify(this.localScheduler);
},
isDefinerInUsers () {
return this.originalScheduler ? this.workspace.users.some(user => this.originalScheduler.definer === `\`${user.name}\`@\`${user.host}\``) : true;
},
schemaTables () {
const schemaTables = this.workspace.structure
.filter(schema => schema.name === this.schema)
.map(schema => schema.tables);
return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : []; const queryEditor: Ref<Component & {editor: Ace.Editor; $el: HTMLElement}> = ref(null);
}, const isLoading = ref(false);
users () { const isSaving = ref(false);
const users = [{ value: '' }, ...this.workspace.users]; const isTimingModal = ref(false);
if (!this.isDefinerInUsers) { const originalScheduler: Ref<EventInfos> = ref(null);
const [name, host] = this.originalScheduler.definer.replaceAll('`', '').split('@'); const localScheduler: Ref<EventInfos> = ref({} as EventInfos);
users.unshift({ name, host }); const lastScheduler = ref(null);
} const sqlProxy = ref('');
const editorHeight = ref(300);
return users; const workspace = computed(() => {
return getWorkspace(props.connection.uid);
});
const isChanged = computed(() => {
return JSON.stringify(originalScheduler.value) !== JSON.stringify(localScheduler.value);
});
const isDefinerInUsers = computed(() => {
return originalScheduler.value ? workspace.value.users.some(user => originalScheduler.value.definer === `\`${user.name}\`@\`${user.host}\``) : true;
});
const users = computed(() => {
const users = [{ value: '' }, ...workspace.value.users];
if (!isDefinerInUsers.value) {
const [name, host] = originalScheduler.value.definer.replaceAll('`', '').split('@');
users.unshift({ name, host });
}
return users;
});
const getSchedulerData = async () => {
if (!props.scheduler) return;
isLoading.value = true;
lastScheduler.value = props.scheduler;
const params = {
uid: props.connection.uid,
schema: props.schema,
scheduler: props.scheduler
};
try {
const { status, response } = await Schedulers.getSchedulerInformations(params);
if (status === 'success') {
originalScheduler.value = response;
localScheduler.value = JSON.parse(JSON.stringify(originalScheduler.value));
sqlProxy.value = localScheduler.value.sql;
} }
}, else
watch: { addNotification({ status: 'error', message: response });
async schema () { }
if (this.isSelected) { catch (err) {
await this.getSchedulerData(); addNotification({ status: 'error', message: err.stack });
this.$refs.queryEditor.editor.session.setValue(this.localScheduler.sql); }
this.lastScheduler = this.scheduler;
}
},
async scheduler () {
if (this.isSelected) {
await this.getSchedulerData();
this.$refs.queryEditor.editor.session.setValue(this.localScheduler.sql);
this.lastScheduler = this.scheduler;
}
},
async isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, scheduler: this.scheduler });
setTimeout(() => { resizeQueryEditor();
this.resizeQueryEditor(); isLoading.value = false;
}, 200); };
if (this.lastScheduler !== this.scheduler) const saveChanges = async () => {
this.getSchedulerData(); if (isSaving.value) return;
isSaving.value = true;
const params = {
uid: props.connection.uid,
scheduler: {
...localScheduler.value,
schema: props.schema,
oldName: originalScheduler.value.name
} as AlterEventParams
};
try {
const { status, response } = await Schedulers.alterScheduler(params);
if (status === 'success') {
const oldName = originalScheduler.value.name;
await refreshStructure(props.connection.uid);
if (oldName !== localScheduler.value.name) {
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: oldName,
elementNewName: localScheduler.value.name,
elementType: 'scheduler'
});
changeBreadcrumbs({ schema: props.schema, scheduler: localScheduler.value.name });
} }
}, else
isChanged (val) { getSchedulerData();
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
} }
}, else
async created () { addNotification({ status: 'error', message: response });
await this.getSchedulerData(); }
this.$refs.queryEditor.editor.session.setValue(this.localScheduler.sql); catch (err) {
window.addEventListener('keydown', this.onKey); addNotification({ status: 'error', message: err.stack });
}, }
mounted () {
window.addEventListener('resize', this.resizeQueryEditor);
},
unmounted () {
window.removeEventListener('resize', this.resizeQueryEditor);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getSchedulerData () {
if (!this.scheduler) return;
this.isLoading = true; isSaving.value = false;
this.lastScheduler = this.scheduler; };
const params = { const clearChanges = () => {
uid: this.connection.uid, localScheduler.value = JSON.parse(JSON.stringify(originalScheduler.value));
schema: this.schema, queryEditor.value.editor.session.setValue(localScheduler.value.sql);
scheduler: this.scheduler };
};
try { const resizeQueryEditor = () => {
const { status, response } = await Schedulers.getSchedulerInformations(params); if (queryEditor.value) {
if (status === 'success') { const footer = document.getElementById('footer');
this.originalScheduler = response; const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
this.localScheduler = JSON.parse(JSON.stringify(this.originalScheduler)); editorHeight.value = size;
this.sqlProxy = this.localScheduler.sql; queryEditor.value.editor.resize();
} }
else };
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor(); const showTimingModal = () => {
this.isLoading = false; isTimingModal.value = true;
}, };
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
const params = {
uid: this.connection.uid,
scheduler: {
...this.localScheduler,
schema: this.schema,
oldName: this.originalScheduler.name
}
};
try { const hideTimingModal = () => {
const { status, response } = await Schedulers.alterScheduler(params); isTimingModal.value = false;
};
if (status === 'success') { const timingUpdate = (options: EventInfos) => {
const oldName = this.originalScheduler.name; localScheduler.value = options;
};
await this.refreshStructure(this.connection.uid); const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
if (oldName !== this.localScheduler.name) { e.stopPropagation();
this.renameTabs({ if (e.ctrlKey && e.key === 's') { // CTRL + S
uid: this.connection.uid, if (isChanged.value)
schema: this.schema, saveChanges();
elementName: oldName,
elementNewName: this.localScheduler.name,
elementType: 'scheduler'
});
this.changeBreadcrumbs({ schema: this.schema, scheduler: this.localScheduler.name });
}
else
this.getSchedulerData();
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false;
},
clearChanges () {
this.localScheduler = JSON.parse(JSON.stringify(this.originalScheduler));
this.$refs.queryEditor.editor.session.setValue(this.localScheduler.sql);
},
resizeQueryEditor () {
if (this.$refs.queryEditor) {
const footer = document.getElementById('footer');
const size = window.innerHeight - this.$refs.queryEditor.$el.getBoundingClientRect().top - footer.offsetHeight;
this.editorHeight = size;
this.$refs.queryEditor.editor.resize();
}
},
showTimingModal () {
this.isTimingModal = true;
},
hideTimingModal () {
this.isTimingModal = false;
},
timingUpdate (options) {
this.localScheduler = options;
},
onKey (e) {
if (this.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (this.isChanged)
this.saveChanges();
}
}
} }
} }
}; };
watch(() => props.schema, async () => {
if (props.isSelected) {
await getSchedulerData();
queryEditor.value.editor.session.setValue(localScheduler.value.sql);
lastScheduler.value = props.scheduler;
}
});
watch(() => props.scheduler, async () => {
if (props.isSelected) {
await getSchedulerData();
queryEditor.value.editor.session.setValue(localScheduler.value.sql);
lastScheduler.value = props.scheduler;
}
});
watch(() => props.isSelected, async (val) => {
if (val) {
changeBreadcrumbs({ schema: props.schema, scheduler: props.scheduler });
setTimeout(() => {
resizeQueryEditor();
}, 200);
if (lastScheduler.value !== props.scheduler)
getSchedulerData();
}
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
(async () => {
await getSchedulerData();
queryEditor.value.editor.session.setValue(localScheduler.value.sql);
window.addEventListener('keydown', onKey);
})();
onMounted(() => {
window.addEventListener('resize', resizeQueryEditor);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeQueryEditor);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script> </script>

View File

@ -1,6 +1,6 @@
<template> <template>
<ConfirmModal <ConfirmModal
:confirm-text="$t('word.confirm')" :confirm-text="t('word.confirm')"
size="400" size="400"
@confirm="confirmOptionsChange" @confirm="confirmOptionsChange"
@hide="$emit('hide')" @hide="$emit('hide')"
@ -8,14 +8,14 @@
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-timer mr-1" /> <i class="mdi mdi-24px mdi-timer mr-1" />
<span class="cut-text">{{ $t('word.timing') }} "{{ localOptions.name }}"</span> <span class="cut-text">{{ t('word.timing') }} "{{ localOptions.name }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
<form class="form-horizontal"> <form class="form-horizontal">
<div class="form-group"> <div class="form-group">
<label class="form-label col-4"> <label class="form-label col-4">
{{ $t('word.execution') }} {{ t('word.execution') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
@ -61,7 +61,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-4"> <label class="form-label col-4">
{{ $t('word.starts') }} {{ t('word.starts') }}
</label> </label>
<div class="column"> <div class="column">
<div class="input-group"> <div class="input-group">
@ -82,7 +82,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-4"> <label class="form-label col-4">
{{ $t('word.ends') }} {{ t('word.ends') }}
</label> </label>
<div class="column"> <div class="column">
<div class="input-group"> <div class="input-group">
@ -124,7 +124,7 @@
<div class="col-4" /> <div class="col-4" />
<div class="column"> <div class="column">
<label class="form-checkbox form-inline mt-2"> <label class="form-checkbox form-inline mt-2">
<input v-model="optionsProxy.preserve" type="checkbox"><i class="form-icon" /> {{ $t('message.preserveOnCompletion') }} <input v-model="optionsProxy.preserve" type="checkbox"><i class="form-icon" /> {{ t('message.preserveOnCompletion') }}
</label> </label>
</div> </div>
</div> </div>
@ -133,52 +133,47 @@
</ConfirmModal> </ConfirmModal>
</template> </template>
<script> <script setup lang="ts">
import moment from 'moment'; import { Ref, ref } from 'vue';
import ConfirmModal from '@/components/BaseConfirmModal'; import * as moment from 'moment';
import { useI18n } from 'vue-i18n';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { EventInfos } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsSchedulerTimingModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
localOptions: Object,
workspace: Object
},
emits: ['hide', 'options-update'],
data () {
return {
optionsProxy: {},
isOptionsChanging: false,
hasStart: false,
hasEnd: false
};
},
created () {
this.optionsProxy = JSON.parse(JSON.stringify(this.localOptions));
this.hasStart = !!this.optionsProxy.starts; const props = defineProps({
this.hasEnd = !!this.optionsProxy.ends; localOptions: Object,
workspace: Object
});
if (!this.optionsProxy.at) this.optionsProxy.at = moment().format('YYYY-MM-DD HH:mm:ss'); const emit = defineEmits(['hide', 'options-update']);
if (!this.optionsProxy.starts) this.optionsProxy.starts = moment().format('YYYY-MM-DD HH:mm:ss');
if (!this.optionsProxy.ends) this.optionsProxy.ends = moment().format('YYYY-MM-DD HH:mm:ss');
if (!this.optionsProxy.every.length) this.optionsProxy.every = ['1', 'DAY'];
},
methods: {
confirmOptionsChange () {
if (!this.hasStart) this.optionsProxy.starts = '';
if (!this.hasEnd) this.optionsProxy.ends = '';
this.$emit('options-update', this.optionsProxy); const optionsProxy: Ref<EventInfos> = ref({} as EventInfos);
}, const hasStart = ref(false);
isNumberOrMinus (event) { const hasEnd = ref(false);
if (!/\d/.test(event.key) && event.key !== '-')
return event.preventDefault(); const confirmOptionsChange = () => {
} if (!hasStart.value) optionsProxy.value.starts = '';
} if (!hasEnd.value) optionsProxy.value.ends = '';
emit('options-update', optionsProxy.value);
}; };
const isNumberOrMinus = (event: KeyboardEvent) => {
if (!/\d/.test(event.key) && event.key !== '-')
return event.preventDefault();
};
optionsProxy.value = JSON.parse(JSON.stringify(props.localOptions));
hasStart.value = !!optionsProxy.value.starts;
hasEnd.value = !!optionsProxy.value.ends;
if (!optionsProxy.value.at) optionsProxy.value.at = moment().format('YYYY-MM-DD HH:mm:ss');
if (!optionsProxy.value.starts) optionsProxy.value.starts = moment().format('YYYY-MM-DD HH:mm:ss');
if (!optionsProxy.value.ends) optionsProxy.value.ends = moment().format('YYYY-MM-DD HH:mm:ss');
if (!optionsProxy.value.every.length) optionsProxy.value.every = ['1', 'DAY'];
</script> </script>

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@
@close-context="closeContext" @close-context="closeContext"
> >
<div class="context-element"> <div class="context-element">
<span class="d-flex"><i class="mdi mdi-18px mdi-key-plus text-light pr-1" /> {{ $t('message.createNewIndex') }}</span> <span class="d-flex"><i class="mdi mdi-18px mdi-key-plus text-light pr-1" /> {{ t('message.createNewIndex') }}</span>
<i class="mdi mdi-18px mdi-chevron-right text-light pl-1" /> <i class="mdi mdi-18px mdi-chevron-right text-light pl-1" />
<div class="context-submenu"> <div class="context-submenu">
<div <div
@ -19,7 +19,7 @@
</div> </div>
</div> </div>
<div v-if="indexes.length" class="context-element"> <div v-if="indexes.length" class="context-element">
<span class="d-flex"><i class="mdi mdi-18px mdi-key-arrow-right text-light pr-1" /> {{ $t('message.addToIndex') }}</span> <span class="d-flex"><i class="mdi mdi-18px mdi-key-arrow-right text-light pr-1" /> {{ t('message.addToIndex') }}</span>
<i class="mdi mdi-18px mdi-chevron-right text-light pl-1" /> <i class="mdi mdi-18px mdi-chevron-right text-light pl-1" />
<div class="context-submenu"> <div class="context-submenu">
<div <div
@ -34,54 +34,54 @@
</div> </div>
</div> </div>
<div class="context-element" @click="duplicateField"> <div class="context-element" @click="duplicateField">
<span class="d-flex"><i class="mdi mdi-18px mdi-content-duplicate text-light pr-1" /> {{ $t('word.duplicate') }}</span> <span class="d-flex"><i class="mdi mdi-18px mdi-content-duplicate text-light pr-1" /> {{ t('word.duplicate') }}</span>
</div> </div>
<div class="context-element" @click="deleteField"> <div class="context-element" @click="deleteField">
<span class="d-flex"><i class="mdi mdi-18px mdi-delete text-light pr-1" /> {{ $t('message.deleteField') }}</span> <span class="d-flex"><i class="mdi mdi-18px mdi-delete text-light pr-1" /> {{ t('message.deleteField') }}</span>
</div> </div>
</BaseContextMenu> </BaseContextMenu>
</template> </template>
<script> <script setup lang="ts">
import BaseContextMenu from '@/components/BaseContextMenu'; import { computed, Prop } from 'vue';
import { useI18n } from 'vue-i18n';
import BaseContextMenu from '@/components/BaseContextMenu.vue';
import { TableIndex } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabQueryTableContext',
components: { const props = defineProps({
BaseContextMenu contextEvent: MouseEvent,
}, indexes: Array as Prop<TableIndex[]>,
props: { indexTypes: Array as Prop<string[]>,
contextEvent: MouseEvent, selectedField: Object
indexes: Array, });
indexTypes: Array,
selectedField: Object const emit = defineEmits(['close-context', 'duplicate-selected', 'delete-selected', 'add-new-index', 'add-to-index']);
},
emits: ['close-context', 'duplicate-selected', 'delete-selected', 'add-new-index', 'add-to-index'], const hasPrimary = computed(() => props.indexes.some(index => index.type === 'PRIMARY'));
computed: {
hasPrimary () { const closeContext = () => {
return this.indexes.some(index => index.type === 'PRIMARY'); emit('close-context');
} };
},
methods: { const duplicateField = () => {
closeContext () { emit('duplicate-selected');
this.$emit('close-context'); closeContext();
}, };
duplicateField () {
this.$emit('duplicate-selected'); const deleteField = () => {
this.closeContext(); emit('delete-selected');
}, closeContext();
deleteField () { };
this.$emit('delete-selected');
this.closeContext(); const addNewIndex = (index: string) => {
}, emit('add-new-index', { field: props.selectedField.name, index });
addNewIndex (index) { closeContext();
this.$emit('add-new-index', { field: this.selectedField.name, index }); };
this.closeContext();
}, const addToIndex = (index: string) => {
addToIndex (index) { emit('add-to-index', { field: props.selectedField.name, index });
this.$emit('add-to-index', { field: this.selectedField.name, index }); closeContext();
this.closeContext();
}
}
}; };
</script> </script>

View File

@ -13,89 +13,89 @@
@delete-selected="removeField" @delete-selected="removeField"
@duplicate-selected="duplicateField" @duplicate-selected="duplicateField"
@close-context="isContext = false" @close-context="isContext = false"
@add-new-index="$emit('add-new-index', $event)" @add-new-index="emit('add-new-index', $event)"
@add-to-index="$emit('add-to-index', $event)" @add-to-index="emit('add-to-index', $event)"
/> />
<div ref="propTable" class="table table-hover"> <div ref="propTable" class="table table-hover">
<div class="thead"> <div class="thead">
<div class="tr"> <div class="tr">
<div class="th"> <div class="th">
<div class="text-right"> <div class="text-right">
{{ $t('word.order') }} {{ t('word.order') }}
</div> </div>
</div> </div>
<div class="th"> <div class="th">
<div class="table-column-title"> <div class="table-column-title">
{{ $tc('word.key', 2) }} {{ t('word.key', 2) }}
</div> </div>
</div> </div>
<div class="th"> <div class="th">
<div class="column-resizable min-100"> <div class="column-resizable min-100">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.name') }} {{ t('word.name') }}
</div> </div>
</div> </div>
</div> </div>
<div class="th"> <div class="th">
<div class="column-resizable min-100"> <div class="column-resizable min-100">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.type') }} {{ t('word.type') }}
</div> </div>
</div> </div>
</div> </div>
<div v-if="customizations.tableArray" class="th"> <div v-if="customizations.tableArray" class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.array') }} {{ t('word.array') }}
</div> </div>
</div> </div>
</div> </div>
<div class="th"> <div class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.length') }} {{ t('word.length') }}
</div> </div>
</div> </div>
</div> </div>
<div v-if="customizations.unsigned" class="th"> <div v-if="customizations.unsigned" class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.unsigned') }} {{ t('word.unsigned') }}
</div> </div>
</div> </div>
</div> </div>
<div v-if="customizations.nullable" class="th"> <div v-if="customizations.nullable" class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('message.allowNull') }} {{ t('message.allowNull') }}
</div> </div>
</div> </div>
</div> </div>
<div v-if="customizations.zerofill" class="th"> <div v-if="customizations.zerofill" class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('message.zeroFill') }} {{ t('message.zeroFill') }}
</div> </div>
</div> </div>
</div> </div>
<div class="th"> <div class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.default') }} {{ t('word.default') }}
</div> </div>
</div> </div>
</div> </div>
<div v-if="customizations.comment" class="th"> <div v-if="customizations.comment" class="th">
<div class="column-resizable"> <div class="column-resizable">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.comment') }} {{ t('word.comment') }}
</div> </div>
</div> </div>
</div> </div>
<div v-if="customizations.collation" class="th"> <div v-if="customizations.collation" class="th">
<div class="column-resizable min-100"> <div class="column-resizable min-100">
<div class="table-column-title"> <div class="table-column-title">
{{ $t('word.collation') }} {{ t('word.collation') }}
</div> </div>
</div> </div>
</div> </div>
@ -116,7 +116,7 @@
:data-types="dataTypes" :data-types="dataTypes"
:customizations="customizations" :customizations="customizations"
@contextmenu="contextMenu" @contextmenu="contextMenu"
@rename-field="$emit('rename-field', $event)" @rename-field="emit('rename-field', $event)"
/> />
</template> </template>
</Draggable> </Draggable>
@ -124,135 +124,115 @@
</div> </div>
</template> </template>
<script>// TODO: expose tableWrapper <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onMounted, onUnmounted, onUpdated, Prop, ref, Ref, watch } from 'vue';
import { useNotificationsStore } from '@/stores/notifications'; import { useI18n } from 'vue-i18n';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import Draggable from 'vuedraggable'; import * as Draggable from 'vuedraggable';
import TableRow from '@/components/WorkspaceTabPropsTableRow'; import TableRow from '@/components/WorkspaceTabPropsTableRow.vue';
import TableContext from '@/components/WorkspaceTabPropsTableContext'; import TableContext from '@/components/WorkspaceTabPropsTableContext.vue';
import { TableField, TableForeign, TableIndex } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsTableFields',
components: {
TableRow,
TableContext,
Draggable
},
props: {
fields: Array,
indexes: Array,
foreigns: Array,
indexTypes: Array,
tabUid: [String, Number],
connUid: String,
table: String,
schema: String,
mode: String
},
emits: ['add-new-index', 'add-to-index', 'rename-field', 'duplicate-field', 'remove-field'],
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
fields: Array as Prop<TableField[]>,
indexes: Array as Prop<TableIndex[]>,
foreigns: Array as Prop<TableForeign[]>,
indexTypes: Array as Prop<string[]>,
tabUid: [String, Number],
connUid: String,
table: String,
schema: String,
mode: String
});
const { getWorkspace } = workspacesStore; const emit = defineEmits(['add-new-index', 'add-to-index', 'rename-field', 'duplicate-field', 'remove-field']);
return { const workspacesStore = useWorkspacesStore();
addNotification,
selectedWorkspace,
getWorkspace
};
},
data () {
return {
resultsSize: 1000,
isContext: false,
contextEvent: null,
selectedField: null,
scrollElement: null
};
},
computed: {
workspaceSchema () {
return this.getWorkspace(this.connUid).breadcrumbs.schema;
},
customizations () {
return this.getWorkspace(this.connUid).customizations;
},
dataTypes () {
return this.getWorkspace(this.connUid).dataTypes;
},
primaryField () {
return this.fields.filter(field => ['pri', 'uni'].includes(field.key))[0] || false;
},
tabProperties () {
return this.getWorkspaceTab(this.tabUid);
},
fieldsLength () {
return this.fields.length;
}
},
watch: {
fieldsLength () {
this.refreshScroller();
}
},
updated () {
if (this.$refs.propTable)
this.refreshScroller();
if (this.$refs.tableWrapper) const { getWorkspace } = workspacesStore;
this.scrollElement = this.$refs.tableWrapper;
},
mounted () {
window.addEventListener('resize', this.resizeResults);
},
unmounted () {
window.removeEventListener('resize', this.resizeResults);
},
methods: {
resizeResults () {
if (this.$refs.resultTable) {
const el = this.$refs.tableWrapper;
if (el) { const tableWrapper: Ref<HTMLDivElement> = ref(null);
const footer = document.getElementById('footer'); const propTable: Ref<HTMLDivElement> = ref(null);
const size = window.innerHeight - el.getBoundingClientRect().top - footer.offsetHeight; const resultTable: Ref<Component> = ref(null);
this.resultsSize = size; const resultsSize = ref(1000);
} const isContext = ref(false);
} const contextEvent = ref(null);
}, const selectedField = ref(null);
refreshScroller () { const scrollElement = ref(null);
this.resizeResults();
}, const customizations = computed(() => getWorkspace(props.connUid).customizations);
contextMenu (event, uid) { // eslint-disable-next-line @typescript-eslint/no-explicit-any
this.selectedField = this.fields.find(field => field._antares_id === uid); const dataTypes = computed(() => getWorkspace(props.connUid).dataTypes) as any;
this.contextEvent = event; const fieldsLength = computed(() => props.fields.length);
this.isContext = true;
}, const resizeResults = () => {
duplicateField () { if (resultTable.value) {
this.$emit('duplicate-field', this.selectedField._antares_id); const el = tableWrapper.value;
},
removeField () { if (el) {
this.$emit('remove-field', this.selectedField._antares_id); const footer = document.getElementById('footer');
}, const size = window.innerHeight - el.getBoundingClientRect().top - footer.offsetHeight;
getIndexes (field) { resultsSize.value = size;
return this.indexes.reduce((acc, curr) => {
acc.push(...curr.fields.map(f => ({ name: f, type: curr.type })));
return acc;
}, []).filter(f => f.name === field);
},
getForeigns (field) {
return this.foreigns.reduce((acc, curr) => {
if (curr.field === field)
acc.push(`${curr.refTable}.${curr.refField}`);
return acc;
}, []);
} }
} }
}; };
const refreshScroller = () => {
resizeResults();
};
const contextMenu = (event: MouseEvent, uid: string) => {
selectedField.value = props.fields.find(field => field._antares_id === uid);
contextEvent.value = event;
isContext.value = true;
};
const duplicateField = () => {
emit('duplicate-field', selectedField.value._antares_id);
};
const removeField = () => {
emit('remove-field', selectedField.value._antares_id);
};
const getIndexes = (field: string) => {
return props.indexes.reduce((acc, curr) => {
acc.push(...curr.fields.map(f => ({ name: f, type: curr.type })));
return acc;
}, []).filter(f => f.name === field);
};
const getForeigns = (field: string) => {
return props.foreigns.reduce((acc, curr) => {
if (curr.field === field)
acc.push(`${curr.refTable}.${curr.refField}`);
return acc;
}, []);
};
watch(fieldsLength, () => {
refreshScroller();
});
onUpdated(() => {
if (propTable.value)
refreshScroller();
if (tableWrapper.value)
scrollElement.value = tableWrapper.value;
});
onMounted(() => {
window.addEventListener('resize', resizeResults);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeResults);
});
defineExpose({ tableWrapper });
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -1,6 +1,6 @@
<template> <template>
<ConfirmModal <ConfirmModal
:confirm-text="$t('word.confirm')" :confirm-text="t('word.confirm')"
size="medium" size="medium"
class="options-modal" class="options-modal"
@confirm="confirmForeignsChange" @confirm="confirmForeignsChange"
@ -9,7 +9,7 @@
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-key-link mr-1" /> <i class="mdi mdi-24px mdi-key-link mr-1" />
<span class="cut-text">{{ $t('word.foreignKeys') }} "{{ table }}"</span> <span class="cut-text">{{ t('word.foreignKeys') }} "{{ table }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -20,16 +20,16 @@
<div class="d-flex"> <div class="d-flex">
<button class="btn btn-dark btn-sm d-flex" @click="addForeign"> <button class="btn btn-dark btn-sm d-flex" @click="addForeign">
<i class="mdi mdi-24px mdi-link-plus mr-1" /> <i class="mdi mdi-24px mdi-link-plus mr-1" />
<span>{{ $t('word.add') }}</span> <span>{{ t('word.add') }}</span>
</button> </button>
<button <button
class="btn btn-dark btn-sm d-flex ml-2 mr-0" class="btn btn-dark btn-sm d-flex ml-2 mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
:disabled="!isChanged" :disabled="!isChanged"
@click.prevent="clearChanges" @click.prevent="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
</div> </div>
@ -67,7 +67,7 @@
<div class="tile-action"> <div class="tile-action">
<button <button
class="btn btn-link remove-field p-0 mr-2" class="btn btn-link remove-field p-0 mr-2"
:title="$t('word.delete')" :title="t('word.delete')"
@click.prevent="removeIndex(foreign._antares_id)" @click.prevent="removeIndex(foreign._antares_id)"
> >
<i class="mdi mdi-close" /> <i class="mdi mdi-close" />
@ -86,7 +86,7 @@
> >
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -98,7 +98,7 @@
</div> </div>
<div class="form-group mb-4"> <div class="form-group mb-4">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $tc('word.field', 1) }} {{ t('word.field', 1) }}
</label> </label>
<div class="fields-list column pt-1"> <div class="fields-list column pt-1">
<label <label
@ -114,7 +114,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3 pt-0"> <label class="form-label col-3 pt-0">
{{ $t('message.referenceTable') }} {{ t('message.referenceTable') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
@ -129,7 +129,7 @@
</div> </div>
<div class="form-group mb-4"> <div class="form-group mb-4">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('message.referenceField') }} {{ t('message.referenceField') }}
</label> </label>
<div class="fields-list column pt-1"> <div class="fields-list column pt-1">
<label <label
@ -145,7 +145,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('message.onUpdate') }} {{ t('message.onUpdate') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
@ -157,7 +157,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('message.onDelete') }} {{ t('message.onDelete') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
@ -174,11 +174,11 @@
<i class="mdi mdi-key-link mdi-48px" /> <i class="mdi mdi-key-link mdi-48px" />
</div> </div>
<p class="empty-title h5"> <p class="empty-title h5">
{{ $t('message.thereAreNoForeign') }} {{ t('message.thereAreNoForeign') }}
</p> </p>
<div class="empty-action"> <div class="empty-action">
<button class="btn btn-primary" @click="addForeign"> <button class="btn btn-primary" @click="addForeign">
{{ $t('message.createNewForeign') }} {{ t('message.createNewForeign') }}
</button> </button>
</div> </div>
</div> </div>
@ -188,176 +188,173 @@
</ConfirmModal> </ConfirmModal>
</template> </template>
<script> <script setup lang="ts">
import { computed, onMounted, onUnmounted, Prop, Ref, ref } from 'vue';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useI18n } from 'vue-i18n';
import { uidGen } from 'common/libs/uidGen'; import { uidGen } from 'common/libs/uidGen';
import Tables from '@/ipc-api/Tables'; import Tables from '@/ipc-api/Tables';
import ConfirmModal from '@/components/BaseConfirmModal'; import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { TableField } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsTableForeignModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
localKeyUsage: Array,
connection: Object,
table: String,
schema: String,
schemaTables: Array,
fields: Array,
workspace: Object
},
emits: ['foreigns-update', 'hide'],
setup () {
const { addNotification } = useNotificationsStore();
return { addNotification }; const props = defineProps({
}, localKeyUsage: Array,
data () { connection: Object,
return { table: String,
foreignProxy: [], schema: String,
isOptionsChanging: false, schemaTables: Array,
selectedForeignID: '', fields: Array as Prop<TableField[]>,
modalInnerHeight: 400, workspace: Object
refFields: {}, });
foreignActions: [
'RESTRICT',
'CASCADE',
'SET NULL',
'NO ACTION'
]
};
},
computed: {
selectedForeignObj () {
return this.foreignProxy.find(foreign => foreign._antares_id === this.selectedForeignID);
},
isChanged () {
return JSON.stringify(this.localKeyUsage) !== JSON.stringify(this.foreignProxy);
},
hasPrimary () {
return this.foreignProxy.some(foreign => foreign.type === 'PRIMARY');
}
},
mounted () {
this.foreignProxy = JSON.parse(JSON.stringify(this.localKeyUsage));
if (this.foreignProxy.length) const emit = defineEmits(['foreigns-update', 'hide']);
this.resetSelectedID();
if (this.selectedForeignObj) const { addNotification } = useNotificationsStore();
this.getRefFields();
this.getModalInnerHeight(); const indexesPanel: Ref<HTMLDivElement> = ref(null);
window.addEventListener('resize', this.getModalInnerHeight); const foreignProxy = ref([]);
}, const selectedForeignID = ref('');
unmounted () { const modalInnerHeight = ref(400);
window.removeEventListener('resize', this.getModalInnerHeight); const refFields = ref({} as {[key: string]: TableField[]});
}, const foreignActions = [
methods: { 'RESTRICT',
confirmForeignsChange () { 'CASCADE',
this.foreignProxy = this.foreignProxy.filter(foreign => 'SET NULL',
foreign.field && 'NO ACTION'
foreign.refField && ];
foreign.table &&
foreign.refTable
);
this.$emit('foreigns-update', this.foreignProxy);
},
selectForeign (event, id) {
if (this.selectedForeignID !== id && !event.target.classList.contains('remove-field')) {
this.selectedForeignID = id;
this.getRefFields();
}
},
getModalInnerHeight () {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
this.modalInnerHeight = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
},
addForeign () {
this.foreignProxy = [...this.foreignProxy, {
_antares_id: uidGen(),
constraintName: `FK_${uidGen()}`,
refSchema: this.schema,
table: this.table,
refTable: '',
field: '',
refField: '',
onUpdate: this.foreignActions[0],
onDelete: this.foreignActions[0]
}];
if (this.foreignProxy.length === 1) const selectedForeignObj = computed(() => foreignProxy.value.find(foreign => foreign._antares_id === selectedForeignID.value));
this.resetSelectedID(); const isChanged = computed(() => JSON.stringify(props.localKeyUsage) !== JSON.stringify(foreignProxy.value));
setTimeout(() => { const confirmForeignsChange = () => {
this.$refs.indexesPanel.scrollTop = this.$refs.indexesPanel.scrollHeight + 60; foreignProxy.value = foreignProxy.value.filter(foreign =>
}, 20); foreign.field &&
}, foreign.refField &&
removeIndex (id) { foreign.table &&
this.foreignProxy = this.foreignProxy.filter(foreign => foreign._antares_id !== id); foreign.refTable
);
emit('foreigns-update', foreignProxy.value);
};
if (this.selectedForeignID === id && this.foreignProxy.length) const selectForeign = (event: MouseEvent, id: string) => {
this.resetSelectedID(); // eslint-disable-next-line @typescript-eslint/no-explicit-any
}, if (selectedForeignID.value !== id && !(event.target as any).classList.contains('remove-field')) {
clearChanges () { selectedForeignID.value = id;
this.foreignProxy = JSON.parse(JSON.stringify(this.localKeyUsage)); getRefFields();
if (!this.foreignProxy.some(foreign => foreign._antares_id === this.selectedForeignID))
this.resetSelectedID();
},
toggleField (field) {
this.foreignProxy = this.foreignProxy.map(foreign => {
if (foreign._antares_id === this.selectedForeignID)
foreign.field = field;
return foreign;
});
},
toggleRefField (field) {
this.foreignProxy = this.foreignProxy.map(foreign => {
if (foreign._antares_id === this.selectedForeignID)
foreign.refField = field;
return foreign;
});
},
resetSelectedID () {
this.selectedForeignID = this.foreignProxy.length ? this.foreignProxy[0]._antares_id : '';
},
async getRefFields () {
if (!this.selectedForeignObj.refTable) return;
const params = {
uid: this.connection.uid,
schema: this.selectedForeignObj.refSchema,
table: this.selectedForeignObj.refTable
};
try { // Field data
const { status, response } = await Tables.getTableColumns(params);
if (status === 'success') {
this.refFields = {
...this.refFields,
[this.selectedForeignID]: response
};
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
},
reloadRefFields () {
this.selectedForeignObj.refField = '';
this.getRefFields();
}
} }
}; };
const getModalInnerHeight = () => {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
modalInnerHeight.value = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
};
const addForeign = () => {
foreignProxy.value = [...foreignProxy.value, {
_antares_id: uidGen(),
constraintName: `FK_${uidGen()}`,
refSchema: props.schema,
table: props.table,
refTable: '',
field: '',
refField: '',
onUpdate: foreignActions[0],
onDelete: foreignActions[0]
}];
if (foreignProxy.value.length === 1)
resetSelectedID();
setTimeout(() => {
indexesPanel.value.scrollTop = indexesPanel.value.scrollHeight + 60;
}, 20);
};
const removeIndex = (id: string) => {
foreignProxy.value = foreignProxy.value.filter(foreign => foreign._antares_id !== id);
if (selectedForeignID.value === id && foreignProxy.value.length)
resetSelectedID();
};
const clearChanges = () => {
foreignProxy.value = JSON.parse(JSON.stringify(props.localKeyUsage));
if (!foreignProxy.value.some(foreign => foreign._antares_id === selectedForeignID.value))
resetSelectedID();
};
const toggleField = (field: string) => {
foreignProxy.value = foreignProxy.value.map(foreign => {
if (foreign._antares_id === selectedForeignID.value)
foreign.field = field;
return foreign;
});
};
const toggleRefField = (field: string) => {
foreignProxy.value = foreignProxy.value.map(foreign => {
if (foreign._antares_id === selectedForeignID.value)
foreign.refField = field;
return foreign;
});
};
const resetSelectedID = () => {
selectedForeignID.value = foreignProxy.value.length ? foreignProxy.value[0]._antares_id : '';
};
const getRefFields = async () => {
if (!selectedForeignObj.value.refTable) return;
const params = {
uid: props.connection.uid,
schema: selectedForeignObj.value.refSchema,
table: selectedForeignObj.value.refTable
};
try { // Field data
const { status, response } = await Tables.getTableColumns(params);
if (status === 'success') {
refFields.value = {
...refFields.value,
[selectedForeignID.value]: response
};
}
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
};
const reloadRefFields = () => {
selectedForeignObj.value.refField = '';
getRefFields();
};
onMounted(() => {
foreignProxy.value = JSON.parse(JSON.stringify(props.localKeyUsage));
if (foreignProxy.value.length)
resetSelectedID();
if (selectedForeignObj.value)
getRefFields();
getModalInnerHeight();
window.addEventListener('resize', getModalInnerHeight);
});
onUnmounted(() => {
window.removeEventListener('resize', getModalInnerHeight);
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@ -384,7 +381,7 @@ export default {
} }
.fields-list { .fields-list {
max-height: 80px; max-height: 90px;
overflow: auto; overflow: auto;
} }

View File

@ -1,6 +1,6 @@
<template> <template>
<ConfirmModal <ConfirmModal
:confirm-text="$t('word.confirm')" :confirm-text="t('word.confirm')"
size="medium" size="medium"
class="options-modal" class="options-modal"
@confirm="confirmIndexesChange" @confirm="confirmIndexesChange"
@ -9,7 +9,7 @@
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-key mdi-rotate-45 mr-1" /> <i class="mdi mdi-24px mdi-key mdi-rotate-45 mr-1" />
<span class="cut-text">{{ $t('word.indexes') }} "{{ table }}"</span> <span class="cut-text">{{ t('word.indexes') }} "{{ table }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -20,16 +20,16 @@
<div class="d-flex"> <div class="d-flex">
<button class="btn btn-dark btn-sm d-flex" @click="addIndex"> <button class="btn btn-dark btn-sm d-flex" @click="addIndex">
<i class="mdi mdi-24px mdi-key-plus mr-1" /> <i class="mdi mdi-24px mdi-key-plus mr-1" />
<span>{{ $t('word.add') }}</span> <span>{{ t('word.add') }}</span>
</button> </button>
<button <button
class="btn btn-dark btn-sm d-flex ml-2 mr-0" class="btn btn-dark btn-sm d-flex ml-2 mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
:disabled="!isChanged" :disabled="!isChanged"
@click.prevent="clearChanges" @click.prevent="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
</div> </div>
@ -50,12 +50,12 @@
<div class="tile-title"> <div class="tile-title">
{{ index.name }} {{ index.name }}
</div> </div>
<small class="tile-subtitle text-gray">{{ index.type }} · {{ index.fields.length }} {{ $tc('word.field', index.fields.length) }}</small> <small class="tile-subtitle text-gray">{{ index.type }} · {{ index.fields.length }} {{ t('word.field', index.fields.length) }}</small>
</div> </div>
<div class="tile-action"> <div class="tile-action">
<button <button
class="btn btn-link remove-field p-0 mr-2" class="btn btn-link remove-field p-0 mr-2"
:title="$t('word.delete')" :title="t('word.delete')"
@click.prevent="removeIndex(index._antares_id)" @click.prevent="removeIndex(index._antares_id)"
> >
<i class="mdi mdi-close" /> <i class="mdi mdi-close" />
@ -74,7 +74,7 @@
> >
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.name') }} {{ t('word.name') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -86,20 +86,20 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $t('word.type') }} {{ t('word.type') }}
</label> </label>
<div class="column"> <div class="column">
<BaseSelect <BaseSelect
v-model="selectedIndexObj.type" v-model="selectedIndexObj.type"
:options="indexTypes" :options="indexTypes"
:option-disabled="(opt) => opt === 'PRIMARY'" :option-disabled="(opt: any) => opt === 'PRIMARY'"
class="form-select" class="form-select"
/> />
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="form-label col-3"> <label class="form-label col-3">
{{ $tc('word.field', fields.length) }} {{ t('word.field', fields.length) }}
</label> </label>
<div class="fields-list column pt-1"> <div class="fields-list column pt-1">
<label <label
@ -108,7 +108,7 @@
class="form-checkbox m-0" class="form-checkbox m-0"
@click.prevent="toggleField(field.name)" @click.prevent="toggleField(field.name)"
> >
<input type="checkbox" :checked="selectedIndexObj.fields.some(f => f === field.name)"> <input type="checkbox" :checked="selectedIndexObj.fields.some((f: string) => f === field.name)">
<i class="form-icon" /> {{ field.name }} <i class="form-icon" /> {{ field.name }}
</label> </label>
</div> </div>
@ -119,11 +119,11 @@
<i class="mdi mdi-key-outline mdi-48px" /> <i class="mdi mdi-key-outline mdi-48px" />
</div> </div>
<p class="empty-title h5"> <p class="empty-title h5">
{{ $t('message.thereAreNoIndexes') }} {{ t('message.thereAreNoIndexes') }}
</p> </p>
<div class="empty-action"> <div class="empty-action">
<button class="btn btn-primary" @click="addIndex"> <button class="btn btn-primary" @click="addIndex">
{{ $t('message.createNewIndex') }} {{ t('message.createNewIndex') }}
</button> </button>
</div> </div>
</div> </div>
@ -133,116 +133,113 @@
</ConfirmModal> </ConfirmModal>
</template> </template>
<script> <script setup lang="ts">
import { computed, onMounted, onUnmounted, Prop, Ref, ref } from 'vue';
import { TableField } from 'common/interfaces/antares';
import { uidGen } from 'common/libs/uidGen'; import { uidGen } from 'common/libs/uidGen';
import ConfirmModal from '@/components/BaseConfirmModal'; import { useI18n } from 'vue-i18n';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsTableIndexesModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
localIndexes: Array,
table: String,
fields: Array,
workspace: Object,
indexTypes: Array
},
emits: ['hide', 'indexes-update'],
data () {
return {
indexesProxy: [],
isOptionsChanging: false,
selectedIndexID: '',
modalInnerHeight: 400
};
},
computed: {
selectedIndexObj () {
return this.indexesProxy.find(index => index._antares_id === this.selectedIndexID);
},
isChanged () {
return JSON.stringify(this.localIndexes) !== JSON.stringify(this.indexesProxy);
},
hasPrimary () {
return this.indexesProxy.some(index => index.type === 'PRIMARY');
}
},
mounted () {
this.indexesProxy = JSON.parse(JSON.stringify(this.localIndexes));
if (this.indexesProxy.length) const props = defineProps({
this.resetSelectedID(); localIndexes: Array,
table: String,
fields: Array as Prop<TableField[]>,
workspace: Object,
indexTypes: Array
});
this.getModalInnerHeight(); const emit = defineEmits(['hide', 'indexes-update']);
window.addEventListener('resize', this.getModalInnerHeight);
},
unmounted () {
window.removeEventListener('resize', this.getModalInnerHeight);
},
methods: {
confirmIndexesChange () {
this.indexesProxy = this.indexesProxy.filter(index => index.fields.length);
this.$emit('indexes-update', this.indexesProxy);
},
selectIndex (event, id) {
if (this.selectedIndexID !== id && !event.target.classList.contains('remove-field'))
this.selectedIndexID = id;
},
getModalInnerHeight () {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
this.modalInnerHeight = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
},
addIndex () {
this.indexesProxy = [...this.indexesProxy, {
_antares_id: uidGen(),
name: 'NEW_INDEX',
fields: [],
type: 'INDEX',
comment: '',
indexType: 'BTREE',
indexComment: '',
cardinality: 0
}];
if (this.indexesProxy.length === 1) const indexesPanel: Ref<HTMLDivElement> = ref(null);
this.resetSelectedID(); const indexesProxy = ref([]);
const selectedIndexID = ref('');
const modalInnerHeight = ref(400);
setTimeout(() => { const selectedIndexObj = computed(() => indexesProxy.value.find(index => index._antares_id === selectedIndexID.value));
this.$refs.indexesPanel.scrollTop = this.$refs.indexesPanel.scrollHeight + 60; const isChanged = computed(() => JSON.stringify(props.localIndexes) !== JSON.stringify(indexesProxy.value));
}, 20);
},
removeIndex (id) {
this.indexesProxy = this.indexesProxy.filter(index => index._antares_id !== id);
if (this.selectedIndexID === id && this.indexesProxy.length) const confirmIndexesChange = () => {
this.resetSelectedID(); indexesProxy.value = indexesProxy.value.filter(index => index.fields.length);
}, emit('indexes-update', indexesProxy.value);
clearChanges () {
this.indexesProxy = JSON.parse(JSON.stringify(this.localIndexes));
if (!this.indexesProxy.some(index => index._antares_id === this.selectedIndexID))
this.resetSelectedID();
},
toggleField (field) {
this.indexesProxy = this.indexesProxy.map(index => {
if (index._antares_id === this.selectedIndexID) {
if (index.fields.includes(field))
index.fields = index.fields.filter(f => f !== field);
else
index.fields.push(field);
}
return index;
});
},
resetSelectedID () {
this.selectedIndexID = this.indexesProxy.length ? this.indexesProxy[0]._antares_id : '';
}
}
}; };
const selectIndex = (event: MouseEvent, id: string) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (selectedIndexID.value !== id && !(event.target as any).classList.contains('remove-field'))
selectedIndexID.value = id;
};
const getModalInnerHeight = () => {
const modalBody = document.querySelector('.modal-body');
if (modalBody)
modalInnerHeight.value = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
};
const addIndex = () => {
indexesProxy.value = [...indexesProxy.value, {
_antares_id: uidGen(),
name: 'NEW_INDEX',
fields: [],
type: 'INDEX',
comment: '',
indexType: 'BTREE',
indexComment: '',
cardinality: 0
}];
if (indexesProxy.value.length === 1)
resetSelectedID();
setTimeout(() => {
indexesPanel.value.scrollTop = indexesPanel.value.scrollHeight + 60;
}, 20);
};
const removeIndex = (id: string) => {
indexesProxy.value = indexesProxy.value.filter(index => index._antares_id !== id);
if (selectedIndexID.value === id && indexesProxy.value.length)
resetSelectedID();
};
const clearChanges = () => {
indexesProxy.value = JSON.parse(JSON.stringify(props.localIndexes));
if (!indexesProxy.value.some(index => index._antares_id === selectedIndexID.value))
resetSelectedID();
};
const toggleField = (field: string) => {
indexesProxy.value = indexesProxy.value.map(index => {
if (index._antares_id === selectedIndexID.value) {
if (index.fields.includes(field))
index.fields = index.fields.filter((f: string) => f !== field);
else
index.fields.push(field);
}
return index;
});
};
const resetSelectedID = () => {
selectedIndexID.value = indexesProxy.value.length ? indexesProxy.value[0]._antares_id : '';
};
onMounted(() => {
indexesProxy.value = JSON.parse(JSON.stringify(props.localIndexes));
if (indexesProxy.value.length)
resetSelectedID();
getModalInnerHeight();
window.addEventListener('resize', getModalInnerHeight);
});
onUnmounted(() => {
window.removeEventListener('resize', getModalInnerHeight);
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -219,7 +219,7 @@
</div> </div>
<ConfirmModal <ConfirmModal
v-if="isDefaultModal" v-if="isDefaultModal"
:confirm-text="$t('word.confirm')" :confirm-text="t('word.confirm')"
size="400" size="400"
@confirm="editOFF" @confirm="editOFF"
@hide="hideDefaultModal" @hide="hideDefaultModal"
@ -227,7 +227,7 @@
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-edit mr-1" /> <i class="mdi mdi-24px mdi-playlist-edit mr-1" />
<span class="cut-text">{{ $t('word.default') }} "{{ row.name }}"</span> <span class="cut-text">{{ t('word.default') }} "{{ row.name }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -250,7 +250,7 @@
value="custom" value="custom"
type="radio" type="radio"
name="default" name="default"
><i class="form-icon" /> {{ $t('message.customValue') }} ><i class="form-icon" /> {{ t('message.customValue') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -291,7 +291,7 @@
type="radio" type="radio"
name="default" name="default"
value="expression" value="expression"
><i class="form-icon" /> {{ $t('word.expression') }} ><i class="form-icon" /> {{ t('word.expression') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -306,7 +306,7 @@
<div v-if="customizations.onUpdate"> <div v-if="customizations.onUpdate">
<div class="form-group"> <div class="form-group">
<label class="form-label col-4"> <label class="form-label col-4">
{{ $t('message.onUpdate') }} {{ t('message.onUpdate') }}
</label> </label>
<div class="column"> <div class="column">
<input <input
@ -323,285 +323,269 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { computed, nextTick, onMounted, Prop, PropType, Ref, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import ConfirmModal from '@/components/BaseConfirmModal'; import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { TableField, TableIndex, TypesGroup } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsTableRow',
components: { const props = defineProps({
ConfirmModal, row: Object as Prop<TableField>,
BaseSelect dataTypes: {
type: Array as PropType<TypesGroup[]>,
default: () => []
}, },
props: { indexes: Array as Prop<TableIndex[]>,
row: Object, foreigns: Array as Prop<string[]>,
dataTypes: { type: Array, default: () => [] }, customizations: Object
indexes: Array, });
foreigns: Array,
customizations: Object
},
emits: ['contextmenu', 'rename-field'],
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const emit = defineEmits(['contextmenu', 'rename-field']);
const { getWorkspace } = workspacesStore; const workspacesStore = useWorkspacesStore();
return { const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore);
addNotification,
selectedWorkspace,
getWorkspace
};
},
data () {
return {
localRow: {},
isInlineEditor: {},
isDefaultModal: false,
defaultValue: {
type: 'noval',
custom: '',
expression: '',
onUpdate: ''
},
editingContent: null,
originalContent: null,
editingField: null
};
},
computed: {
localLength () {
const localLength = this.localRow.numLength || this.localRow.charLength || this.localRow.datePrecision || this.localRow.numPrecision || 0;
return localLength === true ? null : localLength;
},
fieldType () {
const fieldType = this.dataTypes.reduce((acc, group) => [...acc, ...group.types], []).filter(type =>
type.name === (this.localRow.type ? this.localRow.type.toUpperCase() : '')
);
const group = this.dataTypes.filter(group => group.types.some(type =>
type.name === (this.localRow.type ? this.localRow.type.toUpperCase() : ''))
);
return fieldType.length ? { ...fieldType[0], group: group[0].group } : {}; const { getWorkspace } = workspacesStore;
},
fieldDefault () {
if (this.localRow.autoIncrement) return 'AUTO_INCREMENT';
if (this.localRow.default === 'NULL') return 'NULL';
return this.localRow.default;
},
collations () {
return this.getWorkspace(this.selectedWorkspace).collations;
},
canAutoincrement () {
return this.indexes.some(index => ['PRIMARY', 'UNIQUE'].includes(index.type));
},
isNullable () {
return this.customizations.nullablePrimary || !this.indexes.some(index => ['PRIMARY'].includes(index.type));
},
isInDataTypes () {
let typeNames = [];
for (const group of this.dataTypes) {
const groupTypeNames = group.types.reduce((acc, curr) => {
acc.push(curr.name);
return acc;
}, []);
typeNames = [...groupTypeNames, ...typeNames]; const localRow: Ref<TableField> = ref({} as TableField);
} const isInlineEditor: Ref<TableField> = ref({} as TableField);
return typeNames.includes(this.row.type); const isDefaultModal = ref(false);
}, const defaultValue = ref({
types () { type: 'noval',
const types = [...this.dataTypes]; custom: '',
if (!this.isInDataTypes) expression: '',
types.unshift({ name: this.row }); onUpdate: ''
});
const editingContent: Ref<string | number> = ref(null);
const originalContent = ref(null);
const editingField: Ref<keyof TableField> = ref(null);
return types; const localLength = computed(() => {
} const localLength = localRow.value.numLength || localRow.value.charLength || localRow.value.datePrecision || localRow.value.numPrecision || 0 as number | true;
}, return localLength === true ? null : localLength;
watch: { });
localRow () {
this.initLocalRow();
},
row () {
this.localRow = this.row;
},
indexes () {
if (!this.canAutoincrement)
this.localRow.autoIncrement = false;
if (!this.isNullable) const fieldType = computed(() => {
this.localRow.nullable = false; const fieldType = props.dataTypes.reduce((acc, group) => [...acc, ...group.types], []).filter(type =>
} type.name === (localRow.value.type ? localRow.value.type.toUpperCase() : '')
}, );
mounted () { const group = props.dataTypes.filter(group => group.types.some(type =>
this.localRow = this.row; type.name === (localRow.value.type ? localRow.value.type.toUpperCase() : ''))
this.initLocalRow(); );
this.isInlineEditor.length = false;
},
methods: {
keyName (key) {
switch (key) {
case 'pri':
return 'PRIMARY';
case 'uni':
return 'UNIQUE';
case 'mul':
return 'INDEX';
default:
return 'UNKNOWN ' + key;
}
},
typeClass (type) {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
},
initLocalRow () {
Object.keys(this.localRow).forEach(key => {
this.isInlineEditor[key] = false;
});
this.defaultValue.onUpdate = this.localRow.onUpdate; return fieldType.length ? { ...fieldType[0], group: group[0].group } : {};
this.defaultValue.type = this.localRow.defaultType || 'noval'; });
if (this.defaultValue.type === 'custom') {
this.defaultValue.custom = this.localRow.default
? this.localRow.default.includes('\'')
? this.localRow.default.split('\'')[1]
: this.localRow.default
: '';
}
else if (this.defaultValue.type === 'expression') {
if (this.localRow.default.toUpperCase().includes('ON UPDATE'))
this.defaultValue.expression = this.localRow.default.replace(/ on update.*$/i, '');
else
this.defaultValue.expression = this.localRow.default;
}
},
editON (event, content, field) {
if (field === 'length') {
if (['integer', 'float', 'binary', 'spatial'].includes(this.fieldType.group)) this.editingField = 'numLength';
else if (['string', 'unknown'].includes(this.fieldType.group)) this.editingField = 'charLength';
else if (['other'].includes(this.fieldType.group)) this.editingField = 'enumValues';
else if (['time'].includes(this.fieldType.group)) this.editingField = 'datePrecision';
}
else
this.editingField = field;
if (this.localRow.enumValues && field === 'length') { const fieldDefault = computed(() => {
this.editingContent = this.localRow.enumValues; if (localRow.value.autoIncrement) return 'AUTO_INCREMENT';
this.originalContent = this.localRow.enumValues; if (localRow.value.default === 'NULL') return 'NULL';
} return localRow.value.default;
else if (this.fieldType.scale && field === 'length') { });
const scale = this.localRow.numScale !== null ? this.localRow.numScale : 0;
this.editingContent = `${content}, ${scale}`;
this.originalContent = `${content}, ${scale}`;
}
else {
this.editingContent = content;
this.originalContent = content;
}
const obj = { [field]: true }; const collations = computed(() => getWorkspace(selectedWorkspace.value).collations);
this.isInlineEditor = { ...this.isInlineEditor, ...obj }; const canAutoincrement = computed(() => props.indexes.some(index => ['PRIMARY', 'UNIQUE'].includes(index.type)));
const isNullable = computed(() => props.customizations.nullablePrimary || !props.indexes.some(index => ['PRIMARY'].includes(index.type)));
if (field === 'default') const isInDataTypes = computed(() => {
this.isDefaultModal = true; let typeNames: string[] = [];
else { for (const group of props.dataTypes) {
this.$nextTick(() => { // Focus on input const groupTypeNames = group.types.reduce((acc, curr) => {
event.target.blur(); acc.push(curr.name);
return acc;
}, []);
this.$nextTick(() => document.querySelector('.editable-field').focus()); typeNames = [...groupTypeNames, ...typeNames];
}); }
} return typeNames.includes(props.row.type);
}, });
editOFF () {
if (this.editingField === 'name')
this.$emit('rename-field', { old: this.localRow[this.editingField], new: this.editingContent });
if (this.editingField === 'numLength' && this.fieldType.scale) { const types = computed(() => {
const [length, scale] = this.editingContent.split(','); const types = [...props.dataTypes];
this.localRow.numLength = +length; if (!isInDataTypes.value)
this.localRow.numScale = scale ? +scale : null; // eslint-disable-next-line @typescript-eslint/no-explicit-any
} (types as any).unshift({ name: props.row });
else
this.localRow[this.editingField] = this.editingContent;
if (this.editingField === 'type' && this.editingContent !== this.originalContent) { return types;
this.localRow.numLength = null; });
this.localRow.numScale = null;
this.localRow.charLength = null;
this.localRow.datePrecision = null;
this.localRow.enumValues = '';
if (this.fieldType.length) { const typeClass = (type: string) => {
if (['integer', 'float', 'binary', 'spatial'].includes(this.fieldType.group)) this.localRow.numLength = 11; if (type)
if (['string'].includes(this.fieldType.group)) this.localRow.charLength = 15; return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
if (['time'].includes(this.fieldType.group)) this.localRow.datePrecision = 0; return '';
if (['other'].includes(this.fieldType.group)) this.localRow.enumValues = '\'valA\',\'valB\''; };
}
if (!this.fieldType.collation) const initLocalRow = () => {
this.localRow.collation = null; Object.keys(localRow.value).forEach(key => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(isInlineEditor as any).value[key] = false;
});
if (!this.fieldType.unsigned) defaultValue.value.onUpdate = localRow.value.onUpdate;
this.localRow.unsigned = false; defaultValue.value.type = localRow.value.defaultType || 'noval';
if (defaultValue.value.type === 'custom') {
if (!this.fieldType.zerofill) defaultValue.value.custom = localRow.value.default
this.localRow.zerofill = false; ? localRow.value.default.includes('\'')
} ? localRow.value.default.split('\'')[1]
else if (this.editingField === 'default') { : localRow.value.default
switch (this.defaultValue.type) { : '';
case 'autoincrement': }
this.localRow.autoIncrement = true; else if (defaultValue.value.type === 'expression') {
break; if (localRow.value.default.toUpperCase().includes('ON UPDATE'))
case 'noval': defaultValue.value.expression = localRow.value.default.replace(/ on update.*$/i, '');
this.localRow.autoIncrement = false; else
this.localRow.default = null; defaultValue.value.expression = localRow.value.default;
break;
case 'null':
this.localRow.autoIncrement = false;
this.localRow.default = 'NULL';
break;
case 'custom':
this.localRow.autoIncrement = false;
this.localRow.default = Number.isNaN(+this.defaultValue.custom) ? `'${this.defaultValue.custom}'` : this.defaultValue.custom;
break;
case 'expression':
this.localRow.autoIncrement = false;
this.localRow.default = this.defaultValue.expression;
break;
}
this.localRow.onUpdate = this.defaultValue.onUpdate;
}
Object.keys(this.isInlineEditor).forEach(key => {
this.isInlineEditor = { ...this.isInlineEditor, [key]: false };
});
this.editingContent = null;
this.originalContent = null;
this.editingField = null;
},
checkLengthScale (e) {
e = (e) || window.event;
const charCode = (e.which) ? e.which : e.keyCode;
if (((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 44) || (charCode === 44 && e.target.value.includes(',')))
e.preventDefault();
else
return true;
},
hideDefaultModal () {
this.isDefaultModal = false;
}
} }
}; };
const editON = async (event: MouseEvent, content: string | number, field: keyof TableField) => {
if (field === 'length') {
if (['integer', 'float', 'binary', 'spatial'].includes(fieldType.value.group)) editingField.value = 'numLength';
else if (['string', 'unknown'].includes(fieldType.value.group)) editingField.value = 'charLength';
else if (['other'].includes(fieldType.value.group)) editingField.value = 'enumValues';
else if (['time'].includes(fieldType.value.group)) editingField.value = 'datePrecision';
}
else
editingField.value = field;
if (localRow.value.enumValues && field === 'length') {
editingContent.value = localRow.value.enumValues;
originalContent.value = localRow.value.enumValues;
}
else if (fieldType.value.scale && field === 'length') {
const scale = localRow.value.numScale !== null ? localRow.value.numScale : 0;
editingContent.value = `${content}, ${scale}`;
originalContent.value = `${content}, ${scale}`;
}
else {
editingContent.value = content;
originalContent.value = content;
}
const obj = { [field]: true };
isInlineEditor.value = { ...isInlineEditor.value, ...obj };
if (field === 'default')
isDefaultModal.value = true;
else {
await nextTick();
(event as MouseEvent & { target: HTMLInputElement }).target.blur();
await nextTick();
document.querySelector<HTMLInputElement>('.editable-field').focus();
}
};
const editOFF = () => {
if (editingField.value === 'name')
emit('rename-field', { old: localRow.value[editingField.value], new: editingContent.value });
if (editingField.value === 'numLength' && fieldType.value.scale) {
const [length, scale] = (editingContent.value as string).split(',');
localRow.value.numLength = +length;
localRow.value.numScale = scale ? +scale : null;
}
else
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(localRow.value as any)[editingField.value] = editingContent.value;
if (editingField.value === 'type' && editingContent.value !== originalContent.value) {
localRow.value.numLength = null;
localRow.value.numScale = null;
localRow.value.charLength = null;
localRow.value.datePrecision = null;
localRow.value.enumValues = '';
if (fieldType.value.length) {
if (['integer', 'float', 'binary', 'spatial'].includes(fieldType.value.group)) localRow.value.numLength = 11;
if (['string'].includes(fieldType.value.group)) localRow.value.charLength = 15;
if (['time'].includes(fieldType.value.group)) localRow.value.datePrecision = 0;
if (['other'].includes(fieldType.value.group)) localRow.value.enumValues = '\'valA\',\'valB\'';
}
if (!fieldType.value.collation)
localRow.value.collation = null;
if (!fieldType.value.unsigned)
localRow.value.unsigned = false;
if (!fieldType.value.zerofill)
localRow.value.zerofill = false;
}
else if (editingField.value === 'default') {
switch (defaultValue.value.type) {
case 'autoincrement':
localRow.value.autoIncrement = true;
break;
case 'noval':
localRow.value.autoIncrement = false;
localRow.value.default = null;
break;
case 'null':
localRow.value.autoIncrement = false;
localRow.value.default = 'NULL';
break;
case 'custom':
localRow.value.autoIncrement = false;
localRow.value.default = Number.isNaN(+defaultValue.value.custom) ? `'${defaultValue.value.custom}'` : defaultValue.value.custom;
break;
case 'expression':
localRow.value.autoIncrement = false;
localRow.value.default = defaultValue.value.expression;
break;
}
localRow.value.onUpdate = defaultValue.value.onUpdate;
}
Object.keys(isInlineEditor.value).forEach(key => {
isInlineEditor.value = { ...isInlineEditor.value, [key]: false };
});
editingContent.value = null;
originalContent.value = null;
editingField.value = null;
};
const checkLengthScale = (e: KeyboardEvent & { target: HTMLInputElement }) => {
e = (e) || window.event as KeyboardEvent & { target: HTMLInputElement };
const charCode = (e.which) ? e.which : e.code;
if (((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 44) || (charCode === 44 && e.target.value.includes(',')))
e.preventDefault();
else
return true;
};
const hideDefaultModal = () => {
isDefaultModal.value = false;
};
watch(localRow, () => {
initLocalRow();
});
watch(() => props.row, () => {
localRow.value = props.row;
});
watch(() => props.indexes, () => {
if (!canAutoincrement.value)
localRow.value.autoIncrement = false;
if (!isNullable.value)
localRow.value.nullable = false;
});
onMounted(() => {
localRow.value = props.row;
initLocalRow();
isInlineEditor.value.length = false;
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -11,20 +11,20 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
<div class="workspace-query-info"> <div class="workspace-query-info">
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -34,7 +34,7 @@
<div class="columns"> <div class="columns">
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.name') }}</label> <label class="form-label">{{ t('word.name') }}</label>
<input <input
v-model="localTrigger.name" v-model="localTrigger.name"
class="form-input" class="form-input"
@ -44,12 +44,12 @@
</div> </div>
<div v-if="customizations.definer" class="column col-auto"> <div v-if="customizations.definer" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.definer') }}</label> <label class="form-label">{{ t('word.definer') }}</label>
<BaseSelect <BaseSelect
v-model="localTrigger.definer" v-model="localTrigger.definer"
:options="users" :options="users"
:option-label="(user) => user.value === '' ? $t('message.currentUser') : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? t('message.currentUser') : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
/> />
</div> </div>
@ -57,7 +57,7 @@
<fieldset class="column columns mb-0" :disabled="customizations.triggerOnlyRename"> <fieldset class="column columns mb-0" :disabled="customizations.triggerOnlyRename">
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.table') }}</label> <label class="form-label">{{ t('word.table') }}</label>
<BaseSelect <BaseSelect
v-model="localTrigger.table" v-model="localTrigger.table"
:options="schemaTables" :options="schemaTables"
@ -69,7 +69,7 @@
</div> </div>
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.event') }}</label> <label class="form-label">{{ t('word.event') }}</label>
<div class="input-group"> <div class="input-group">
<BaseSelect <BaseSelect
v-model="localTrigger.activation" v-model="localTrigger.activation"
@ -85,7 +85,7 @@
<div v-if="customizations.triggerMultipleEvents" class="px-4"> <div v-if="customizations.triggerMultipleEvents" class="px-4">
<label <label
v-for="event in Object.keys(localEvents)" v-for="event in (Object.keys(localEvents) as ('INSERT' | 'UPDATE' | 'DELETE')[])"
:key="event" :key="event"
class="form-checkbox form-inline" class="form-checkbox form-inline"
@change.prevent="changeEvents(event)" @change.prevent="changeEvents(event)"
@ -101,7 +101,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.triggerStatement') }}</label> <label class="form-label ml-2">{{ t('message.triggerStatement') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -114,268 +114,252 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onBeforeUnmount, onMounted, onUnmounted, Ref, ref, watch } from 'vue';
import { Ace } from 'ace-builds';
import { useI18n } from 'vue-i18n';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import QueryEditor from '@/components/QueryEditor'; import QueryEditor from '@/components/QueryEditor.vue';
import BaseLoader from '@/components/BaseLoader'; import BaseLoader from '@/components/BaseLoader.vue';
import Triggers from '@/ipc-api/Triggers'; import Triggers from '@/ipc-api/Triggers';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
export default { type TriggerEventName = 'INSERT' | 'UPDATE' | 'DELETE'
name: 'WorkspaceTabPropsTrigger',
components: {
BaseLoader,
QueryEditor,
BaseSelect
},
props: {
tabUid: String,
connection: Object,
trigger: String,
isSelected: Boolean,
schema: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const { t } = useI18n();
const { const props = defineProps({
getWorkspace, tabUid: String,
refreshStructure, connection: Object,
renameTabs, trigger: String,
newTab, isSelected: Boolean,
changeBreadcrumbs, schema: String
setUnsavedChanges });
} = workspacesStore;
return { const { addNotification } = useNotificationsStore();
addNotification, const workspacesStore = useWorkspacesStore();
selectedWorkspace,
getWorkspace,
refreshStructure,
renameTabs,
newTab,
changeBreadcrumbs,
setUnsavedChanges
};
},
data () {
return {
isLoading: false,
isSaving: false,
originalTrigger: null,
localTrigger: { sql: '' },
lastTrigger: null,
sqlProxy: '',
editorHeight: 300,
localEvents: { INSERT: false, UPDATE: false, DELETE: false }
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
customizations () {
return this.workspace.customizations;
},
isChanged () {
return JSON.stringify(this.originalTrigger) !== JSON.stringify(this.localTrigger);
},
isDefinerInUsers () {
return this.originalTrigger ? this.workspace.users.some(user => this.originalTrigger.definer === `\`${user.name}\`@\`${user.host}\``) : true;
},
schemaTables () {
const schemaTables = this.workspace.structure
.filter(schema => schema.name === this.schema)
.map(schema => schema.tables);
return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : []; const {
}, getWorkspace,
users () { refreshStructure,
const users = [{ value: '' }, ...this.workspace.users]; renameTabs,
if (!this.isDefinerInUsers) { changeBreadcrumbs,
const [name, host] = this.originalTrigger.definer.replaceAll('`', '').split('@'); setUnsavedChanges
users.unshift({ name, host }); } = workspacesStore;
}
return users; const queryEditor: Ref<Component & {editor: Ace.Editor; $el: HTMLElement}> = ref(null);
} const lastTrigger = ref(null);
}, const isLoading = ref(false);
watch: { const isSaving = ref(false);
async schema () { const originalTrigger = ref(null);
if (this.isSelected) { const localTrigger = ref(null);
await this.getTriggerData(); const editorHeight = ref(300);
this.$refs.queryEditor.editor.session.setValue(this.localTrigger.sql); const localEvents = ref({ INSERT: false, UPDATE: false, DELETE: false });
this.lastTrigger = this.trigger;
}
},
async trigger () {
if (this.isSelected) {
await this.getTriggerData();
this.$refs.queryEditor.editor.session.setValue(this.localTrigger.sql);
this.lastTrigger = this.trigger;
}
},
async isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, trigger: this.trigger });
setTimeout(() => { const workspace = computed(() => {
this.resizeQueryEditor(); return getWorkspace(props.connection.uid);
}, 200); });
if (this.lastTrigger !== this.trigger) const customizations = computed(() => {
this.getTriggerData(); return workspace.value.customizations;
} });
},
isChanged (val) {
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
}
},
async created () {
await this.getTriggerData();
this.$refs.queryEditor.editor.session.setValue(this.localTrigger.sql);
window.addEventListener('keydown', this.onKey);
},
mounted () {
window.addEventListener('resize', this.resizeQueryEditor);
},
unmounted () {
window.removeEventListener('resize', this.resizeQueryEditor);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getTriggerData () {
if (!this.trigger) return;
Object.keys(this.localEvents).forEach(event => { const isChanged = computed(() => {
this.localEvents[event] = false; return JSON.stringify(originalTrigger.value) !== JSON.stringify(localTrigger.value);
}); });
this.localTrigger = { sql: '' }; const isDefinerInUsers = computed(() => {
this.isLoading = true; return originalTrigger.value ? workspace.value.users.some(user => originalTrigger.value.definer === `\`${user.name}\`@\`${user.host}\``) : true;
this.lastTrigger = this.trigger; });
const params = { const schemaTables = computed(() => {
uid: this.connection.uid, const schemaTables = workspace.value.structure
schema: this.schema, .filter(schema => schema.name === props.schema)
trigger: this.trigger .map(schema => schema.tables);
};
try { return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : [];
const { status, response } = await Triggers.getTriggerInformations(params); });
if (status === 'success') {
this.originalTrigger = response;
this.localTrigger = JSON.parse(JSON.stringify(this.originalTrigger));
this.sqlProxy = this.localTrigger.sql;
if (this.customizations.triggerMultipleEvents) { const users = computed(() => {
this.originalTrigger.event.forEach(e => { const users = [{ value: '' }, ...workspace.value.users];
this.localEvents[e] = true; if (!isDefinerInUsers.value) {
}); const [name, host] = originalTrigger.value.definer.replaceAll('`', '').split('@');
} users.unshift({ name, host });
} }
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor(); return users;
this.isLoading = false; });
},
changeEvents (event) {
if (this.customizations.triggerMultipleEvents) {
this.localEvents[event] = !this.localEvents[event];
this.localTrigger.event = [];
for (const key in this.localEvents) {
if (this.localEvents[key])
this.localTrigger.event.push(key);
}
}
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
const params = {
uid: this.connection.uid,
trigger: {
...this.localTrigger,
schema: this.schema,
oldName: this.originalTrigger.name
}
};
try { const getTriggerData = async () => {
const { status, response } = await Triggers.alterTrigger(params); if (!props.trigger) return;
if (status === 'success') { Object.keys(localEvents.value).forEach((event: TriggerEventName) => {
await this.refreshStructure(this.connection.uid); localEvents.value[event] = false;
});
if (this.originalTrigger.name !== this.localTrigger.name) { localTrigger.value = { sql: '' };
const triggerName = this.customizations.triggerTableInName ? `${this.localTrigger.table}.${this.localTrigger.name}` : this.localTrigger.name; isLoading.value = true;
const triggerOldName = this.customizations.triggerTableInName ? `${this.originalTrigger.table}.${this.originalTrigger.name}` : this.originalTrigger.name; lastTrigger.value = props.trigger;
this.renameTabs({ const params = {
uid: this.connection.uid, uid: props.connection.uid,
schema: this.schema, schema: props.schema,
elementName: triggerOldName, trigger: props.trigger
elementNewName: triggerName, };
elementType: 'trigger'
});
this.changeBreadcrumbs({ schema: this.schema, trigger: triggerName }); try {
} const { status, response } = await Triggers.getTriggerInformations(params);
else if (status === 'success') {
this.getTriggerData(); originalTrigger.value = response;
} localTrigger.value = JSON.parse(JSON.stringify(originalTrigger.value));
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false; if (customizations.value.triggerMultipleEvents) {
}, originalTrigger.value.event.forEach((event: TriggerEventName) => {
clearChanges () { localEvents.value[event] = true;
this.localTrigger = JSON.parse(JSON.stringify(this.originalTrigger));
this.$refs.queryEditor.editor.session.setValue(this.localTrigger.sql);
Object.keys(this.localEvents).forEach(event => {
this.localEvents[event] = false;
});
if (this.customizations.triggerMultipleEvents) {
this.originalTrigger.event.forEach(e => {
this.localEvents[e] = true;
}); });
} }
}, }
resizeQueryEditor () { else
if (this.$refs.queryEditor) { addNotification({ status: 'error', message: response });
const footer = document.getElementById('footer'); }
const size = window.innerHeight - this.$refs.queryEditor.$el.getBoundingClientRect().top - footer.offsetHeight; catch (err) {
this.editorHeight = size; addNotification({ status: 'error', message: err.stack });
this.$refs.queryEditor.editor.resize(); }
}
}, resizeQueryEditor();
onKey (e) { isLoading.value = false;
if (this.isSelected) { };
e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S const changeEvents = (event: TriggerEventName) => {
if (this.isChanged) if (customizations.value.triggerMultipleEvents) {
this.saveChanges(); localEvents.value[event] = !localEvents.value[event];
} localTrigger.value.event = [];
} for (const key in localEvents.value) {
if (localEvents.value[key as TriggerEventName])
localTrigger.value.event.push(key);
} }
} }
}; };
const saveChanges = async () => {
if (isSaving.value) return;
isSaving.value = true;
const params = {
uid: props.connection.uid,
trigger: {
...localTrigger.value,
schema: props.schema,
oldName: originalTrigger.value.name
}
};
try {
const { status, response } = await Triggers.alterTrigger(params);
if (status === 'success') {
await refreshStructure(props.connection.uid);
if (originalTrigger.value.name !== localTrigger.value.name) {
const triggerName = customizations.value.triggerTableInName ? `${localTrigger.value.table}.${localTrigger.value.name}` : localTrigger.value.name;
const triggerOldName = customizations.value.triggerTableInName ? `${originalTrigger.value.table}.${originalTrigger.value.name}` : originalTrigger.value.name;
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: triggerOldName,
elementNewName: triggerName,
elementType: 'trigger'
});
changeBreadcrumbs({ schema: props.schema, trigger: triggerName });
}
else
getTriggerData();
}
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
isSaving.value = false;
};
const clearChanges = () => {
localTrigger.value = JSON.parse(JSON.stringify(originalTrigger.value));
queryEditor.value.editor.session.setValue(localTrigger.value.sql);
Object.keys(localEvents.value).forEach((event: TriggerEventName) => {
localEvents.value[event] = false;
});
if (customizations.value.triggerMultipleEvents) {
originalTrigger.value.event.forEach((event: TriggerEventName) => {
localEvents.value[event] = true;
});
}
};
const resizeQueryEditor = () => {
if (queryEditor.value) {
const footer = document.getElementById('footer');
const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
editorHeight.value = size;
queryEditor.value.editor.resize();
}
};
const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.key === 's') { // CTRL + S
if (isChanged.value)
saveChanges();
}
}
};
watch(() => props.schema, async () => {
if (props.isSelected) {
await getTriggerData();
queryEditor.value.editor.session.setValue(localTrigger.value.sql);
lastTrigger.value = props.trigger;
}
});
watch(() => props.trigger, async () => {
if (props.isSelected) {
await getTriggerData();
queryEditor.value.editor.session.setValue(localTrigger.value.sql);
lastTrigger.value = props.trigger;
}
});
watch(() => props.isSelected, (val) => {
if (val) changeBreadcrumbs({ schema: props.schema });
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
(async () => {
await getTriggerData();
queryEditor.value.editor.session.setValue(localTrigger.value.sql);
window.addEventListener('keydown', onKey);
})();
onMounted(() => {
window.addEventListener('resize', resizeQueryEditor);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeQueryEditor);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script> </script>

View File

@ -11,16 +11,16 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
</div> </div>
@ -30,7 +30,7 @@
<div v-if="customizations.triggerFunctionlanguages" class="column col-auto"> <div v-if="customizations.triggerFunctionlanguages" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.language') }} {{ t('word.language') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.language" v-model="localFunction.language"
@ -42,20 +42,20 @@
<div v-if="customizations.definer" class="column col-auto"> <div v-if="customizations.definer" class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.definer') }} {{ t('word.definer') }}
</label> </label>
<BaseSelect <BaseSelect
v-model="localFunction.definer" v-model="localFunction.definer"
:options="workspace.users" :options="workspace.users"
:option-label="(user) => user.value === '' ? $t('message.currentUser') : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? t('message.currentUser') : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
/> />
</div> </div>
</div> </div>
<div v-if="customizations.comment" class="form-group"> <div v-if="customizations.comment" class="form-group">
<label class="form-label"> <label class="form-label">
{{ $t('word.comment') }} {{ t('word.comment') }}
</label> </label>
<input <input
v-model="localFunction.comment" v-model="localFunction.comment"
@ -67,7 +67,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.functionBody') }}</label> <label class="form-label ml-2">{{ t('message.functionBody') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -77,295 +77,194 @@
:height="editorHeight" :height="editorHeight"
/> />
</div> </div>
<ModalAskParameters
v-if="isAskingParameters"
:local-routine="localFunction"
:client="workspace.client"
@confirm="runFunction"
@close="hideAskParamsModal"
/>
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onBeforeUnmount, onMounted, onUnmounted, Ref, ref, watch } from 'vue';
import { Ace } from 'ace-builds';
import { useI18n } from 'vue-i18n';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import { uidGen } from 'common/libs/uidGen'; import BaseLoader from '@/components/BaseLoader.vue';
import BaseLoader from '@/components/BaseLoader'; import QueryEditor from '@/components/QueryEditor.vue';
import QueryEditor from '@/components/QueryEditor';
import ModalAskParameters from '@/components/ModalAskParameters';
import Functions from '@/ipc-api/Functions'; import Functions from '@/ipc-api/Functions';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { AlterFunctionParams, TriggerFunctionInfos } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsTriggerFunction',
components: {
BaseLoader,
QueryEditor,
ModalAskParameters,
BaseSelect
},
props: {
tabUid: String,
connection: Object,
function: String,
isSelected: Boolean,
schema: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
tabUid: String,
connection: Object,
function: String,
isSelected: Boolean,
schema: String
});
const { const { addNotification } = useNotificationsStore();
getWorkspace, const workspacesStore = useWorkspacesStore();
refreshStructure,
renameTabs,
newTab,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
return { const {
addNotification, getWorkspace,
selectedWorkspace, refreshStructure,
getWorkspace, renameTabs,
refreshStructure, changeBreadcrumbs,
renameTabs, setUnsavedChanges
newTab, } = workspacesStore;
changeBreadcrumbs,
setUnsavedChanges
};
},
data () {
return {
isLoading: false,
isSaving: false,
isParamsModal: false,
isAskingParameters: false,
originalFunction: null,
localFunction: { sql: '' },
lastFunction: null,
sqlProxy: '',
editorHeight: 300
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
customizations () {
return this.workspace.customizations;
},
isChanged () {
return JSON.stringify(this.originalFunction) !== JSON.stringify(this.localFunction);
},
isDefinerInUsers () {
return this.originalFunction
? this.workspace.users.some(user => this.originalFunction.definer === `\`${user.name}\`@\`${user.host}\``)
: true;
},
schemaTables () {
const schemaTables = this.workspace.structure
.filter(schema => schema.name === this.schema)
.map(schema => schema.tables);
return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : []; const queryEditor: Ref<Component & {editor: Ace.Editor; $el: HTMLElement}> = ref(null);
const isLoading = ref(false);
const isSaving = ref(false);
const originalFunction: Ref<TriggerFunctionInfos> = ref(null);
const localFunction: Ref<TriggerFunctionInfos> = ref(null);
const lastFunction = ref(null);
const sqlProxy = ref('');
const editorHeight = ref(300);
const workspace = computed(() => getWorkspace(props.connection.uid));
const customizations = computed(() => workspace.value.customizations);
const isChanged = computed(() => JSON.stringify(originalFunction.value) !== JSON.stringify(localFunction.value));
const getFunctionData = async () => {
if (!props.function) return;
isLoading.value = true;
localFunction.value = { name: '', sql: '', type: '', definer: null };
lastFunction.value = props.function;
const params = {
uid: props.connection.uid,
schema: props.schema,
func: props.function
};
try {
const { status, response } = await Functions.getFunctionInformations(params);
if (status === 'success') {
originalFunction.value = response;
localFunction.value = JSON.parse(JSON.stringify(originalFunction.value));
sqlProxy.value = localFunction.value.sql;
} }
}, else
watch: { addNotification({ status: 'error', message: response });
async schema () { }
if (this.isSelected) { catch (err) {
await this.getFunctionData(); addNotification({ status: 'error', message: err.stack });
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql); }
this.lastFunction = this.function;
resizeQueryEditor();
isLoading.value = false;
};
const saveChanges = async () => {
if (isSaving.value) return;
isSaving.value = true;
const params = {
uid: props.connection.uid,
func: {
...localFunction.value,
schema: props.schema,
oldName: originalFunction.value.name
} as AlterFunctionParams
};
try {
const { status, response } = await Functions.alterTriggerFunction(params);
if (status === 'success') {
const oldName = originalFunction.value.name;
await refreshStructure(props.connection.uid);
if (oldName !== localFunction.value.name) {
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: oldName,
elementNewName: localFunction.value.name,
elementType: 'triggerFunction'
});
changeBreadcrumbs({ schema: props.schema, triggerFunction: localFunction.value.name });
} }
},
async function () {
if (this.isSelected) {
await this.getFunctionData();
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql);
this.lastFunction = this.function;
}
},
async isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, triggerFunction: this.function });
setTimeout(() => {
this.resizeQueryEditor();
}, 200);
if (this.lastFunction !== this.function)
await this.getFunctionData();
}
},
isChanged (val) {
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
}
},
async created () {
await this.getFunctionData();
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql);
window.addEventListener('keydown', this.onKey);
},
mounted () {
window.addEventListener('resize', this.resizeQueryEditor);
},
unmounted () {
window.removeEventListener('resize', this.resizeQueryEditor);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getFunctionData () {
if (!this.function) return;
this.isLoading = true;
this.localFunction = { sql: '' };
this.lastFunction = this.function;
const params = {
uid: this.connection.uid,
schema: this.schema,
func: this.function
};
try {
const { status, response } = await Functions.getFunctionInformations(params);
if (status === 'success') {
this.originalFunction = response;
this.originalFunction.parameters = [...this.originalFunction.parameters.map(param => {
param._antares_id = uidGen();
return param;
})];
this.localFunction = JSON.parse(JSON.stringify(this.originalFunction));
this.sqlProxy = this.localFunction.sql;
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor();
this.isLoading = false;
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
const params = {
uid: this.connection.uid,
func: {
...this.localFunction,
schema: this.schema,
oldName: this.originalFunction.name
}
};
try {
const { status, response } = await Functions.alterTriggerFunction(params);
if (status === 'success') {
const oldName = this.originalFunction.name;
await this.refreshStructure(this.connection.uid);
if (oldName !== this.localFunction.name) {
this.renameTabs({
uid: this.connection.uid,
schema: this.schema,
elementName: oldName,
elementNewName: this.localFunction.name,
elementType: 'triggerFunction'
});
this.changeBreadcrumbs({ schema: this.schema, triggerFunction: this.localFunction.name });
}
else
this.getFunctionData();
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false;
},
clearChanges () {
this.localFunction = JSON.parse(JSON.stringify(this.originalFunction));
this.$refs.queryEditor.editor.session.setValue(this.localFunction.sql);
},
resizeQueryEditor () {
if (this.$refs.queryEditor) {
const footer = document.getElementById('footer');
const size = window.innerHeight - this.$refs.queryEditor.$el.getBoundingClientRect().top - footer.offsetHeight;
this.editorHeight = size;
this.$refs.queryEditor.editor.resize();
}
},
optionsUpdate (options) {
this.localFunction = options;
},
parametersUpdate (parameters) {
this.localFunction = { ...this.localFunction, parameters };
},
runFunctionCheck () {
if (this.localFunction.parameters.length)
this.showAskParamsModal();
else else
this.runFunction(); getFunctionData();
}, }
runFunction (params) { else
if (!params) params = []; addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
let sql; isSaving.value = false;
switch (this.connection.client) { // TODO: move in a better place };
case 'maria':
case 'mysql':
sql = `SELECT \`${this.originalFunction.name}\` (${params.join(',')})`;
break;
case 'pg':
sql = `SELECT ${this.originalFunction.name}(${params.join(',')})`;
break;
case 'mssql':
sql = `SELECT ${this.originalFunction.name} ${params.join(',')}`;
break;
default:
sql = `SELECT \`${this.originalFunction.name}\` (${params.join(',')})`;
}
this.newTab({ uid: this.connection.uid, content: sql, type: 'query', autorun: true }); const clearChanges = () => {
}, localFunction.value = JSON.parse(JSON.stringify(originalFunction.value));
showParamsModal () { queryEditor.value.editor.session.setValue(localFunction.value.sql);
this.isParamsModal = true; };
},
hideParamsModal () { const resizeQueryEditor = () => {
this.isParamsModal = false; if (queryEditor.value) {
}, const footer = document.getElementById('footer');
showAskParamsModal () { const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
this.isAskingParameters = true; editorHeight.value = size;
}, queryEditor.value.editor.resize();
hideAskParamsModal () { }
this.isAskingParameters = false; };
},
onKey (e) { const onKey = (e: KeyboardEvent) => {
if (this.isSelected) { if (props.isSelected) {
e.stopPropagation(); e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S if (e.ctrlKey && e.key === 's') { // CTRL + S
if (this.isChanged) if (isChanged.value)
this.saveChanges(); saveChanges();
}
}
} }
} }
}; };
watch(() => props.schema, async () => {
if (props.isSelected) {
await getFunctionData();
queryEditor.value.editor.session.setValue(localFunction.value.sql);
lastFunction.value = props.function;
}
});
watch(() => props.function, async () => {
if (props.isSelected) {
await getFunctionData();
queryEditor.value.editor.session.setValue(localFunction.value.sql);
lastFunction.value = props.function;
}
});
watch(() => props.isSelected, (val) => {
if (val) changeBreadcrumbs({ schema: props.schema });
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
(async () => {
await getFunctionData();
queryEditor.value.editor.session.setValue(localFunction.value.sql);
window.addEventListener('keydown', onKey);
})();
onMounted(() => {
window.addEventListener('resize', resizeQueryEditor);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeQueryEditor);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script> </script>

View File

@ -11,20 +11,20 @@
@click="saveChanges" @click="saveChanges"
> >
<i class="mdi mdi-24px mdi-content-save mr-1" /> <i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span> <span>{{ t('word.save') }}</span>
</button> </button>
<button <button
:disabled="!isChanged" :disabled="!isChanged"
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')" :title="t('message.clearChanges')"
@click="clearChanges" @click="clearChanges"
> >
<i class="mdi mdi-24px mdi-delete-sweep mr-1" /> <i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
</div> </div>
<div class="workspace-query-info"> <div class="workspace-query-info">
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -34,7 +34,7 @@
<div class="columns"> <div class="columns">
<div class="column col-auto"> <div class="column col-auto">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('word.name') }}</label> <label class="form-label">{{ t('word.name') }}</label>
<input <input
v-model="localView.name" v-model="localView.name"
class="form-input" class="form-input"
@ -44,19 +44,19 @@
</div> </div>
<div class="column col-auto"> <div class="column col-auto">
<div v-if="workspace.customizations.definer" class="form-group"> <div v-if="workspace.customizations.definer" class="form-group">
<label class="form-label">{{ $t('word.definer') }}</label> <label class="form-label">{{ t('word.definer') }}</label>
<BaseSelect <BaseSelect
v-model="localView.definer" v-model="localView.definer"
:options="users" :options="users"
:option-label="(user) => user.value === '' ? $t('message.currentUser') : `${user.name}@${user.host}`" :option-label="(user: any) => user.value === '' ? t('message.currentUser') : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``" :option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select" class="form-select"
/> />
</div> </div>
</div> </div>
<div class="column col-auto mr-2"> <div class="column col-auto mr-2">
<div v-if="workspace.customizations.viewSqlSecurity" class="form-group"> <div v-if="workspace.customizations.viewSqlSecurity" class="form-group">
<label class="form-label">{{ $t('message.sqlSecurity') }}</label> <label class="form-label">{{ t('message.sqlSecurity') }}</label>
<BaseSelect <BaseSelect
v-model="localView.security" v-model="localView.security"
:options="['DEFINER', 'INVOKER']" :options="['DEFINER', 'INVOKER']"
@ -66,7 +66,7 @@
</div> </div>
<div class="column col-auto mr-2"> <div class="column col-auto mr-2">
<div v-if="workspace.customizations.viewAlgorithm" class="form-group"> <div v-if="workspace.customizations.viewAlgorithm" class="form-group">
<label class="form-label">{{ $t('word.algorithm') }}</label> <label class="form-label">{{ t('word.algorithm') }}</label>
<BaseSelect <BaseSelect
v-model="localView.algorithm" v-model="localView.algorithm"
:options="['UNDEFINED', 'MERGE', 'TEMPTABLE']" :options="['UNDEFINED', 'MERGE', 'TEMPTABLE']"
@ -76,10 +76,10 @@
</div> </div>
<div v-if="workspace.customizations.viewUpdateOption" class="column col-auto mr-2"> <div v-if="workspace.customizations.viewUpdateOption" class="column col-auto mr-2">
<div class="form-group"> <div class="form-group">
<label class="form-label">{{ $t('message.updateOption') }}</label> <label class="form-label">{{ t('message.updateOption') }}</label>
<BaseSelect <BaseSelect
v-model="localView.updateOption" v-model="localView.updateOption"
:option-track-by="(user) => user.value" :option-track-by="(user: any) => user.value"
:options="[{label: 'None', value: ''}, {label: 'CASCADED', value: 'CASCADED'}, {label: 'LOCAL', value: 'LOCAL'}]" :options="[{label: 'None', value: ''}, {label: 'CASCADED', value: 'CASCADED'}, {label: 'LOCAL', value: 'LOCAL'}]"
class="form-select" class="form-select"
/> />
@ -89,7 +89,7 @@
</div> </div>
<div class="workspace-query-results column col-12 mt-2 p-relative"> <div class="workspace-query-results column col-12 mt-2 p-relative">
<BaseLoader v-if="isLoading" /> <BaseLoader v-if="isLoading" />
<label class="form-label ml-2">{{ $t('message.selectStatement') }}</label> <label class="form-label ml-2">{{ t('message.selectStatement') }}</label>
<QueryEditor <QueryEditor
v-show="isSelected" v-show="isSelected"
ref="queryEditor" ref="queryEditor"
@ -102,223 +102,204 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onBeforeUnmount, onMounted, onUnmounted, Ref, ref, watch } from 'vue';
import { Ace } from 'ace-builds';
import { useI18n } from 'vue-i18n';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import BaseLoader from '@/components/BaseLoader'; import BaseLoader from '@/components/BaseLoader.vue';
import QueryEditor from '@/components/QueryEditor'; import QueryEditor from '@/components/QueryEditor.vue';
import Views from '@/ipc-api/Views';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import Views from '@/ipc-api/Views';
export default { const { t } = useI18n();
name: 'WorkspaceTabPropsView',
components: {
BaseLoader,
QueryEditor,
BaseSelect
},
props: {
tabUid: String,
connection: Object,
isSelected: Boolean,
schema: String,
view: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
tabUid: String,
connection: Object,
isSelected: Boolean,
schema: String,
view: String
});
const { const { addNotification } = useNotificationsStore();
getWorkspace, const workspacesStore = useWorkspacesStore();
refreshStructure,
renameTabs,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
return { const {
addNotification, getWorkspace,
selectedWorkspace, refreshStructure,
getWorkspace, renameTabs,
refreshStructure, changeBreadcrumbs,
renameTabs, setUnsavedChanges
changeBreadcrumbs, } = workspacesStore;
setUnsavedChanges
};
},
data () {
return {
isLoading: false,
isSaving: false,
originalView: null,
localView: { sql: '' },
lastView: null,
sqlProxy: '',
editorHeight: 300
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
isChanged () {
return JSON.stringify(this.originalView) !== JSON.stringify(this.localView);
},
isDefinerInUsers () {
return this.originalView ? this.workspace.users.some(user => this.originalView.definer === `\`${user.name}\`@\`${user.host}\``) : true;
},
users () {
const users = [{ value: '' }, ...this.workspace.users];
if (!this.isDefinerInUsers) {
const [name, host] = this.originalView.definer.replaceAll('`', '').split('@');
users.unshift({ name, host });
}
return users; const queryEditor: Ref<Component & {editor: Ace.Editor; $el: HTMLElement}> = ref(null);
const isLoading = ref(false);
const isSaving = ref(false);
const originalView = ref(null);
const localView = ref(null);
const editorHeight = ref(300);
const lastView = ref(null);
const sqlProxy = ref('');
const workspace = computed(() => getWorkspace(props.connection.uid));
const isChanged = computed(() => JSON.stringify(originalView.value) !== JSON.stringify(localView.value));
const isDefinerInUsers = computed(() => originalView.value ? workspace.value.users.some(user => originalView.value.definer === `\`${user.name}\`@\`${user.host}\``) : true);
const users = computed(() => {
const users = [{ value: '' }, ...workspace.value.users];
if (!isDefinerInUsers.value) {
const [name, host] = originalView.value.definer.replaceAll('`', '').split('@');
users.unshift({ name, host });
}
return users;
});
const getViewData = async () => {
if (!props.view) return;
isLoading.value = true;
localView.value = { sql: '' };
lastView.value = props.view;
const params = {
uid: props.connection.uid,
schema: props.schema,
view: props.view
};
try {
const { status, response } = await Views.getViewInformations(params);
if (status === 'success') {
originalView.value = response;
localView.value = JSON.parse(JSON.stringify(originalView.value));
sqlProxy.value = localView.value.sql;
} }
}, else
watch: { addNotification({ status: 'error', message: response });
async schema () { }
if (this.isSelected) { catch (err) {
await this.getViewData(); addNotification({ status: 'error', message: err.stack });
this.$refs.queryEditor.editor.session.setValue(this.localView.sql); }
this.lastView = this.view;
}
},
async view () {
if (this.isSelected) {
await this.getViewData();
this.$refs.queryEditor.editor.session.setValue(this.localView.sql);
this.lastView = this.view;
}
},
isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, view: this.view });
setTimeout(() => { resizeQueryEditor();
this.resizeQueryEditor(); isLoading.value = false;
}, 200); };
if (this.lastView !== this.view) const saveChanges = async () => {
this.getViewData(); if (isSaving.value) return;
} isSaving.value = true;
}, const params = {
isChanged (val) { uid: props.connection.uid,
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val }); view: {
...localView.value,
schema: props.schema,
oldName: originalView.value.name
} }
}, };
async created () {
await this.getViewData();
this.$refs.queryEditor.editor.session.setValue(this.localView.sql);
window.addEventListener('keydown', this.onKey);
},
mounted () {
window.addEventListener('resize', this.resizeQueryEditor);
},
unmounted () {
window.removeEventListener('resize', this.resizeQueryEditor);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getViewData () {
if (!this.view) return;
this.isLoading = true;
this.localView = { sql: '' };
this.lastView = this.view;
const params = { try {
uid: this.connection.uid, const { status, response } = await Views.alterView(params);
schema: this.schema,
view: this.view
};
try { if (status === 'success') {
const { status, response } = await Views.getViewInformations(params); const oldName = originalView.value.name;
if (status === 'success') {
this.originalView = response; await refreshStructure(props.connection.uid);
this.localView = JSON.parse(JSON.stringify(this.originalView));
this.sqlProxy = this.localView.sql; if (oldName !== localView.value.name) {
} renameTabs({
else uid: props.connection.uid,
this.addNotification({ status: 'error', message: response }); schema: props.schema,
} elementName: oldName,
catch (err) { elementNewName: localView.value.name,
this.addNotification({ status: 'error', message: err.stack }); elementType: 'view'
});
changeBreadcrumbs({ schema: props.schema, view: localView.value.name });
} }
else
getViewData();
}
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor(); isSaving.value = false;
this.isLoading = false; };
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
const params = {
uid: this.connection.uid,
view: {
...this.localView,
schema: this.schema,
oldName: this.originalView.name
}
};
try { const clearChanges = () => {
const { status, response } = await Views.alterView(params); localView.value = JSON.parse(JSON.stringify(originalView.value));
queryEditor.value.editor.session.setValue(localView.value.sql);
};
if (status === 'success') { const resizeQueryEditor = () => {
const oldName = this.originalView.name; if (queryEditor.value) {
const footer = document.getElementById('footer');
const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
editorHeight.value = size;
queryEditor.value.editor.resize();
}
};
await this.refreshStructure(this.connection.uid); const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
if (oldName !== this.localView.name) { e.stopPropagation();
this.renameTabs({ if (e.ctrlKey && e.key === 's') { // CTRL + S
uid: this.connection.uid, if (isChanged.value)
schema: this.schema, saveChanges();
elementName: oldName,
elementNewName: this.localView.name,
elementType: 'view'
});
this.changeBreadcrumbs({ schema: this.schema, view: this.localView.name });
}
else
this.getViewData();
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false;
},
clearChanges () {
this.localView = JSON.parse(JSON.stringify(this.originalView));
this.$refs.queryEditor.editor.session.setValue(this.localView.sql);
},
resizeQueryEditor () {
if (this.$refs.queryEditor) {
const footer = document.getElementById('footer');
const size = window.innerHeight - this.$refs.queryEditor.$el.getBoundingClientRect().top - footer.offsetHeight;
this.editorHeight = size;
this.$refs.queryEditor.editor.resize();
}
},
onKey (e) {
if (this.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (this.isChanged)
this.saveChanges();
}
}
} }
} }
}; };
watch(() => props.schema, async () => {
if (props.isSelected) {
await getViewData();
queryEditor.value.editor.session.setValue(localView.value.sql);
lastView.value = props.view;
}
});
watch(() => props.view, async () => {
if (props.isSelected) {
await getViewData();
queryEditor.value.editor.session.setValue(localView.value.sql);
lastView.value = props.view;
}
});
watch(() => props.isSelected, (val) => {
if (val) {
changeBreadcrumbs({ schema: props.schema, view: localView.value.name });
setTimeout(() => {
resizeQueryEditor();
}, 50);
}
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
(async () => {
await getViewData();
queryEditor.value.editor.session.setValue(localView.value.sql);
window.addEventListener('keydown', onKey);
})();
onMounted(() => {
window.addEventListener('resize', resizeQueryEditor);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeQueryEditor);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script> </script>

View File

@ -28,11 +28,11 @@
v-if="showCancel && isQuering" v-if="showCancel && isQuering"
class="btn btn-primary btn-sm cancellable" class="btn btn-primary btn-sm cancellable"
:disabled="!query" :disabled="!query"
:title="$t('word.cancel')" :title="t('word.cancel')"
@click="killTabQuery()" @click="killTabQuery()"
> >
<i class="mdi mdi-24px mdi-window-close" /> <i class="mdi mdi-24px mdi-window-close" />
<span class="d-invisible pr-1">{{ $t('word.run') }}</span> <span class="d-invisible pr-1">{{ t('word.run') }}</span>
</button> </button>
<button <button
v-else v-else
@ -43,7 +43,7 @@
@click="runQuery(query)" @click="runQuery(query)"
> >
<i class="mdi mdi-24px mdi-play pr-1" /> <i class="mdi mdi-24px mdi-play pr-1" />
<span>{{ $t('word.run') }}</span> <span>{{ t('word.run') }}</span>
</button> </button>
</div> </div>
<button <button
@ -53,7 +53,7 @@
@click="commitTab()" @click="commitTab()"
> >
<i class="mdi mdi-24px mdi-cube-send pr-1" /> <i class="mdi mdi-24px mdi-cube-send pr-1" />
<span>{{ $t('word.commit') }}</span> <span>{{ t('word.commit') }}</span>
</button> </button>
<button <button
v-if="!autocommit" v-if="!autocommit"
@ -62,7 +62,7 @@
@click="rollbackTab()" @click="rollbackTab()"
> >
<i class="mdi mdi-24px mdi-undo-variant pr-1" /> <i class="mdi mdi-24px mdi-undo-variant pr-1" />
<span>{{ $t('word.rollback') }}</span> <span>{{ t('word.rollback') }}</span>
</button> </button>
<button <button
class="btn btn-link btn-sm mr-0" class="btn btn-link btn-sm mr-0"
@ -71,7 +71,7 @@
@click="clear()" @click="clear()"
> >
<i class="mdi mdi-24px mdi-delete-sweep pr-1" /> <i class="mdi mdi-24px mdi-delete-sweep pr-1" />
<span>{{ $t('word.clear') }}</span> <span>{{ t('word.clear') }}</span>
</button> </button>
<div class="divider-vert py-3" /> <div class="divider-vert py-3" />
@ -83,7 +83,7 @@
@click="beautify()" @click="beautify()"
> >
<i class="mdi mdi-24px mdi-brush pr-1" /> <i class="mdi mdi-24px mdi-brush pr-1" />
<span>{{ $t('word.format') }}</span> <span>{{ t('word.format') }}</span>
</button> </button>
<button <button
class="btn btn-dark btn-sm" class="btn btn-dark btn-sm"
@ -92,7 +92,7 @@
@click="openHistoryModal()" @click="openHistoryModal()"
> >
<i class="mdi mdi-24px mdi-history pr-1" /> <i class="mdi mdi-24px mdi-history pr-1" />
<span>{{ $t('word.history') }}</span> <span>{{ t('word.history') }}</span>
</button> </button>
<div class="dropdown table-dropdown pr-2"> <div class="dropdown table-dropdown pr-2">
<button <button
@ -101,7 +101,7 @@
tabindex="0" tabindex="0"
> >
<i class="mdi mdi-24px mdi-file-export mr-1" /> <i class="mdi mdi-24px mdi-file-export mr-1" />
<span>{{ $t('word.export') }}</span> <span>{{ t('word.export') }}</span>
<i class="mdi mdi-24px mdi-menu-down" /> <i class="mdi mdi-24px mdi-menu-down" />
</button> </button>
<ul class="menu text-left"> <ul class="menu text-left">
@ -113,13 +113,13 @@
</li> </li>
</ul> </ul>
</div> </div>
<div class="input-group pr-2" :title="$t('message.commitMode')"> <div class="input-group pr-2" :title="t('message.commitMode')">
<i class="input-group-addon addon-sm mdi mdi-24px mdi-source-commit p-0" /> <i class="input-group-addon addon-sm mdi mdi-24px mdi-source-commit p-0" />
<BaseSelect <BaseSelect
v-model="autocommit" v-model="autocommit"
:options="[{value: true, label: $t('message.autoCommit')}, {value: false, label: $t('message.manualCommit')}]" :options="[{value: true, label: t('message.autoCommit')}, {value: false, label: t('message.manualCommit')}]"
:option-label="opt => opt.label" :option-label="(opt: any) => opt.label"
:option-track-by="opt => opt.value" :option-track-by="(opt: any) => opt.value"
class="form-select select-sm text-bold" class="form-select select-sm text-bold"
/> />
</div> </div>
@ -128,30 +128,30 @@
<div <div
v-if="results.length" v-if="results.length"
class="d-flex" class="d-flex"
:title="$t('message.queryDuration')" :title="t('message.queryDuration')"
> >
<i class="mdi mdi-timer-sand mdi-rotate-180 pr-1" /> <b>{{ durationsCount / 1000 }}s</b> <i class="mdi mdi-timer-sand mdi-rotate-180 pr-1" /> <b>{{ durationsCount / 1000 }}s</b>
</div> </div>
<div <div
v-if="resultsCount" v-if="resultsCount"
class="d-flex" class="d-flex"
:title="$t('word.results')" :title="t('word.results')"
> >
<i class="mdi mdi-equal pr-1" /> <b>{{ resultsCount.toLocaleString() }}</b> <i class="mdi mdi-equal pr-1" /> <b>{{ resultsCount.toLocaleString() }}</b>
</div> </div>
<div <div
v-if="hasAffected" v-if="hasAffected"
class="d-flex" class="d-flex"
:title="$t('message.affectedRows')" :title="t('message.affectedRows')"
> >
<i class="mdi mdi-target pr-1" /> <b>{{ affectedCount }}</b> <i class="mdi mdi-target pr-1" /> <b>{{ affectedCount }}</b>
</div> </div>
<div class="input-group" :title="$t('word.schema')"> <div class="input-group" :title="t('word.schema')">
<i class="input-group-addon addon-sm mdi mdi-24px mdi-database" /> <i class="input-group-addon addon-sm mdi mdi-24px mdi-database" />
<BaseSelect <BaseSelect
v-model="selectedSchema" v-model="selectedSchema"
:options="[{value: null, label: $t('message.noSchema')}, ...databaseSchemas.map(el => ({label: el, value: el}))]" :options="[{value: null, label: t('message.noSchema')}, ...databaseSchemas.map(el => ({label: el, value: el}))]"
class="form-select select-sm text-bold" class="form-select select-sm text-bold"
/> />
</div> </div>
@ -183,347 +183,331 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { storeToRefs } from 'pinia'; import { Component, computed, onBeforeUnmount, onMounted, Prop, ref, Ref, watch } from 'vue';
import { Ace } from 'ace-builds';
import { useI18n } from 'vue-i18n';
import { format } from 'sql-formatter'; import { format } from 'sql-formatter';
import { ConnectionParams } from 'common/interfaces/antares';
import { useHistoryStore } from '@/stores/history'; import { useHistoryStore } from '@/stores/history';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import Schema from '@/ipc-api/Schema'; import Schema from '@/ipc-api/Schema';
import QueryEditor from '@/components/QueryEditor'; import QueryEditor from '@/components/QueryEditor.vue';
import BaseLoader from '@/components/BaseLoader'; import BaseLoader from '@/components/BaseLoader.vue';
import WorkspaceTabQueryTable from '@/components/WorkspaceTabQueryTable'; import WorkspaceTabQueryTable from '@/components/WorkspaceTabQueryTable.vue';
import WorkspaceTabQueryEmptyState from '@/components/WorkspaceTabQueryEmptyState'; import WorkspaceTabQueryEmptyState from '@/components/WorkspaceTabQueryEmptyState.vue';
import ModalHistory from '@/components/ModalHistory'; import ModalHistory from '@/components/ModalHistory.vue';
import tableTabs from '@/mixins/tableTabs'; import { useResultTables } from '@/composables/useResultTables';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
export default { const { t } = useI18n();
name: 'WorkspaceTabQuery',
components: {
BaseLoader,
QueryEditor,
WorkspaceTabQueryTable,
WorkspaceTabQueryEmptyState,
ModalHistory,
BaseSelect
},
mixins: [tableTabs],
props: {
tabUid: String,
connection: Object,
tab: Object,
isSelected: Boolean
},
setup () {
const { getHistoryByWorkspace, saveHistory } = useHistoryStore();
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); const props = defineProps({
tabUid: String,
connection: Object as Prop<ConnectionParams>,
tab: Object,
isSelected: Boolean
});
const { const reloadTable = () => runQuery(lastQuery.value);
getWorkspace,
changeBreadcrumbs,
updateTabContent,
setUnsavedChanges
} = workspacesStore;
return { const {
getHistoryByWorkspace, queryTable,
saveHistory, isQuering,
addNotification, updateField,
selectedWorkspace, deleteSelected
getWorkspace, } = useResultTables(props.connection.uid, reloadTable);
changeBreadcrumbs,
updateTabContent,
setUnsavedChanges
};
},
data () {
return {
query: '',
lastQuery: '',
isQuering: false,
isCancelling: false,
showCancel: false,
autocommit: true,
results: [],
selectedSchema: null,
resultsCount: 0,
durationsCount: 0,
affectedCount: null,
editorHeight: 200,
isHistoryOpen: false,
debounceTimeout: null
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
breadcrumbsSchema () {
return this.workspace.breadcrumbs.schema || null;
},
databaseSchemas () {
return this.workspace.structure.reduce((acc, curr) => {
acc.push(curr.name);
return acc;
}, []);
},
isWorkspaceSelected () {
return this.workspace.uid === this.selectedWorkspace;
},
history () {
return this.getHistoryByWorkspace(this.connection.uid) || [];
},
hasResults () {
return this.results.length && this.results[0].rows;
},
hasAffected () {
return this.affectedCount || (!this.resultsCount && this.affectedCount !== null);
}
},
watch: {
query (val) {
clearTimeout(this.debounceTimeout);
this.debounceTimeout = setTimeout(() => { const { saveHistory } = useHistoryStore();
this.updateTabContent({ const { addNotification } = useNotificationsStore();
uid: this.connection.uid, const workspacesStore = useWorkspacesStore();
tab: this.tab.uid,
type: 'query',
schema: this.selectedSchema,
content: val
});
}, 200);
},
isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.selectedSchema, query: `Query #${this.tab.index}` });
setTimeout(() => {
if (this.$refs.queryEditor)
this.$refs.queryEditor.editor.focus();
}, 0);
}
},
selectedSchema () {
this.changeBreadcrumbs({ schema: this.selectedSchema, query: `Query #${this.tab.index}` });
}
},
created () {
this.query = this.tab.content;
this.selectedSchema = this.tab.schema || this.breadcrumbsSchema;
if (!this.databaseSchemas.includes(this.selectedSchema)) const {
this.selectedSchema = null; getWorkspace,
changeBreadcrumbs,
updateTabContent,
setUnsavedChanges
} = workspacesStore;
window.addEventListener('keydown', this.onKey); const queryEditor: Ref<Component & { editor: Ace.Editor; $el: HTMLElement }> = ref(null);
window.addEventListener('resize', this.onWindowResize); const queryAreaFooter: Ref<HTMLDivElement> = ref(null);
}, const resizer: Ref<HTMLDivElement> = ref(null);
mounted () { const query = ref('');
const resizer = this.$refs.resizer; const lastQuery = ref('');
const isCancelling = ref(false);
const showCancel = ref(false);
const autocommit = ref(true);
const results = ref([]);
const selectedSchema = ref(null);
const resultsCount = ref(0);
const durationsCount = ref(0);
const affectedCount = ref(null);
const editorHeight = ref(200);
const isHistoryOpen = ref(false);
const debounceTimeout = ref(null);
resizer.addEventListener('mousedown', e => { const workspace = computed(() => getWorkspace(props.connection.uid));
e.preventDefault(); const breadcrumbsSchema = computed(() => workspace.value.breadcrumbs.schema || null);
const databaseSchemas = computed(() => {
return workspace.value.structure.reduce((acc, curr) => {
acc.push(curr.name);
return acc;
}, []);
});
const hasResults = computed(() => results.value.length && results.value[0].rows);
const hasAffected = computed(() => affectedCount.value || (!resultsCount.value && affectedCount.value !== null));
window.addEventListener('mousemove', this.resize); watch(query, (val) => {
window.addEventListener('mouseup', this.stopResize); clearTimeout(debounceTimeout.value);
debounceTimeout.value = setTimeout(() => {
updateTabContent({
uid: props.connection.uid,
tab: props.tab.uid,
type: 'query',
schema: selectedSchema.value,
content: val
}); });
}, 200);
});
if (this.tab.autorun) watch(() => props.isSelected, (val) => {
this.runQuery(this.query); if (val) {
}, changeBreadcrumbs({ schema: selectedSchema.value, query: `Query #${props.tab.index}` });
beforeUnmount () { setTimeout(() => {
window.removeEventListener('resize', this.onWindowResize); if (queryEditor.value)
window.removeEventListener('keydown', this.onKey); queryEditor.value.editor.focus();
}, 0);
}
});
watch(selectedSchema, () => {
changeBreadcrumbs({ schema: selectedSchema.value, query: `Query #${props.tab.index}` });
});
const runQuery = async (query: string) => {
if (!query || isQuering.value) return;
isQuering.value = true;
clearTabData();
queryTable.value.resetSort();
try { // Query Data
const params = { const params = {
uid: this.connection.uid, uid: props.connection.uid,
tabUid: this.tab.uid schema: selectedSchema.value,
tabUid: props.tab.uid,
autocommit: autocommit.value,
query
}; };
Schema.destroyConnectionToCommit(params);
},
methods: {
async runQuery (query) {
if (!query || this.isQuering) return;
this.isQuering = true;
this.clearTabData();
this.$refs.queryTable.resetSort();
try { // Query Data const { status, response } = await Schema.rawQuery(params);
const params = {
uid: this.connection.uid,
schema: this.selectedSchema,
tabUid: this.tab.uid,
autocommit: this.autocommit,
query
};
const { status, response } = await Schema.rawQuery(params); if (status === 'success') {
results.value = Array.isArray(response) ? response : [response];
resultsCount.value = results.value.reduce((acc, curr) => acc + (curr.rows ? curr.rows.length : 0), 0);
durationsCount.value = results.value.reduce((acc, curr) => acc + curr.duration, 0);
affectedCount.value = results.value
.filter(result => result.report !== null)
.reduce((acc, curr) => {
if (acc === null) acc = 0;
return acc + (curr.report ? curr.report.affectedRows : 0);
}, null);
if (status === 'success') { saveHistory(params);
this.results = Array.isArray(response) ? response : [response]; if (!autocommit.value)
this.resultsCount = this.results.reduce((acc, curr) => acc + (curr.rows ? curr.rows.length : 0), 0); setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: true });
this.durationsCount = this.results.reduce((acc, curr) => acc + curr.duration, 0);
this.affectedCount = this.results
.filter(result => result.report !== null)
.reduce((acc, curr) => {
if (acc === null) acc = 0;
return acc + (curr.report ? curr.report.affectedRows : 0);
}, null);
this.saveHistory(params);
if (!this.autocommit)
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: true });
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false;
this.lastQuery = query;
},
async killTabQuery () {
if (this.isCancelling) return;
this.isCancelling = true;
try {
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
await Schema.killTabQuery(params);
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isCancelling = false;
},
setCancelButtonVisibility (val) {
if (this.workspace.customizations.cancelQueries)
this.showCancel = val;
},
reloadTable () {
this.runQuery(this.lastQuery);
},
clearTabData () {
this.results = [];
this.resultsCount = 0;
this.durationsCount = 0;
this.affectedCount = null;
},
resize (e) {
const el = this.$refs.queryEditor.$el;
const queryFooterHeight = this.$refs.queryAreaFooter.clientHeight;
const bottom = e.pageY || this.$refs.resizer.getBoundingClientRect().bottom;
const maxHeight = window.innerHeight - 100 - queryFooterHeight;
let editorHeight = bottom - el.getBoundingClientRect().top;
if (editorHeight > maxHeight) editorHeight = maxHeight;
if (editorHeight < 50) editorHeight = 50;
this.editorHeight = editorHeight;
},
onWindowResize (e) {
const el = this.$refs.queryEditor.$el;
const queryFooterHeight = this.$refs.queryAreaFooter.clientHeight;
const bottom = e.pageY || this.$refs.resizer.getBoundingClientRect().bottom;
const maxHeight = window.innerHeight - 100 - queryFooterHeight;
const editorHeight = bottom - el.getBoundingClientRect().top;
if (editorHeight > maxHeight)
this.editorHeight = maxHeight;
},
stopResize () {
window.removeEventListener('mousemove', this.resize);
if (this.$refs.queryTable && this.results.length)
this.$refs.queryTable.resizeResults();
if (this.$refs.queryEditor)
this.$refs.queryEditor.editor.resize();
},
beautify () {
if (this.$refs.queryEditor) {
let language = 'sql';
switch (this.workspace.client) {
case 'mysql':
language = 'mysql';
break;
case 'maria':
language = 'mariadb';
break;
case 'pg':
language = 'postgresql';
break;
}
const formattedQuery = format(this.query, {
language,
uppercase: true
});
this.$refs.queryEditor.editor.session.setValue(formattedQuery);
}
},
openHistoryModal () {
this.isHistoryOpen = true;
},
selectQuery (sql) {
if (this.$refs.queryEditor)
this.$refs.queryEditor.editor.session.setValue(sql);
this.isHistoryOpen = false;
},
clear () {
if (this.$refs.queryEditor)
this.$refs.queryEditor.editor.session.setValue('');
this.clearTabData();
},
downloadTable (format) {
this.$refs.queryTable.downloadTable(format, `${this.tab.type}-${this.tab.index}`);
},
async commitTab () {
this.isQuering = true;
try {
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
await Schema.commitTab(params);
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: false });
this.addNotification({ status: 'success', message: this.$t('message.actionSuccessful', { action: 'COMMIT' }) });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false;
},
async rollbackTab () {
this.isQuering = true;
try {
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
await Schema.rollbackTab(params);
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: false });
this.addNotification({ status: 'success', message: this.$t('message.actionSuccessful', { action: 'ROLLBACK' }) });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false;
} }
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
isQuering.value = false;
lastQuery.value = query;
};
const killTabQuery = async () => {
if (isCancelling.value) return;
isCancelling.value = true;
try {
const params = {
uid: props.connection.uid,
tabUid: props.tab.uid
};
await Schema.killTabQuery(params);
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
isCancelling.value = false;
};
const setCancelButtonVisibility = (val: boolean) => {
if (workspace.value.customizations.cancelQueries)
showCancel.value = val;
};
const clearTabData = () => {
results.value = [];
resultsCount.value = 0;
durationsCount.value = 0;
affectedCount.value = null;
};
const resize = (e: MouseEvent) => {
const el = queryEditor.value.$el;
const queryFooterHeight = queryAreaFooter.value.clientHeight;
const bottom = e.pageY || resizer.value.getBoundingClientRect().bottom;
const maxHeight = window.innerHeight - 100 - queryFooterHeight;
let localEditorHeight = bottom - el.getBoundingClientRect().top;
if (localEditorHeight > maxHeight) localEditorHeight = maxHeight;
if (localEditorHeight < 50) localEditorHeight = 50;
editorHeight.value = localEditorHeight;
};
const onWindowResize = (e: MouseEvent) => {
const el = queryEditor.value.$el;
const queryFooterHeight = queryAreaFooter.value.clientHeight;
const bottom = e.pageY || resizer.value.getBoundingClientRect().bottom;
const maxHeight = window.innerHeight - 100 - queryFooterHeight;
const localEditorHeight = bottom - el.getBoundingClientRect().top;
if (localEditorHeight > maxHeight)
editorHeight.value = maxHeight;
};
const stopResize = () => {
window.removeEventListener('mousemove', resize);
if (queryTable.value && results.value.length)
queryTable.value.resizeResults();
if (queryEditor.value)
queryEditor.value.editor.resize();
};
const beautify = () => {
if (queryEditor.value) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let language: any = 'sql';
switch (workspace.value.client) {
case 'mysql':
language = 'mysql';
break;
case 'maria':
language = 'mariadb';
break;
case 'pg':
language = 'postgresql';
break;
}
const formattedQuery = format(query.value, {
language,
uppercase: true
});
queryEditor.value.editor.session.setValue(formattedQuery);
} }
}; };
const openHistoryModal = () => {
isHistoryOpen.value = true;
};
const selectQuery = (sql: string) => {
if (queryEditor.value)
queryEditor.value.editor.session.setValue(sql);
isHistoryOpen.value = false;
};
const clear = () => {
if (queryEditor.value)
queryEditor.value.editor.session.setValue('');
clearTabData();
};
const downloadTable = (format: 'csv' | 'json') => {
queryTable.value.downloadTable(format, `${props.tab.type}-${props.tab.index}`);
};
const commitTab = async () => {
isQuering.value = true;
try {
const params = {
uid: props.connection.uid,
tabUid: props.tab.uid
};
await Schema.commitTab(params);
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: false });
addNotification({ status: 'success', message: t('message.actionSuccessful', { action: 'COMMIT' }) });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
isQuering.value = false;
};
const rollbackTab = async () => {
isQuering.value = true;
try {
const params = {
uid: props.connection.uid,
tabUid: props.tab.uid
};
await Schema.rollbackTab(params);
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: false });
addNotification({ status: 'success', message: t('message.actionSuccessful', { action: 'ROLLBACK' }) });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
isQuering.value = false;
};
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('keydown', onKey);
window.addEventListener('resize', onWindowResize);
onMounted(() => {
const localResizer = resizer.value;
localResizer.addEventListener('mousedown', (e: MouseEvent) => {
e.preventDefault();
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
});
if (props.tab.autorun)
runQuery(query.value);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', onWindowResize);
// window.removeEventListener('keydown', onKey);
const params = {
uid: props.connection.uid,
tabUid: props.tab.uid
};
Schema.destroyConnectionToCommit(params);
});
</script> </script>
<style lang="scss"> <style lang="scss">

View File

@ -3,25 +3,25 @@
<div class="columns"> <div class="columns">
<div class="column col-16 text-right"> <div class="column col-16 text-right">
<div class="mb-4"> <div class="mb-4">
{{ $t('message.runQuery') }} {{ t('message.runQuery') }}
</div> </div>
<div v-if="customizations.cancelQueries" class="mb-4"> <div v-if="customizations.cancelQueries" class="mb-4">
{{ $t('message.killQuery') }} {{ t('message.killQuery') }}
</div> </div>
<div class="mb-4"> <div class="mb-4">
{{ $t('word.format') }} {{ t('word.format') }}
</div> </div>
<div class="mb-4"> <div class="mb-4">
{{ $t('word.clear') }} {{ t('word.clear') }}
</div> </div>
<div class="mb-4"> <div class="mb-4">
{{ $t('word.history') }} {{ t('word.history') }}
</div> </div>
<div class="mb-4"> <div class="mb-4">
{{ $t('message.openNewTab') }} {{ t('message.openNewTab') }}
</div> </div>
<div class="mb-4"> <div class="mb-4">
{{ $t('message.closeTab') }} {{ t('message.closeTab') }}
</div> </div>
</div> </div>
<div class="column col-16"> <div class="column col-16">
@ -51,13 +51,14 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
export default { import { useI18n } from 'vue-i18n';
name: 'WorkspaceTabQueryEmptyState',
props: { const { t } = useI18n();
customizations: Object
} defineProps({
}; customizations: Object
});
</script> </script>
<style scoped> <style scoped>

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@
@close-context="closeContext" @close-context="closeContext"
> >
<div v-if="selectedRows.length === 1" class="context-element"> <div v-if="selectedRows.length === 1" class="context-element">
<span class="d-flex"><i class="mdi mdi-18px mdi-content-copy text-light pr-1" /> {{ $t('word.copy') }}</span> <span class="d-flex"><i class="mdi mdi-18px mdi-content-copy text-light pr-1" /> {{ t('word.copy') }}</span>
<i class="mdi mdi-18px mdi-chevron-right text-light pl-1" /> <i class="mdi mdi-18px mdi-chevron-right text-light pl-1" />
<div class="context-submenu"> <div class="context-submenu">
<div <div
@ -13,7 +13,7 @@
@click="copyCell" @click="copyCell"
> >
<span class="d-flex"> <span class="d-flex">
<i class="mdi mdi-18px mdi-numeric-0 mdi-rotate-90 text-light pr-1" /> {{ $tc('word.cell', 1) }} <i class="mdi mdi-18px mdi-numeric-0 mdi-rotate-90 text-light pr-1" /> {{ t('word.cell', 1) }}
</span> </span>
</div> </div>
<div <div
@ -22,7 +22,7 @@
@click="copyRow" @click="copyRow"
> >
<span class="d-flex"> <span class="d-flex">
<i class="mdi mdi-18px mdi-table-row text-light pr-1" /> {{ $tc('word.row', 1) }} <i class="mdi mdi-18px mdi-table-row text-light pr-1" /> {{ t('word.row', 1) }}
</span> </span>
</div> </div>
</div> </div>
@ -33,7 +33,7 @@
@click="setNull" @click="setNull"
> >
<span class="d-flex"> <span class="d-flex">
<i class="mdi mdi-18px mdi-null text-light pr-1" /> {{ $t('message.setNull') }} <i class="mdi mdi-18px mdi-null text-light pr-1" /> {{ t('message.setNull') }}
</span> </span>
</div> </div>
<div <div
@ -42,45 +42,46 @@
@click="showConfirmModal" @click="showConfirmModal"
> >
<span class="d-flex"> <span class="d-flex">
<i class="mdi mdi-18px mdi-delete text-light pr-1" /> {{ $tc('message.deleteRows', selectedRows.length) }} <i class="mdi mdi-18px mdi-delete text-light pr-1" /> {{ t('message.deleteRows', selectedRows.length) }}
</span> </span>
</div> </div>
</BaseContextMenu> </BaseContextMenu>
</template> </template>
<script> <script setup lang="ts">
import BaseContextMenu from '@/components/BaseContextMenu'; import BaseContextMenu from '@/components/BaseContextMenu.vue';
import { useI18n } from 'vue-i18n';
export default { const { t } = useI18n();
name: 'WorkspaceTabQueryTableContext',
components: { defineProps({
BaseContextMenu contextEvent: MouseEvent,
}, selectedRows: Array,
props: { selectedCell: Object
contextEvent: MouseEvent, });
selectedRows: Array,
selectedCell: Object const emit = defineEmits(['show-delete-modal', 'close-context', 'set-null', 'copy-cell', 'copy-row']);
},
emits: ['show-delete-modal', 'close-context', 'set-null', 'copy-cell', 'copy-row'], const showConfirmModal = () => {
methods: { emit('show-delete-modal');
showConfirmModal () { };
this.$emit('show-delete-modal');
}, const closeContext = () => {
closeContext () { emit('close-context');
this.$emit('close-context'); };
},
setNull () { const setNull = () => {
this.$emit('set-null'); emit('set-null');
this.closeContext(); closeContext();
}, };
copyCell () {
this.$emit('copy-cell'); const copyCell = () => {
this.closeContext(); emit('copy-cell');
}, closeContext();
copyRow () { };
this.$emit('copy-row');
this.closeContext(); const copyRow = () => {
} emit('copy-row');
} closeContext();
}; };
</script> </script>

View File

@ -19,7 +19,7 @@
class="cell-content" class="cell-content"
:class="`${isNull(col)} ${typeClass(fields[cKey].type)}`" :class="`${isNull(col)} ${typeClass(fields[cKey].type)}`"
@dblclick="editON(cKey)" @dblclick="editON(cKey)"
>{{ cutText(typeFormat(col, fields[cKey].type.toLowerCase(), fields[cKey].length)) }}</span> >{{ cutText(typeFormat(col, fields[cKey].type.toLowerCase(), fields[cKey].length) as string) }}</span>
<ForeignKeySelect <ForeignKeySelect
v-else-if="isForeignKey(cKey)" v-else-if="isForeignKey(cKey)"
v-model="editingContent" v-model="editingContent"
@ -68,14 +68,14 @@
</div> </div>
<ConfirmModal <ConfirmModal
v-if="isTextareaEditor" v-if="isTextareaEditor"
:confirm-text="$t('word.update')" :confirm-text="t('word.update')"
size="medium" size="medium"
@confirm="editOFF" @confirm="editOFF"
@hide="hideEditorModal" @hide="hideEditorModal"
> >
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-edit mr-1" /> <span class="cut-text">{{ $t('word.edit') }} "{{ editingField }}"</span> <i class="mdi mdi-24px mdi-playlist-edit mr-1" /> <span class="cut-text">{{ t('word.edit') }} "{{ editingField }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -90,7 +90,7 @@
<div class="editor-field-info p-vcentered"> <div class="editor-field-info p-vcentered">
<div class="d-flex p-vcentered"> <div class="d-flex p-vcentered">
<label for="editorMode" class="form-label mr-2"> <label for="editorMode" class="form-label mr-2">
<b>{{ $t('word.content') }}</b>: <b>{{ t('word.content') }}</b>:
</label> </label>
<BaseSelect <BaseSelect
id="editorMode" id="editorMode"
@ -104,10 +104,10 @@
<div class="d-flex"> <div class="d-flex">
<div class="p-vcentered"> <div class="p-vcentered">
<div class="mr-4"> <div class="mr-4">
<b>{{ $t('word.size') }}</b>: {{ editingContent ? editingContent.length : 0 }} <b>{{ t('word.size') }}</b>: {{ editingContent ? editingContent.length : 0 }}
</div> </div>
<div v-if="editingType"> <div v-if="editingType">
<b>{{ $t('word.type') }}</b>: {{ editingType.toUpperCase() }} <b>{{ t('word.type') }}</b>: {{ editingType.toUpperCase() }}
</div> </div>
</div> </div>
</div> </div>
@ -132,14 +132,14 @@
</ConfirmModal> </ConfirmModal>
<ConfirmModal <ConfirmModal
v-if="isBlobEditor" v-if="isBlobEditor"
:confirm-text="$t('word.update')" :confirm-text="t('word.update')"
@confirm="editOFF" @confirm="editOFF"
@hide="hideEditorModal" @hide="hideEditorModal"
> >
<template #header> <template #header>
<div class="d-flex"> <div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-edit mr-1" /> <i class="mdi mdi-24px mdi-playlist-edit mr-1" />
<span class="cut-text">{{ $t('word.edit') }} "{{ editingField }}"</span> <span class="cut-text">{{ t('word.edit') }} "{{ editingField }}"</span>
</div> </div>
</template> </template>
<template #body> <template #body>
@ -156,11 +156,11 @@
</div> </div>
<div class="editor-buttons mt-2"> <div class="editor-buttons mt-2">
<button class="btn btn-link btn-sm" @click="downloadFile"> <button class="btn btn-link btn-sm" @click="downloadFile">
<span>{{ $t('word.download') }}</span> <span>{{ t('word.download') }}</span>
<i class="mdi mdi-24px mdi-download ml-1" /> <i class="mdi mdi-24px mdi-download ml-1" />
</button> </button>
<button class="btn btn-link btn-sm" @click="prepareToDelete"> <button class="btn btn-link btn-sm" @click="prepareToDelete">
<span>{{ $t('word.delete') }}</span> <span>{{ t('word.delete') }}</span>
<i class="mdi mdi-24px mdi-delete-forever ml-1" /> <i class="mdi mdi-24px mdi-delete-forever ml-1" />
</button> </button>
</div> </div>
@ -168,19 +168,19 @@
</Transition> </Transition>
<div class="editor-field-info"> <div class="editor-field-info">
<div> <div>
<b>{{ $t('word.size') }}</b>: {{ formatBytes(editingContent.length) }}<br> <b>{{ t('word.size') }}</b>: {{ formatBytes(editingContent.length) }}<br>
<b>{{ $t('word.mimeType') }}</b>: {{ contentInfo.mime }} <b>{{ t('word.mimeType') }}</b>: {{ contentInfo.mime }}
</div> </div>
<div v-if="editingType"> <div v-if="editingType">
<b>{{ $t('word.type') }}</b>: {{ editingType.toUpperCase() }} <b>{{ t('word.type') }}</b>: {{ editingType.toUpperCase() }}
</div> </div>
</div> </div>
<div class="mt-3"> <div class="mt-3">
<label>{{ $t('message.uploadFile') }}</label> <label>{{ t('message.uploadFile') }}</label>
<input <input
class="form-input" class="form-input"
type="file" type="file"
@change="filesChange($event)" @change="filesChange($event as any)"
> >
</div> </div>
</div> </div>
@ -189,13 +189,15 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import moment from 'moment'; import { computed, onBeforeUnmount, Prop, ref, Ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import * as moment from 'moment';
import { ModelOperations } from '@vscode/vscode-languagedetection'; import { ModelOperations } from '@vscode/vscode-languagedetection';
import { mimeFromHex } from 'common/libs/mimeFromHex'; import { mimeFromHex } from 'common/libs/mimeFromHex';
import { formatBytes } from 'common/libs/formatBytes'; import { formatBytes } from 'common/libs/formatBytes';
import { bufferToBase64 } from 'common/libs/bufferToBase64'; import { bufferToBase64 } from 'common/libs/bufferToBase64';
import hexToBinary from 'common/libs/hexToBinary'; import hexToBinary, { HexChar } from 'common/libs/hexToBinary';
import { import {
TEXT, TEXT,
LONG_TEXT, LONG_TEXT,
@ -213,413 +215,423 @@ import {
SPATIAL, SPATIAL,
IS_MULTI_SPATIAL IS_MULTI_SPATIAL
} from 'common/fieldTypes'; } from 'common/fieldTypes';
import ConfirmModal from '@/components/BaseConfirmModal'; import ConfirmModal from '@/components/BaseConfirmModal.vue';
import TextEditor from '@/components/BaseTextEditor'; import TextEditor from '@/components/BaseTextEditor.vue';
import BaseMap from '@/components/BaseMap'; import BaseMap from '@/components/BaseMap.vue';
import ForeignKeySelect from '@/components/ForeignKeySelect'; import ForeignKeySelect from '@/components/ForeignKeySelect.vue';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { QueryForeign, TableField } from 'common/interfaces/antares';
export default { const { t } = useI18n();
name: 'WorkspaceTabQueryTableRow',
components: {
ConfirmModal,
TextEditor,
ForeignKeySelect,
BaseMap,
BaseSelect
},
props: {
row: Object,
fields: Object,
keyUsage: Array,
itemHeight: Number,
elementType: { type: String, default: 'table' },
selected: { type: Boolean, default: false },
selectedCell: { type: String, default: null }
},
emits: ['update-field', 'select-row', 'contextmenu', 'start-editing', 'stop-editing'],
data () {
return {
isInlineEditor: {},
isTextareaEditor: false,
isBlobEditor: false,
isMapModal: false,
isMultiSpatial: false,
willBeDeleted: false,
originalContent: null,
editingContent: null,
editingType: null,
editingField: null,
editingLength: null,
editorMode: 'text',
contentInfo: {
ext: '',
mime: '',
size: null
},
fileToUpload: null,
availableLanguages: [
{ name: 'TEXT', slug: 'text', id: 'text' },
{ name: 'HTML', slug: 'html', id: 'html' },
{ name: 'XML', slug: 'xml', id: 'xml' },
{ name: 'JSON', slug: 'json', id: 'json' },
{ name: 'SVG', slug: 'svg', id: 'svg' },
{ name: 'INI', slug: 'ini', id: 'ini' },
{ name: 'MARKDOWN', slug: 'markdown', id: 'md' },
{ name: 'YAML', slug: 'yaml', id: 'yaml' }
]
};
},
computed: {
inputProps () {
if ([...TEXT, ...LONG_TEXT].includes(this.editingType))
return { type: 'text', mask: false };
if ([...NUMBER, ...FLOAT].includes(this.editingType)) const props = defineProps({
return { type: 'number', mask: false }; row: Object,
fields: Object as Prop<{
[key: string]: TableField;
}>,
keyUsage: Array as Prop<QueryForeign[]>,
itemHeight: Number,
elementType: { type: String, default: 'table' },
selected: { type: Boolean, default: false },
selectedCell: { type: String, default: null }
});
if (TIME.includes(this.editingType)) { const emit = defineEmits(['update-field', 'select-row', 'contextmenu', 'start-editing', 'stop-editing']);
let timeMask = '##:##:##';
const precision = this.fields[this.editingField].length;
for (let i = 0; i < precision; i++) // eslint-disable-next-line @typescript-eslint/no-explicit-any
timeMask += i === 0 ? '.#' : '#'; const isInlineEditor: Ref<any> = ref({});
const isTextareaEditor = ref(false);
const isBlobEditor = ref(false);
const isMapModal = ref(false);
const isMultiSpatial = ref(false);
const willBeDeleted = ref(false);
const originalContent = ref(null);
const editingContent = ref(null);
const editingType = ref(null);
const editingField = ref(null);
const editingLength = ref(null);
const editorMode = ref('text');
const contentInfo = ref({
ext: '',
mime: '',
size: null
});
const fileToUpload = ref(null);
const availableLanguages = ref([
{ name: 'TEXT', slug: 'text', id: 'text' },
{ name: 'HTML', slug: 'html', id: 'html' },
{ name: 'XML', slug: 'xml', id: 'xml' },
{ name: 'JSON', slug: 'json', id: 'json' },
{ name: 'SVG', slug: 'svg', id: 'svg' },
{ name: 'INI', slug: 'ini', id: 'ini' },
{ name: 'MARKDOWN', slug: 'markdown', id: 'md' },
{ name: 'YAML', slug: 'yaml', id: 'yaml' }
]);
if (HAS_TIMEZONE.includes(this.editingType)) const inputProps = computed(() => {
timeMask += 'X##'; if ([...TEXT, ...LONG_TEXT].includes(editingType.value))
return { type: 'text', mask: false };
return { type: 'text', mask: timeMask }; if ([...NUMBER, ...FLOAT].includes(editingType.value))
} return { type: 'number', mask: false };
if (DATE.includes(this.editingType)) if (TIME.includes(editingType.value)) {
return { type: 'text', mask: '####-##-##' }; let timeMask = '##:##:##';
const precision = props.fields[editingField.value].length;
if (DATETIME.includes(this.editingType)) { for (let i = 0; i < precision; i++)
let datetimeMask = '####-##-## ##:##:##'; timeMask += i === 0 ? '.#' : '#';
const precision = this.fields[this.editingField].length;
for (let i = 0; i < precision; i++) if (HAS_TIMEZONE.includes(editingType.value))
datetimeMask += i === 0 ? '.#' : '#'; timeMask += 'X##';
if (HAS_TIMEZONE.includes(this.editingType)) return { type: 'text', mask: timeMask };
datetimeMask += 'X##'; }
return { type: 'text', mask: datetimeMask }; if (DATE.includes(editingType.value))
} return { type: 'text', mask: '####-##-##' };
if (BLOB.includes(this.editingType)) if (DATETIME.includes(editingType.value)) {
return { type: 'file', mask: false }; let datetimeMask = '####-##-## ##:##:##';
const precision = props.fields[editingField.value].length;
if (BOOLEAN.includes(this.editingType)) for (let i = 0; i < precision; i++)
return { type: 'boolean', mask: false }; datetimeMask += i === 0 ? '.#' : '#';
if (SPATIAL.includes(this.editingType)) if (HAS_TIMEZONE.includes(editingType.value))
return { type: 'map', mask: false }; datetimeMask += 'X##';
return { type: 'text', mask: false }; return { type: 'text', mask: datetimeMask };
}, }
isImage () {
return ['gif', 'jpg', 'png', 'bmp', 'ico', 'tif'].includes(this.contentInfo.ext);
},
foreignKeys () {
return this.keyUsage.map(key => key.field);
},
isEditable () {
if (this.elementType === 'view') return false;
if (this.fields) { if (BLOB.includes(editingType.value))
const nElements = Object.keys(this.fields).reduce((acc, curr) => { return { type: 'file', mask: false };
acc.add(this.fields[curr].table);
acc.add(this.fields[curr].schema);
return acc;
}, new Set([]));
if (nElements.size > 2) return false; if (BOOLEAN.includes(editingType.value))
return { type: 'boolean', mask: false };
return !!(this.fields[Object.keys(this.fields)[0]].schema && this.fields[Object.keys(this.fields)[0]].table); if (SPATIAL.includes(editingType.value))
} return { type: 'map', mask: false };
return false; return { type: 'text', mask: false };
}, });
isBaseSelectField () {
return this.isForeignKey(this.editingField) || this.inputProps.type === 'boolean' || this.enumArray;
},
enumArray () {
if (this.fields[this.editingField] && this.fields[this.editingField].enumValues)
return this.fields[this.editingField].enumValues.replaceAll('\'', '').split(',');
return false;
}
},
watch: {
fields () {
Object.keys(this.fields).forEach(field => {
this.isInlineEditor[field.name] = false;
});
},
isTextareaEditor (val) {
if (val) {
const modelOperations = new ModelOperations();
(async () => {
const detected = await modelOperations.runModel(this.editingContent);
const filteredLanguages = detected.filter(dLang =>
this.availableLanguages.some(aLang => aLang.id === dLang.languageId) &&
dLang.confidence > 0.1
);
if (filteredLanguages.length) const isImage = computed(() => {
this.editorMode = this.availableLanguages.find(lang => lang.id === filteredLanguages[0].languageId).slug; return ['gif', 'jpg', 'png', 'bmp', 'ico', 'tif'].includes(contentInfo.value.ext);
})(); });
}
},
selected (isSelected) {
if (isSelected)
window.addEventListener('keydown', this.onKey);
else { const foreignKeys = computed(() => {
this.editOFF(); return props.keyUsage.map(key => key.field);
window.removeEventListener('keydown', this.onKey); });
}
}
},
beforeUnmount () {
if (this.selected)
window.removeEventListener('keydown', this.onKey);
},
methods: {
isForeignKey (key) {
if (key.includes('.'))
key = key.split('.').pop();
return this.foreignKeys.includes(key); const isEditable = computed(() => {
}, if (props.elementType === 'view') return false;
isNull (value) {
return value === null ? ' is-null' : '';
},
typeClass (type) {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
},
bufferToBase64 (val) {
return bufferToBase64(val);
},
editON (field) {
if (!this.isEditable || this.editingType === 'none') return;
const content = this.row[field]; if (props.fields) {
const type = this.fields[field].type.toUpperCase(); const nElements = Object.keys(props.fields).reduce((acc, curr) => {
this.originalContent = this.typeFormat(content, type, this.fields[field].length); acc.add(props.fields[curr].table);
this.editingType = type; acc.add(props.fields[curr].schema);
this.editingField = field; return acc;
this.editingLength = this.fields[field].length; }, new Set([]));
if ([...LONG_TEXT, ...ARRAY, ...TEXT_SEARCH].includes(type)) { if (nElements.size > 2) return false;
this.isTextareaEditor = true;
this.editingContent = this.typeFormat(content, type);
this.$emit('start-editing', field);
return;
}
if (SPATIAL.includes(type)) { return !!(props.fields[Object.keys(props.fields)[0]].schema && props.fields[Object.keys(props.fields)[0]].table);
if (content) { }
this.isMultiSpatial = IS_MULTI_SPATIAL.includes(type);
this.isMapModal = true;
this.editingContent = this.typeFormat(content, type);
}
this.$emit('start-editing', field);
return;
}
if (BLOB.includes(type)) { return false;
this.isBlobEditor = true; });
this.editingContent = content || '';
this.fileToUpload = null;
this.willBeDeleted = false;
if (content !== null) { const isBaseSelectField = computed(() => {
const buff = Buffer.from(this.editingContent); return isForeignKey(editingField.value) || inputProps.value.type === 'boolean' || enumArray.value;
if (buff.length) { });
const hex = buff.toString('hex').substring(0, 8).toUpperCase();
const { ext, mime } = mimeFromHex(hex);
this.contentInfo = {
ext,
mime,
size: this.editingContent.length
};
}
}
this.$emit('start-editing', field);
return;
}
// Inline editable fields const enumArray = computed(() => {
this.editingContent = this.originalContent; if (props.fields[editingField.value] && props.fields[editingField.value].enumValues)
return props.fields[editingField.value].enumValues.replaceAll('\'', '').split(',');
return false;
});
const obj = { [field]: true }; const isForeignKey = (key: string) => {
this.isInlineEditor = { ...this.isInlineEditor, ...obj }; if (key) {
if (key.includes('.'))
key = key.split('.').pop();
this.$nextTick(() => { // Focus on input return foreignKeys.value.includes(key);
document.querySelector('.editable-field').focus();
});
this.$emit('start-editing', field);
},
editOFF () {
if (!this.editingField) return;
this.isInlineEditor[this.editingField] = false;
let content;
if (!BLOB.includes(this.editingType)) {
if ([...DATETIME, ...TIME].includes(this.editingType)) {
if (this.editingContent.substring(this.editingContent.length - 1) === '.')
this.editingContent = this.editingContent.slice(0, -1);
}
// If not changed
if (this.editingContent === this.typeFormat(this.originalContent, this.editingType, this.editingLength)) {
this.editingType = null;
this.editingField = null;
this.$emit('stop-editing', this.editingField);
return;
}
content = this.editingContent;
}
else { // Handle file upload
if (this.willBeDeleted) {
content = '';
this.willBeDeleted = false;
}
else {
if (!this.fileToUpload) return;
content = this.fileToUpload.file.path;
}
}
this.$emit('update-field', {
field: this.fields[this.editingField].name,
type: this.editingType,
content
});
this.$emit('stop-editing', this.editingField);
this.editingType = null;
this.editingField = null;
},
hideEditorModal () {
this.isTextareaEditor = false;
this.isBlobEditor = false;
this.isMapModal = false;
this.isMultiSpatial = false;
this.$emit('stop-editing', this.editingField);
},
downloadFile () {
const downloadLink = document.createElement('a');
downloadLink.href = `data:${this.contentInfo.mime};base64, ${bufferToBase64(this.editingContent)}`;
downloadLink.setAttribute('download', `${this.editingField}.${this.contentInfo.ext}`);
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
},
filesChange (event) {
const { files } = event.target;
if (!files.length) return;
this.fileToUpload = { name: files[0].name, file: files[0] };
this.willBeDeleted = false;
},
prepareToDelete () {
this.editingContent = '';
this.contentInfo = {
ext: '',
mime: '',
size: null
};
this.willBeDeleted = true;
},
selectRow (event, field) {
this.$emit('select-row', event, this.row, field);
},
getKeyUsage (keyName) {
if (keyName.includes('.'))
return this.keyUsage.find(key => key.field === keyName.split('.').pop());
return this.keyUsage.find(key => key.field === keyName);
},
openContext (event, payload) {
payload.field = this.fields[payload.orgField].name;// Ensures field name only
payload.isEditable = this.isEditable;
this.$emit('contextmenu', event, payload);
},
onKey (e) {
e.stopPropagation();
if (!this.editingField && e.key === 'Enter')
return this.editON(this.selectedCell);
if (this.editingField && e.key === 'Enter' && !this.isBaseSelectField)
return this.editOFF();
if (this.editingField && e.key === 'Escape') {
this.isInlineEditor[this.editingField] = false;
this.editingField = null;
this.$emit('stop-editing', this.editingField);
}
},
formatBytes,
cutText (val) {
if (typeof val !== 'string') return val;
return val.length > 128 ? `${val.substring(0, 128)}[...]` : val;
},
typeFormat (val, type, precision) {
if (!val) return val;
type = type.toUpperCase();
if (DATE.includes(type))
return moment(val).isValid() ? moment(val).format('YYYY-MM-DD') : val;
if (DATETIME.includes(type)) {
if (typeof val === 'string')
return val;
let datePrecision = '';
for (let i = 0; i < precision; i++)
datePrecision += i === 0 ? '.S' : 'S';
return moment(val).isValid() ? moment(val).format(`YYYY-MM-DD HH:mm:ss${datePrecision}`) : val;
}
if (BLOB.includes(type)) {
const buff = Buffer.from(val);
if (!buff.length) return '';
const hex = buff.toString('hex').substring(0, 8).toUpperCase();
return `${mimeFromHex(hex).mime} (${formatBytes(buff.length)})`;
}
if (BIT.includes(type)) {
if (typeof val === 'number') val = [val];
const hex = Buffer.from(val).toString('hex');
const bitString = hexToBinary(hex);
return parseInt(bitString).toString().padStart(precision, '0');
}
if (ARRAY.includes(type)) {
if (Array.isArray(val))
return JSON.stringify(val).replaceAll('[', '{').replaceAll(']', '}');
return val;
}
if (SPATIAL.includes(type))
return val;
return typeof val === 'object' ? JSON.stringify(val) : val;
}
} }
}; };
const isNull = (value: null | string | number) => {
return value === null ? ' is-null' : '';
};
const typeClass = (type: string) => {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
};
const editON = async (field: string) => {
if (!isEditable.value || editingType.value === 'none') return;
const content = props.row[field];
const type = props.fields[field].type.toUpperCase();
originalContent.value = typeFormat(content, type, props.fields[field].length);
editingType.value = type;
editingField.value = field;
editingLength.value = props.fields[field].length;
if ([...LONG_TEXT, ...ARRAY, ...TEXT_SEARCH].includes(type)) {
isTextareaEditor.value = true;
editingContent.value = typeFormat(content, type);
emit('start-editing', field);
return;
}
if (SPATIAL.includes(type)) {
if (content) {
isMultiSpatial.value = IS_MULTI_SPATIAL.includes(type);
isMapModal.value = true;
editingContent.value = typeFormat(content, type);
}
emit('start-editing', field);
return;
}
if (BLOB.includes(type)) {
isBlobEditor.value = true;
editingContent.value = content || '';
fileToUpload.value = null;
willBeDeleted.value = false;
if (content !== null) {
const buff = Buffer.from(editingContent.value);
if (buff.length) {
const hex = buff.toString('hex').substring(0, 8).toUpperCase();
const { ext, mime } = mimeFromHex(hex);
contentInfo.value = {
ext,
mime,
size: editingContent.value.length
};
}
}
emit('start-editing', field);
return;
}
// Inline editable fields
editingContent.value = originalContent.value;
const obj = { [field]: true };
isInlineEditor.value = { ...isInlineEditor.value, ...obj };
nextTick(() => {
document.querySelector<HTMLInputElement>('.editable-field').focus();
});
emit('start-editing', field);
};
const editOFF = () => {
if (!editingField.value) return;
isInlineEditor.value[editingField.value] = false;
let content;
if (!BLOB.includes(editingType.value)) {
if ([...DATETIME, ...TIME].includes(editingType.value)) {
if (editingContent.value.substring(editingContent.value.length - 1) === '.')
editingContent.value = editingContent.value.slice(0, -1);
}
// If not changed
if (editingContent.value === typeFormat(originalContent.value, editingType.value, editingLength.value)) {
editingType.value = null;
editingField.value = null;
emit('stop-editing', editingField.value);
return;
}
content = editingContent.value;
}
else { // Handle file upload
if (willBeDeleted.value) {
content = '';
willBeDeleted.value = false;
}
else {
if (!fileToUpload.value) return;
content = fileToUpload.value.file.path;
}
}
emit('update-field', {
field: props.fields[editingField.value].name,
type: editingType.value,
content
});
emit('stop-editing', editingField.value);
editingType.value = null;
editingField.value = null;
};
const hideEditorModal = () => {
isTextareaEditor.value = false;
isBlobEditor.value = false;
isMapModal.value = false;
isMultiSpatial.value = false;
emit('stop-editing', editingField.value);
};
const downloadFile = () => {
const downloadLink = document.createElement('a');
downloadLink.href = `data:${contentInfo.value.mime};base64, ${bufferToBase64(editingContent.value)}`;
downloadLink.setAttribute('download', `${editingField.value}.${contentInfo.value.ext}`);
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
};
const filesChange = (event: Event & {target: {files: {name: string}[]}}) => {
const { files } = event.target;
if (!files.length) return;
fileToUpload.value = { name: files[0].name, file: files[0] };
willBeDeleted.value = false;
};
const prepareToDelete = () => {
editingContent.value = '';
contentInfo.value = {
ext: '',
mime: '',
size: null
};
willBeDeleted.value = true;
};
const selectRow = (event: Event, field: string) => {
emit('select-row', event, props.row, field);
};
const getKeyUsage = (keyName: string) => {
if (keyName.includes('.'))
return props.keyUsage.find(key => key.field === keyName.split('.').pop());
return props.keyUsage.find(key => key.field === keyName);
};
const openContext = (event: MouseEvent, payload: { id: string; field?: string; orgField: string; isEditable?: boolean }) => {
payload.field = props.fields[payload.orgField].name;// Ensures field name only
payload.isEditable = isEditable.value;
emit('contextmenu', event, payload);
};
const onKey = (e: KeyboardEvent) => {
e.stopPropagation();
if (!editingField.value && e.key === 'Enter')
return editON(props.selectedCell);
if (editingField.value && e.key === 'Enter' && !isBaseSelectField.value)
return editOFF();
if (editingField.value && e.key === 'Escape') {
isInlineEditor.value[editingField.value] = false;
editingField.value = null;
emit('stop-editing', editingField.value);
}
};
const cutText = (val: string) => {
if (typeof val !== 'string') return val;
return val.length > 128 ? `${val.substring(0, 128)}[...]` : val;
};
const typeFormat = (val: string | number | Date | number[], type: string, precision?: number | false) => {
if (!val) return val;
type = type.toUpperCase();
if (DATE.includes(type))
return moment(val).isValid() ? moment(val).format('YYYY-MM-DD') : val;
if (DATETIME.includes(type)) {
if (typeof val === 'string')
return val;
let datePrecision = '';
for (let i = 0; i < precision; i++)
datePrecision += i === 0 ? '.S' : 'S';
return moment(val).isValid() ? moment(val).format(`YYYY-MM-DD HH:mm:ss${datePrecision}`) : val;
}
if (BLOB.includes(type)) {
const buff = Buffer.from(val as string);
if (!buff.length) return '';
const hex = buff.toString('hex').substring(0, 8).toUpperCase();
return `${mimeFromHex(hex).mime} (${formatBytes(buff.length)})`;
}
if (BIT.includes(type)) {
if (typeof val === 'number') val = [val] as number[];
const hex = Buffer.from(val as number[]).toString('hex') as unknown as HexChar[];
const bitString = hexToBinary(hex);
return parseInt(bitString).toString().padStart(Number(precision), '0');
}
if (ARRAY.includes(type)) {
if (Array.isArray(val))
return JSON.stringify(val).replaceAll('[', '{').replaceAll(']', '}');
return val;
}
if (SPATIAL.includes(type))
return val;
return typeof val === 'object' ? JSON.stringify(val) : val;
};
watch(() => props.fields, () => {
Object.keys(props.fields).forEach(field => {
isInlineEditor.value[field] = false;
});
});
watch(isTextareaEditor, (val) => {
if (val) {
const modelOperations = new ModelOperations();
(async () => {
const detected = await modelOperations.runModel(editingContent.value);
const filteredLanguages = detected.filter(dLang =>
availableLanguages.value.some(aLang => aLang.id === dLang.languageId) &&
dLang.confidence > 0.1
);
if (filteredLanguages.length)
editorMode.value = availableLanguages.value.find(lang => lang.id === filteredLanguages[0].languageId).slug;
})();
}
});
watch(() => props.selected, (isSelected) => {
if (isSelected)
window.addEventListener('keydown', onKey);
else {
editOFF();
window.removeEventListener('keydown', onKey);
}
});
onBeforeUnmount(() => {
if (props.selected)
window.removeEventListener('keydown', onKey);
});
</script> </script>
<style lang="scss"> <style lang="scss">

View File

@ -8,7 +8,7 @@
<button <button
class="btn btn-dark btn-sm mr-0 pr-1" class="btn btn-dark btn-sm mr-0 pr-1"
:class="{'loading':isQuering}" :class="{'loading':isQuering}"
:title="`${$t('word.refresh')} (F5)`" :title="`${t('word.refresh')} (F5)`"
@click="reloadTable" @click="reloadTable"
> >
<i v-if="!+autorefreshTimer" class="mdi mdi-24px mdi-refresh mr-1" /> <i v-if="!+autorefreshTimer" class="mdi mdi-24px mdi-refresh mr-1" />
@ -18,7 +18,7 @@
<i class="mdi mdi-24px mdi-menu-down" /> <i class="mdi mdi-24px mdi-menu-down" />
</div> </div>
<div class="menu px-3"> <div class="menu px-3">
<span>{{ $t('word.autoRefresh') }}: <b>{{ +autorefreshTimer ? `${autorefreshTimer}s` : 'OFF' }}</b></span> <span>{{ t('word.autoRefresh') }}: <b>{{ +autorefreshTimer ? `${autorefreshTimer}s` : 'OFF' }}</b></span>
<input <input
v-model="autorefreshTimer" v-model="autorefreshTimer"
class="slider no-border" class="slider no-border"
@ -46,7 +46,7 @@
{{ page }} {{ page }}
</div> </div>
<div class="menu px-3"> <div class="menu px-3">
<span>{{ $t('message.pageNumber') }}</span> <span>{{ t('message.pageNumber') }}</span>
<input <input
ref="pageSelect" ref="pageSelect"
v-model="pageProxy" v-model="pageProxy"
@ -72,7 +72,7 @@
<button <button
class="btn btn-sm" class="btn btn-sm"
:title="`${$t('word.filter')} (CTRL+F)`" :title="`${t('word.filter')} (CTRL+F)`"
:class="{'btn-primary': isSearch, 'btn-dark': !isSearch}" :class="{'btn-primary': isSearch, 'btn-dark': !isSearch}"
@click="isSearch = !isSearch" @click="isSearch = !isSearch"
> >
@ -95,7 +95,7 @@
tabindex="0" tabindex="0"
> >
<i class="mdi mdi-24px mdi-file-export mr-1" /> <i class="mdi mdi-24px mdi-file-export mr-1" />
<span>{{ $t('word.export') }}</span> <span>{{ t('word.export') }}</span>
<i class="mdi mdi-24px mdi-menu-down" /> <i class="mdi mdi-24px mdi-menu-down" />
</button> </button>
<ul class="menu text-left"> <ul class="menu text-left">
@ -112,22 +112,22 @@
<div <div
v-if="results.length" v-if="results.length"
class="d-flex" class="d-flex"
:title="$t('message.queryDuration')" :title="t('message.queryDuration')"
> >
<i class="mdi mdi-timer-sand mdi-rotate-180 pr-1" /> <b>{{ results[0].duration / 1000 }}s</b> <i class="mdi mdi-timer-sand mdi-rotate-180 pr-1" /> <b>{{ results[0].duration / 1000 }}s</b>
</div> </div>
<div v-if="results.length && results[0].rows"> <div v-if="results.length && results[0].rows">
{{ $t('word.results') }}: <b>{{ localeString(results[0].rows.length) }}</b> {{ t('word.results') }}: <b>{{ localeString(results[0].rows.length) }}</b>
</div> </div>
<div v-if="hasApproximately || (page > 1 && approximateCount)"> <div v-if="hasApproximately || (page > 1 && approximateCount)">
{{ $t('word.total') }}: <b {{ t('word.total') }}: <b
:title="!customizations.tableRealCount ? $t('word.approximately') : ''" :title="!customizations.tableRealCount ? t('word.approximately') : ''"
> >
<span v-if="!customizations.tableRealCount"></span> <span v-if="!customizations.tableRealCount"></span>
{{ localeString(approximateCount) }} {{ localeString(approximateCount) }}
</b> </b>
</div> </div>
<div class="d-flex" :title="$t('word.schema')"> <div class="d-flex" :title="t('word.schema')">
<i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b> <i class="mdi mdi-18px mdi-database mr-1" /><b>{{ schema }}</b>
</div> </div>
</div> </div>
@ -167,291 +167,288 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { computed, onBeforeUnmount, Prop, ref, Ref, watch } from 'vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import Tables from '@/ipc-api/Tables'; import Tables from '@/ipc-api/Tables';
import { useResultTables } from '@/composables/useResultTables';
import { useNotificationsStore } from '@/stores/notifications'; import { useNotificationsStore } from '@/stores/notifications';
import { useSettingsStore } from '@/stores/settings'; import { useSettingsStore } from '@/stores/settings';
import { useWorkspacesStore } from '@/stores/workspaces'; import { useWorkspacesStore } from '@/stores/workspaces';
import BaseLoader from '@/components/BaseLoader'; import BaseLoader from '@/components/BaseLoader.vue';
import WorkspaceTabQueryTable from '@/components/WorkspaceTabQueryTable'; import WorkspaceTabQueryTable from '@/components/WorkspaceTabQueryTable.vue';
import WorkspaceTabTableFilters from '@/components/WorkspaceTabTableFilters'; import WorkspaceTabTableFilters from '@/components/WorkspaceTabTableFilters.vue';
import ModalFakerRows from '@/components/ModalFakerRows'; import ModalFakerRows from '@/components/ModalFakerRows.vue';
import tableTabs from '@/mixins/tableTabs'; import { ConnectionParams } from 'common/interfaces/antares';
import { TableFilterClausole } from 'common/interfaces/tableApis';
export default { const { t } = useI18n();
name: 'WorkspaceTabTable',
components: {
BaseLoader,
WorkspaceTabQueryTable,
WorkspaceTabTableFilters,
ModalFakerRows
},
mixins: [tableTabs],
props: {
connection: Object,
isSelected: Boolean,
table: String,
schema: String,
elementType: String
},
setup () {
const { addNotification } = useNotificationsStore();
const settingsStore = useSettingsStore();
const workspacesStore = useWorkspacesStore();
const { dataTabLimit: limit } = storeToRefs(settingsStore); const props = defineProps({
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore); connection: Object as Prop<ConnectionParams>,
isSelected: Boolean,
table: String,
schema: String,
elementType: String
});
const { changeBreadcrumbs, getWorkspace } = workspacesStore; const reloadTable = () => getTableData();
return { const {
addNotification, queryTable,
limit, isQuering,
selectedWorkspace, updateField,
changeBreadcrumbs, deleteSelected
getWorkspace } = useResultTables(props.connection.uid, reloadTable);
};
},
data () {
return {
tabUid: 'data', // ???
isQuering: false,
isPageMenu: false,
isSearch: false,
results: [],
lastTable: null,
isFakerModal: false,
autorefreshTimer: 0,
refreshInterval: null,
sortParams: {},
filters: [],
page: 1,
pageProxy: 1,
approximateCount: 0
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
customizations () {
return this.workspace.customizations;
},
isTable () {
return !!this.workspace.breadcrumbs.table;
},
fields () {
return this.results.length ? this.results[0].fields : [];
},
keyUsage () {
return this.results.length ? this.results[0].keys : [];
},
tableInfo () {
try {
return this.workspace.structure.find(db => db.name === this.schema).tables.find(table => table.name === this.table);
}
catch (err) {
return { rows: 0 };
}
},
hasApproximately () {
return this.results.length &&
this.results[0].rows &&
this.results[0].rows.length === this.limit &&
this.results[0].rows.length < this.approximateCount;
}
},
watch: {
schema () {
if (this.isSelected) {
this.page = 1;
this.approximateCount = 0;
this.sortParams = {};
this.getTableData();
this.lastTable = this.table;
this.$refs.queryTable.resetSort();
}
},
table () {
if (this.isSelected) {
this.page = 1;
this.approximateCount = 0;
this.sortParams = {};
this.getTableData();
this.lastTable = this.table;
this.$refs.queryTable.resetSort();
}
},
page (val, oldVal) {
if (val && val > 0 && val !== oldVal) {
this.pageProxy = this.page;
this.getTableData();
}
},
isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, [this.elementType]: this.table });
if (this.lastTable !== this.table) const { addNotification } = useNotificationsStore();
this.getTableData(); const settingsStore = useSettingsStore();
} const workspacesStore = useWorkspacesStore();
},
isSearch (val) {
if (this.filters.length > 0 && !val) {
this.filters = [];
this.getTableData();
}
this.resizeScroller();
}
},
created () {
this.getTableData();
window.addEventListener('keydown', this.onKey);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
clearInterval(this.refreshInterval);
},
methods: {
async getTableData () {
if (!this.table || !this.isSelected) return;
this.isQuering = true;
// if table changes clear cached values const { dataTabLimit: limit } = storeToRefs(settingsStore);
if (this.lastTable !== this.table)
this.results = [];
this.lastTable = this.table; const { changeBreadcrumbs, getWorkspace } = workspacesStore;
const params = { const pageSelect: Ref<HTMLInputElement> = ref(null);
uid: this.connection.uid, const tabUid = ref('data');
schema: this.schema, const isPageMenu = ref(false);
table: this.table, const isSearch = ref(false);
limit: this.limit, const results = ref([]);
page: this.page, const lastTable = ref(null);
sortParams: { ...this.sortParams }, const isFakerModal = ref(false);
where: [...this.filters] || [] const autorefreshTimer = ref(0);
}; const refreshInterval = ref(null);
const sortParams = ref({} as { field: string; dir: 'asc' | 'desc'});
const filters = ref([]);
const page = ref(1);
const pageProxy = ref(1);
const approximateCount = ref(0);
try { // Table data const workspace = computed(() => {
const { status, response } = await Tables.getTableData(params); return getWorkspace(props.connection.uid);
});
if (status === 'success') const customizations = computed(() => {
this.results = [response]; return workspace.value.customizations;
else });
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
if (this.results.length && this.results[0].rows.length === this.limit) { const isTable = computed(() => {
try { // Table approximate count return !!workspace.value.breadcrumbs.table;
const { status, response } = await Tables.getTableApproximateCount(params); });
if (status === 'success') const fields = computed(() => {
this.approximateCount = response; return results.value.length ? results.value[0].fields : [];
else });
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
}
this.isQuering = false; const keyUsage = computed(() => {
}, return results.value.length ? results.value[0].keys : [];
getTable () { });
return this.table;
},
reloadTable () {
this.getTableData();
},
hardSort (sortParams) {
this.sortParams = sortParams;
this.getTableData();
},
openPageMenu () {
if (this.isQuering || (this.results.length && this.results[0].rows.length < this.limit && this.page === 1)) return;
this.isPageMenu = true; const getTableData = async () => {
if (this.isPageMenu) if (!props.table || !props.isSelected) return;
setTimeout(() => this.$refs.pageSelect.focus(), 20); isQuering.value = true;
},
setPageNumber () {
this.isPageMenu = false;
if (this.pageProxy > 0) // if table changes clear cached values
this.page = this.pageProxy; if (lastTable.value !== props.table)
results.value = [];
lastTable.value = props.table;
const params = {
uid: props.connection.uid,
schema: props.schema,
table: props.table,
limit: limit.value,
page: page.value,
sortParams: { ...sortParams.value },
where: [...filters.value] || []
};
try { // Table data
const { status, response } = await Tables.getTableData(params);
if (status === 'success')
results.value = [response];
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
if (results.value.length && results.value[0].rows.length === limit.value) {
try { // Table approximate count
const { status, response } = await Tables.getTableApproximateCount(params);
if (status === 'success')
approximateCount.value = response;
else else
this.pageProxy = this.page; addNotification({ status: 'error', message: response as unknown as string });
}, }
pageChange (direction) { catch (err) {
if (this.isQuering) return; addNotification({ status: 'error', message: err.stack });
}
}
if (direction === 'next' && (this.results.length && this.results[0].rows.length === this.limit)) { isQuering.value = false;
if (!this.page) };
this.page = 2;
else
this.page++;
}
else if (direction === 'prev' && this.page > 1)
this.page--;
},
showFakerModal () {
if (this.isQuering) return;
this.isFakerModal = true;
},
hideFakerModal () {
this.isFakerModal = false;
},
onKey (e) {
if (this.isSelected) {
e.stopPropagation();
if (e.key === 'F5')
this.reloadTable();
if (e.ctrlKey || e.metaKey) { const hardSort = (params: { field: string; dir: 'asc' | 'desc'}) => {
if (e.key === 'ArrowRight') sortParams.value = params;
this.pageChange('next'); getTableData();
if (e.key === 'ArrowLeft') };
this.pageChange('prev');
if (e.keyCode === 70) // f
this.isSearch = !this.isSearch;
}
}
},
setRefreshInterval () {
if (this.refreshInterval)
clearInterval(this.refreshInterval);
if (+this.autorefreshTimer) { const openPageMenu = () => {
this.refreshInterval = setInterval(() => { if (isQuering.value || (results.value.length && results.value[0].rows.length < limit.value && page.value === 1)) return;
if (!this.isQuering)
this.reloadTable(); isPageMenu.value = true;
}, this.autorefreshTimer * 1000); if (isPageMenu.value)
} setTimeout(() => pageSelect.value.focus(), 20);
}, };
downloadTable (format) {
this.$refs.queryTable.downloadTable(format, this.table); const setPageNumber = () => {
}, isPageMenu.value = false;
onFilterChange (clausoles) {
this.resizeScroller(); if (pageProxy.value > 0)
if (clausoles.length === 0) page.value = pageProxy.value;
this.isSearch = false; else
}, pageProxy.value = page.value;
resizeScroller () { };
setTimeout(() => this.$refs.queryTable.refreshScroller(), 1);
}, const pageChange = (direction: 'prev' | 'next') => {
updateFilters (clausoles) { if (isQuering.value) return;
this.filters = clausoles;
this.getTableData(); if (direction === 'next' && (results.value.length && results.value[0].rows.length === limit.value)) {
}, if (!page.value)
localeString (val) { page.value = 2;
if (val !== null) else
return val.toLocaleString(); page.value++;
}
else if (direction === 'prev' && page.value > 1)
page.value--;
};
const showFakerModal = () => {
if (isQuering.value) return;
isFakerModal.value = true;
};
const hideFakerModal = () => {
isFakerModal.value = false;
};
const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
e.stopPropagation();
if (e.key === 'F5')
reloadTable();
if (e.ctrlKey || e.metaKey) {
if (e.key === 'ArrowRight')
pageChange('next');
if (e.key === 'ArrowLeft')
pageChange('prev');
if (e.key === 'f') // f
isSearch.value = !isSearch.value;
} }
} }
}; };
const setRefreshInterval = () => {
if (refreshInterval.value)
clearInterval(refreshInterval.value);
if (+autorefreshTimer.value) {
refreshInterval.value = setInterval(() => {
if (!isQuering.value)
reloadTable();
}, autorefreshTimer.value * 1000);
}
};
const downloadTable = (format: 'csv' | 'json') => {
queryTable.value.downloadTable(format, props.table);
};
const onFilterChange = (clausoles: TableFilterClausole[]) => {
resizeScroller();
if (clausoles.length === 0)
isSearch.value = false;
};
const resizeScroller = () => {
setTimeout(() => queryTable.value.refreshScroller(), 1);
};
const updateFilters = (clausoles: TableFilterClausole[]) => {
filters.value = clausoles;
getTableData();
};
const localeString = (val: number | null) => {
if (val !== null)
return val.toLocaleString();
};
const hasApproximately = computed(() => {
return results.value.length &&
results.value[0].rows &&
results.value[0].rows.length === limit.value &&
results.value[0].rows.length < approximateCount.value;
});
watch(() => props.schema, () => {
if (props.isSelected) {
page.value = 1;
approximateCount.value = 0;
sortParams.value = {} as { field: string; dir: 'asc' | 'desc'};
getTableData();
lastTable.value = props.table;
queryTable.value.resetSort();
}
});
watch(() => props.table, () => {
if (props.isSelected) {
page.value = 1;
approximateCount.value = 0;
sortParams.value = {} as { field: string; dir: 'asc' | 'desc'};
getTableData();
lastTable.value = props.table;
queryTable.value.resetSort();
}
});
watch(page, (val, oldVal) => {
if (val && val > 0 && val !== oldVal) {
pageProxy.value = page.value;
getTableData();
}
});
watch(() => props.isSelected, (val) => {
if (val) {
changeBreadcrumbs({ schema: props.schema, [props.elementType]: props.table });
if (lastTable.value !== props.table)
getTableData();
}
});
watch(isSearch, (val) => {
if (filters.value.length > 0 && !val) {
filters.value = [];
getTableData();
}
resizeScroller();
});
getTableData();
window.addEventListener('keydown', onKey);
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
clearInterval(refreshInterval.value);
});
</script> </script>

View File

@ -64,91 +64,85 @@
</form> </form>
</template> </template>
<script> <script setup lang="ts">
import { computed, Prop, ref } from 'vue';
import { ClientCode, TableField } from 'common/interfaces/antares';
import customizations from 'common/customizations'; import customizations from 'common/customizations';
import { NUMBER, FLOAT } from 'common/fieldTypes'; import { NUMBER, FLOAT } from 'common/fieldTypes';
import BaseSelect from '@/components/BaseSelect.vue'; import BaseSelect from '@/components/BaseSelect.vue';
import { TableFilterClausole } from 'common/interfaces/tableApis';
export default { const props = defineProps({
components: { fields: Array as Prop<TableField[]>,
BaseSelect connClient: String as Prop<ClientCode>
}, });
props: {
fields: Array,
connClient: String
},
emits: ['filter-change', 'filter'],
data () {
return {
rows: [],
operators: [
'=', '!=', '>', '<', '>=', '<=', 'IN', 'NOT IN', 'LIKE', 'BETWEEN', 'IS NULL', 'IS NOT NULL'
]
};
},
computed: {
customizations () {
return customizations[this.connClient];
}
},
created () {
this.addRow();
},
methods: {
addRow () {
this.rows.push({ active: true, field: this.fields[0].name, op: '=', value: '', value2: '' });
this.$emit('filter-change', this.rows);
},
removeRow (i) {
this.rows = this.rows.filter((_, idx) => idx !== i);
this.$emit('filter-change', this.rows);
},
doFilter () {
const clausoles = this.rows.filter(el => el.active).map(el => this.createClausole(el));
this.$emit('filter', clausoles);
},
createClausole (filter) {
const field = this.fields.find(field => field.name === filter.field);
const isNumeric = [...NUMBER, ...FLOAT].includes(field.type);
const { elementsWrapper: ew, stringsWrapper: sw } = this.customizations;
let value;
switch (filter.op) { const emit = defineEmits(['filter-change', 'filter']);
case '=':
case '!=':
value = isNumeric ? filter.value : `${sw}${filter.value}${sw}`;
break;
case 'BETWEEN':
value = isNumeric ? filter.value : `${sw}${filter.value}${sw}`;
value += ' AND ';
value += isNumeric ? filter.value2 : `${sw}${filter.value2}${sw}`;
break;
case 'IN':
case 'NOT IN':
value = filter.value.split(',').map(val => {
val = val.trim();
return isNumeric ? val : `${sw}${val}${sw}`;
}).join(',');
value = `(${filter.value})`;
break;
case 'IS NULL':
case 'IS NOT NULL':
value = '';
break;
case 'LIKE':
value = `${sw}%${filter.value}%${sw}`;
break;
default:
value = `${sw}${filter.value}${sw}`;
}
if (isNumeric && !value.length && !['IS NULL', 'IS NOT NULL'].includes(filter.op)) const rows = ref([]);
value = `${sw}${sw}`; const operators = ref([
'=', '!=', '>', '<', '>=', '<=', 'IN', 'NOT IN', 'LIKE', 'BETWEEN', 'IS NULL', 'IS NOT NULL'
]);
return `${ew}${filter.field}${ew} ${filter.op} ${value}`; const clientCustomizations = computed(() => customizations[props.connClient]);
}
} const addRow = () => {
rows.value.push({ active: true, field: props.fields[0].name, op: '=', value: '', value2: '' });
emit('filter-change', rows.value);
}; };
const removeRow = (i: number) => {
rows.value = rows.value.filter((_, idx) => idx !== i);
emit('filter-change', rows.value);
};
const doFilter = () => {
const clausoles = rows.value.filter(el => el.active).map(el => createClausole(el));
emit('filter', clausoles);
};
const createClausole = (filter: TableFilterClausole) => {
const field = props.fields.find(field => field.name === filter.field);
const isNumeric = [...NUMBER, ...FLOAT].includes(field.type);
const { elementsWrapper: ew, stringsWrapper: sw } = clientCustomizations.value;
let value;
switch (filter.op) {
case '=':
case '!=':
value = isNumeric ? filter.value : `${sw}${filter.value}${sw}`;
break;
case 'BETWEEN':
value = isNumeric ? filter.value : `${sw}${filter.value}${sw}`;
value += ' AND ';
value += isNumeric ? filter.value2 : `${sw}${filter.value2}${sw}`;
break;
case 'IN':
case 'NOT IN':
value = filter.value.split(',').map(val => {
val = val.trim();
return isNumeric ? val : `${sw}${val}${sw}`;
}).join(',');
value = `(${filter.value})`;
break;
case 'IS NULL':
case 'IS NOT NULL':
value = '';
break;
case 'LIKE':
value = `${sw}%${filter.value}%${sw}`;
break;
default:
value = `${sw}${filter.value}${sw}`;
}
if (isNumeric && !value.length && !['IS NULL', 'IS NOT NULL'].includes(filter.op))
value = `${sw}${sw}`;
return `${ew}${filter.field}${ew} ${filter.op} ${value}`;
};
addRow();
</script> </script>
<style lang="scss"> <style lang="scss">

View File

@ -1,12 +1,20 @@
// TODO: unfinished
import Tables from '@/ipc-api/Tables'; import Tables from '@/ipc-api/Tables';
import { ref } from 'vue'; import { Component, Ref, ref } from 'vue';
import { useNotificationsStore } from '@/stores/notifications';
import { TableDeleteParams, TableUpdateParams } from 'common/interfaces/tableApis';
const { addNotification } = useNotificationsStore();
export default function useResultTables (uid, reloadTable, addNotification) { export function useResultTables (uid: string, reloadTable: () => void) {
const tableRef = ref(null); const queryTable: Ref<Component & {
resetSort: () => void;
resizeResults: () => void;
refreshScroller: () => void;
downloadTable: (format: string, fileName: string) => void;
applyUpdate: (payload: TableUpdateParams) => void;
}> = ref(null);
const isQuering = ref(false); const isQuering = ref(false);
async function updateField (payload) { async function updateField (payload: TableUpdateParams) {
isQuering.value = true; isQuering.value = true;
const params = { const params = {
@ -20,7 +28,7 @@ export default function useResultTables (uid, reloadTable, addNotification) {
if (response.reload)// Needed for blob fields if (response.reload)// Needed for blob fields
reloadTable(); reloadTable();
else else
tableRef.value.applyUpdate(payload); queryTable.value.applyUpdate(payload);
} }
else else
addNotification({ status: 'error', message: response }); addNotification({ status: 'error', message: response });
@ -32,7 +40,7 @@ export default function useResultTables (uid, reloadTable, addNotification) {
isQuering.value = false; isQuering.value = false;
} }
async function deleteSelected (payload) { async function deleteSelected (payload: TableDeleteParams) {
isQuering.value = true; isQuering.value = true;
const params = { const params = {
@ -56,7 +64,7 @@ export default function useResultTables (uid, reloadTable, addNotification) {
} }
return { return {
tableRef, queryTable,
isQuering, isQuering,
updateField, updateField,
deleteSelected deleteSelected

View File

@ -15,7 +15,7 @@ export default class {
return ipcRenderer.invoke('alter-function', unproxify(params)); return ipcRenderer.invoke('alter-function', unproxify(params));
} }
static alterTriggerFunction (params: {func: CreateFunctionParams & { uid: string }}): Promise<IpcResponse> { static alterTriggerFunction (params: { uid: string; func: AlterFunctionParams }): Promise<IpcResponse> {
return ipcRenderer.invoke('alter-trigger-function', unproxify(params)); return ipcRenderer.invoke('alter-trigger-function', unproxify(params));
} }

View File

@ -11,7 +11,7 @@ export default class {
return ipcRenderer.invoke('drop-routine', unproxify(params)); return ipcRenderer.invoke('drop-routine', unproxify(params));
} }
static alterRoutine (params: { routine: AlterRoutineParams & { uid: string } }): Promise<IpcResponse> { static alterRoutine (params: { uid: string; routine: AlterRoutineParams }): Promise<IpcResponse> {
return ipcRenderer.invoke('alter-routine', unproxify(params)); return ipcRenderer.invoke('alter-routine', unproxify(params));
} }

View File

@ -1,9 +1,9 @@
import { ipcRenderer } from 'electron'; import { ipcRenderer } from 'electron';
import { unproxify } from '../libs/unproxify'; import { unproxify } from '../libs/unproxify';
import { AlterEventParams, CreateEventParams, EventInfos, IpcResponse } from 'common/interfaces/antares'; import { AlterEventParams, CreateEventParams, IpcResponse } from 'common/interfaces/antares';
export default class { export default class {
static getSchedulerInformations (params: { uid: string; schema: string; scheduler: string}): Promise<IpcResponse<EventInfos>> { static getSchedulerInformations (params: { uid: string; schema: string; scheduler: string}): Promise<IpcResponse> {
return ipcRenderer.invoke('get-scheduler-informations', unproxify(params)); return ipcRenderer.invoke('get-scheduler-informations', unproxify(params));
} }
@ -11,7 +11,7 @@ export default class {
return ipcRenderer.invoke('drop-scheduler', unproxify(params)); return ipcRenderer.invoke('drop-scheduler', unproxify(params));
} }
static alterScheduler (params: { scheduler: AlterEventParams & { uid: string } }): Promise<IpcResponse> { static alterScheduler (params: { uid: string; scheduler: AlterEventParams }): Promise<IpcResponse> {
return ipcRenderer.invoke('alter-scheduler', unproxify(params)); return ipcRenderer.invoke('alter-scheduler', unproxify(params));
} }

View File

@ -82,7 +82,7 @@ export default class {
return ipcRenderer.invoke('get-processes', uid); return ipcRenderer.invoke('get-processes', uid);
} }
static killProcess (params: { uid: string; pid: string }): Promise<IpcResponse> { static killProcess (params: { uid: string; pid: number }): Promise<IpcResponse> {
return ipcRenderer.invoke('kill-process', unproxify(params)); return ipcRenderer.invoke('kill-process', unproxify(params));
} }

View File

@ -1,6 +1,6 @@
import { ipcRenderer } from 'electron'; import { ipcRenderer } from 'electron';
import { unproxify } from '../libs/unproxify'; import { unproxify } from '../libs/unproxify';
import { AlterTableParams, CreateTableParams, IpcResponse, TableForeign, TableIndex, TableInfos } from 'common/interfaces/antares'; import { AlterTableParams, CreateTableParams, IpcResponse } from 'common/interfaces/antares';
export default class { export default class {
static getTableColumns (params: {schema: string; table: string }): Promise<IpcResponse> { static getTableColumns (params: {schema: string; table: string }): Promise<IpcResponse> {
@ -27,15 +27,15 @@ export default class {
return ipcRenderer.invoke('get-table-count', unproxify(params)); return ipcRenderer.invoke('get-table-count', unproxify(params));
} }
static getTableOptions (params: { uid: string; schema: string; table: string }): Promise<IpcResponse<TableInfos>> { static getTableOptions (params: { uid: string; schema: string; table: string }): Promise<IpcResponse> {
return ipcRenderer.invoke('get-table-options', unproxify(params)); return ipcRenderer.invoke('get-table-options', unproxify(params));
} }
static getTableIndexes (params: { uid: string; schema: string; table: string }): Promise<IpcResponse<TableIndex[]>> { static getTableIndexes (params: { uid: string; schema: string; table: string }): Promise<IpcResponse> {
return ipcRenderer.invoke('get-table-indexes', unproxify(params)); return ipcRenderer.invoke('get-table-indexes', unproxify(params));
} }
static getKeyUsage (params: { uid: string; schema: string; table: string }): Promise<IpcResponse<TableForeign[]>> { static getKeyUsage (params: { uid: string; schema: string; table: string }): Promise<IpcResponse> {
return ipcRenderer.invoke('get-key-usage', unproxify(params)); return ipcRenderer.invoke('get-key-usage', unproxify(params));
} }

View File

@ -1,53 +0,0 @@
import Tables from '@/ipc-api/Tables';
export default {
methods: {
async updateField (payload) {
this.isQuering = true;
const params = {
uid: this.connection.uid,
...payload
};
try {
const { status, response } = await Tables.updateTableCell(params);
if (status === 'success') {
if (response.reload)// Needed for blob fields
this.reloadTable();
else
this.$refs.queryTable.applyUpdate(payload);
}
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false;
},
async deleteSelected (payload) {
this.isQuering = true;
const params = {
uid: this.connection.uid,
...payload
};
try {
const { status, response } = await Tables.deleteTableRows(params);
this.isQuering = false;
if (status === 'success')
this.reloadTable();
else
this.addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
this.isQuering = false;
}
}
}
};