1
1
mirror of https://github.com/Fabio286/antares.git synced 2025-06-05 21:59:22 +02:00

refactor: ts and composition api on missing components

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

View File

@ -1,5 +1,34 @@
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 {
uid: 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 => {
return {
name: scheduler.EVENT_NAME,
definition: scheduler.EVENT_DEFINITION,
type: scheduler.EVENT_TYPE,
schema: scheduler.Db,
sql: scheduler.EVENT_DEFINITION,
execution: scheduler.EVENT_TYPE === 'RECURRING' ? 'EVERY' : 'ONCE',
definer: scheduler.DEFINER,
body: scheduler.EVENT_BODY,
starts: scheduler.STARTS,
ends: scheduler.ENDS,
state: scheduler.STATUS === 'ENABLED' ? 'ENABLE' : scheduler.STATE === 'DISABLED' ? 'DISABLE' : 'DISABLE ON SLAVE',
enabled: scheduler.STATUS === 'ENABLED',
executeAt: scheduler.EXECUTE_AT,
intervalField: scheduler.INTERVAL_FIELD,
intervalValue: scheduler.INTERVAL_VALUE,
onCompletion: scheduler.ON_COMPLETION,
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
at: scheduler.EXECUTE_AT,
every: [scheduler.INTERVAL_FIELD, scheduler.INTERVAL_VALUE],
preserve: scheduler.ON_COMPLETION.includes('PRESERVE'),
comment: scheduler.EVENT_COMMENT
};
});
@ -930,19 +923,22 @@ export class MySQLClient extends AntaresCore {
}
async getViewInformations ({ schema, view }: { schema: string; view: string }) {
const sql = `SHOW CREATE VIEW \`${schema}\`.\`${view}\``;
const results = await this.raw(sql);
const { rows: algorithm } = await this.raw(`SHOW CREATE VIEW \`${schema}\`.\`${view}\``);
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 {
algorithm: row['Create View'].match(/(?<=CREATE ALGORITHM=).*?(?=\s)/gs)[0],
definer: row['Create View'].match(/(?<=DEFINER=).*?(?=\s)/gs)[0],
security: row['Create View'].match(/(?<=SQL SECURITY ).*?(?=\s)/gs)[0],
updateOption: row['Create View'].match(/(?<=WITH ).*?(?=\s)/gs) ? row['Create View'].match(/(?<=WITH ).*?(?=\s)/gs)[0] : '',
sql: row['Create View'].match(/(?<=AS ).*?$/gs)[0],
name: row.View
algorithm: algorithm[0]['Create View'].match(/(?<=CREATE ALGORITHM=).*?(?=\s)/gs)[0],
definer: viewInfo[0].DEFINER,
security: viewInfo[0].SECURITY_TYPE,
updateOption: viewInfo[0].CHECK_OPTION === 'NONE' ? '' : viewInfo[0].CHECK_OPTION,
sql: viewInfo[0].VIEW_DEFINITION,
name: viewInfo[0].TABLE_NAME
};
})[0];
}
async dropView (params: { schema: string; view: string }) {
@ -955,7 +951,7 @@ export class MySQLClient extends AntaresCore {
USE \`${view.schema}\`;
ALTER ALGORITHM = ${view.algorithm}${view.definer ? ` DEFINER=${view.definer}` : ''}
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)

View File

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

View File

@ -7,7 +7,7 @@
<div class="modal-title h6">
<div class="d-flex">
<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>
<a class="btn btn-clear c-hand" @click.stop="closeModal" />
@ -22,7 +22,7 @@
v-model="searchTerm"
class="form-input"
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
@ -67,13 +67,13 @@
<small class="tile-subtitle">{{ query.schema }} · {{ formatDate(query.date) }}</small>
<div class="tile-history-buttons">
<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 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 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>
</div>
</div>
@ -88,7 +88,7 @@
<i class="mdi mdi-history mdi-48px" />
</div>
<p class="empty-title h5">
{{ $t('message.thereIsNoQueriesYet') }}
{{ t('message.thereIsNoQueriesYet') }}
</p>
</div>
</div>
@ -99,12 +99,15 @@
<script setup lang="ts">
import { Component, computed, ComputedRef, onBeforeUnmount, onMounted, onUpdated, Prop, Ref, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import * as moment from 'moment';
import { ConnectionParams } from 'common/interfaces/antares';
import { HistoryRecord, useHistoryStore } from '@/stores/history';
import { useConnectionsStore } from '@/stores/connections';
import BaseVirtualScroll from '@/components/BaseVirtualScroll.vue';
const { t } = useI18n();
const { getHistoryByWorkspace, deleteQueryFromHistory } = useHistoryStore();
const { getConnectionName } = useConnectionsStore();

View File

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

View File

@ -201,7 +201,7 @@ const {
changeBreadcrumbs
} = 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 isLoading = ref(false);
const isSaving = ref(false);
@ -336,7 +336,7 @@ const addField = () => {
});
setTimeout(() => {
const scrollable = indexTable.value.$refs.tableWrapper;
const scrollable = indexTable.value.tableWrapper;
scrollable.scrollTop = scrollable.scrollHeight + 30;
}, 20);
};
@ -364,7 +364,7 @@ const duplicateField = (uid: string) => {
localFields.value = [...localFields.value, fieldToClone];
setTimeout(() => {
const scrollable = indexTable.value.$refs.tableWrapper;
const scrollable = indexTable.value.tableWrapper;
scrollable.scrollTop = scrollable.scrollHeight + 30;
}, 20);
};

View File

@ -85,12 +85,12 @@
/>
<div v-if="customizations.triggerMultipleEvents" class="px-4">
<label
v-for="event in Object.keys(localEvents)"
v-for="event in Object.keys(localEvents) as ('INSERT' | 'UPDATE' | 'DELETE')[]"
:key="event"
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>
</div>
</div>

View File

@ -144,17 +144,9 @@ const originalView = ref(null);
const localView = ref(null);
const editorHeight = ref(300);
const workspace = computed(() => {
return getWorkspace(props.connection.uid);
});
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 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];

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
<template>
<ConfirmModal
:confirm-text="$t('word.confirm')"
:confirm-text="t('word.confirm')"
size="400"
@confirm="confirmOptionsChange"
@hide="$emit('hide')"
@ -8,14 +8,14 @@
<template #header>
<div class="d-flex">
<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>
</template>
<template #body>
<form class="form-horizontal">
<div class="form-group">
<label class="form-label col-4">
{{ $t('word.execution') }}
{{ t('word.execution') }}
</label>
<div class="column">
<BaseSelect
@ -61,7 +61,7 @@
</div>
<div class="form-group">
<label class="form-label col-4">
{{ $t('word.starts') }}
{{ t('word.starts') }}
</label>
<div class="column">
<div class="input-group">
@ -82,7 +82,7 @@
</div>
<div class="form-group">
<label class="form-label col-4">
{{ $t('word.ends') }}
{{ t('word.ends') }}
</label>
<div class="column">
<div class="input-group">
@ -124,7 +124,7 @@
<div class="col-4" />
<div class="column">
<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>
</div>
</div>
@ -133,52 +133,47 @@
</ConfirmModal>
</template>
<script>
import moment from 'moment';
import ConfirmModal from '@/components/BaseConfirmModal';
<script setup lang="ts">
import { Ref, ref } from 'vue';
import * as moment from 'moment';
import { useI18n } from 'vue-i18n';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import { EventInfos } from 'common/interfaces/antares';
export default {
name: 'WorkspaceTabPropsSchedulerTimingModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
const { t } = useI18n();
const props = defineProps({
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;
this.hasEnd = !!this.optionsProxy.ends;
const emit = defineEmits(['hide', 'options-update']);
if (!this.optionsProxy.at) this.optionsProxy.at = moment().format('YYYY-MM-DD HH:mm:ss');
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 = '';
const optionsProxy: Ref<EventInfos> = ref({} as EventInfos);
const hasStart = ref(false);
const hasEnd = ref(false);
this.$emit('options-update', this.optionsProxy);
},
isNumberOrMinus (event) {
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>

View File

@ -11,16 +11,16 @@
@click="saveChanges"
>
<i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span>
<span>{{ t('word.save') }}</span>
</button>
<button
:disabled="!isChanged || isSaving"
class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')"
:title="t('message.clearChanges')"
@click="clearChanges"
>
<i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span>
<span>{{ t('word.clear') }}</span>
</button>
<div class="divider-vert py-3" />
@ -28,20 +28,20 @@
<button
:disabled="isSaving"
class="btn btn-dark btn-sm"
:title="$t('message.addNewField')"
:title="t('message.addNewField')"
@click="addField"
>
<i class="mdi mdi-24px mdi-playlist-plus mr-1" />
<span>{{ $t('word.add') }}</span>
<span>{{ t('word.add') }}</span>
</button>
<button
:disabled="isSaving"
class="btn btn-dark btn-sm"
:title="$t('message.manageIndexes')"
:title="t('message.manageIndexes')"
@click="showIntdexesModal"
>
<i class="mdi mdi-24px mdi-key mdi-rotate-45 mr-1" />
<span>{{ $t('word.indexes') }}</span>
<span>{{ t('word.indexes') }}</span>
</button>
<button
class="btn btn-dark btn-sm"
@ -49,11 +49,11 @@
@click="showForeignModal"
>
<i class="mdi mdi-24px mdi-key-link mr-1" />
<span>{{ $t('word.foreignKeys') }}</span>
<span>{{ t('word.foreignKeys') }}</span>
</button>
</div>
<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>
</div>
</div>
@ -63,7 +63,7 @@
<div class="columns mb-4">
<div class="column col-auto">
<div class="form-group">
<label class="form-label">{{ $t('word.name') }}</label>
<label class="form-label">{{ t('word.name') }}</label>
<input
v-model="localOptions.name"
class="form-input"
@ -73,7 +73,7 @@
</div>
<div v-if="workspace.customizations.comment" class="column">
<div class="form-group">
<label class="form-label">{{ $t('word.comment') }}</label>
<label class="form-label">{{ t('word.comment') }}</label>
<input
v-model="localOptions.comment"
class="form-input"
@ -85,7 +85,7 @@
<div v-if="workspace.customizations.autoIncrement" class="column col-auto">
<div class="form-group">
<label class="form-label">
{{ $t('word.autoIncrement') }}
{{ t('word.autoIncrement') }}
</label>
<input
ref="firstInput"
@ -99,7 +99,7 @@
<div v-if="workspace.customizations.collations" class="column col-auto">
<div class="form-group">
<label class="form-label">
{{ $t('word.collation') }}
{{ t('word.collation') }}
</label>
<BaseSelect
v-model="localOptions.collation"
@ -113,7 +113,7 @@
<div v-if="workspace.customizations.engines" class="column col-auto">
<div class="form-group">
<label class="form-label">
{{ $t('word.engine') }}
{{ t('word.engine') }}
</label>
<BaseSelect
v-model="localOptions.engine"
@ -172,170 +172,119 @@
</div>
</template>
<script>
<script setup lang="ts">
import { Component, computed, onBeforeUnmount, Ref, ref, watch } from 'vue';
import { AlterTableParams, TableField, TableForeign, TableIndex, TableInfos, TableOptions } from 'common/interfaces/antares';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces';
import { uidGen } from 'common/libs/uidGen';
import Tables from '@/ipc-api/Tables';
import BaseLoader from '@/components/BaseLoader';
import WorkspaceTabPropsTableFields from '@/components/WorkspaceTabPropsTableFields';
import WorkspaceTabPropsTableIndexesModal from '@/components/WorkspaceTabPropsTableIndexesModal';
import WorkspaceTabPropsTableForeignModal from '@/components/WorkspaceTabPropsTableForeignModal';
import BaseLoader from '@/components/BaseLoader.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import WorkspaceTabPropsTableFields from '@/components/WorkspaceTabPropsTableFields.vue';
import WorkspaceTabPropsTableIndexesModal from '@/components/WorkspaceTabPropsTableIndexesModal.vue';
import WorkspaceTabPropsTableForeignModal from '@/components/WorkspaceTabPropsTableForeignModal.vue';
export default {
name: 'WorkspaceTabPropsTable',
components: {
BaseLoader,
WorkspaceTabPropsTableFields,
WorkspaceTabPropsTableIndexesModal,
WorkspaceTabPropsTableForeignModal,
BaseSelect
},
props: {
const { t } = useI18n();
const props = defineProps({
tabUid: String,
connection: Object,
isSelected: Boolean,
table: String,
schema: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
});
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore);
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const {
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore);
const {
getWorkspace,
getDatabaseVariable,
refreshStructure,
renameTabs,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
} = workspacesStore;
return {
addNotification,
getDatabaseVariable,
getWorkspace,
selectedWorkspace,
refreshStructure,
setUnsavedChanges,
renameTabs,
changeBreadcrumbs
};
},
data () {
return {
isLoading: false,
isSaving: false,
isIndexesModal: false,
isForeignModal: false,
isOptionsChanging: false,
originalFields: [],
localFields: [],
originalKeyUsage: [],
localKeyUsage: [],
originalIndexes: [],
localIndexes: [],
tableOptions: {},
localOptions: {},
lastTable: null,
newFieldsCounter: 0
};
},
computed: {
workspace () {
return this.getWorkspace(this.connection.uid);
},
defaultCollation () {
if (this.workspace.customizations.collations)
return this.getDatabaseVariable(this.selectedWorkspace, 'collation_server')?.value || '';
const indexTable: Ref<Component & {tableWrapper: HTMLDivElement }> = ref(null);
const firstInput: Ref<HTMLInputElement> = ref(null);
const isLoading = ref(false);
const isSaving = ref(false);
const isIndexesModal = ref(false);
const isForeignModal = ref(false);
const originalFields: Ref<TableField[]> = ref([]);
const localFields: Ref<TableField[]> = ref([]);
const originalKeyUsage: Ref<TableForeign[]> = ref([]);
const localKeyUsage: Ref<TableForeign[]> = ref([]);
const originalIndexes: Ref<TableIndex[]> = ref([]);
const localIndexes: Ref<TableIndex[]> = ref([]);
const tableOptions: Ref<TableOptions> = ref(null);
const localOptions: Ref<TableOptions> = ref({} as TableOptions);
const lastTable = ref(null);
const newFieldsCounter = ref(0);
const workspace = computed(() => {
return getWorkspace(props.connection.uid);
});
const defaultCollation = computed(() => {
if (workspace.value.customizations.collations)
return getDatabaseVariable(selectedWorkspace.value, 'collation_server')?.value || '';
return '';
},
defaultEngine () {
const engine = this.getDatabaseVariable(this.connection.uid, 'default_storage_engine');
return engine ? engine.value : '';
},
schemaTables () {
const schemaTables = this.workspace.structure
.filter(schema => schema.name === this.schema)
});
const schemaTables = computed(() => {
const schemaTables = workspace.value.structure
.filter(schema => schema.name === props.schema)
.map(schema => schema.tables);
return schemaTables.length ? schemaTables[0].filter(table => table.type === 'table') : [];
},
isChanged () {
return JSON.stringify(this.originalFields) !== JSON.stringify(this.localFields) ||
JSON.stringify(this.originalKeyUsage) !== JSON.stringify(this.localKeyUsage) ||
JSON.stringify(this.originalIndexes) !== JSON.stringify(this.localIndexes) ||
JSON.stringify(this.tableOptions) !== JSON.stringify(this.localOptions);
}
},
watch: {
schema () {
if (this.isSelected) {
this.getFieldsData();
this.lastTable = this.table;
}
},
table () {
if (this.isSelected) {
this.getFieldsData();
this.lastTable = this.table;
}
},
isSelected (val) {
if (val) {
this.changeBreadcrumbs({ schema: this.schema, table: this.table });
});
if (this.lastTable !== this.table)
this.getFieldsData();
}
},
isChanged (val) {
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
}
},
created () {
this.getFieldsData();
window.addEventListener('keydown', this.onKey);
},
beforeUnmount () {
window.removeEventListener('keydown', this.onKey);
},
methods: {
async getTableOptions (params) {
const db = this.workspace.structure.find(db => db.name === this.schema);
const isChanged = computed(() => {
return JSON.stringify(originalFields.value) !== JSON.stringify(localFields.value) ||
JSON.stringify(originalKeyUsage.value) !== JSON.stringify(localKeyUsage.value) ||
JSON.stringify(originalIndexes.value) !== JSON.stringify(localIndexes.value) ||
JSON.stringify(tableOptions.value) !== JSON.stringify(localOptions.value);
});
if (db && db.tables.length && this.table)
this.tableOptions = db.tables.find(table => table.name === this.table);
const getTableOptions = async (params: {uid: string; schema: string; table: string}) => {
const db = workspace.value.structure.find(db => db.name === props.schema);
if (db && db.tables.length && props.table)
tableOptions.value = db.tables.find(table => table.name === props.table);
else {
const { status, response } = await Tables.getTableOptions(params);
if (status === 'success')
this.tableOptions = response;
tableOptions.value = response;
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
},
async getFieldsData () {
if (!this.table) return;
};
this.localFields = [];
this.lastTable = this.table;
this.newFieldsCounter = 0;
this.isLoading = true;
const getFieldsData = async () => {
if (!props.table) return;
localFields.value = [];
lastTable.value = props.table;
newFieldsCounter.value = 0;
isLoading.value = true;
const params = {
uid: this.connection.uid,
schema: this.schema,
table: this.table
uid: props.connection.uid,
schema: props.schema,
table: props.table
};
try {
await this.getTableOptions(params);
this.localOptions = JSON.parse(JSON.stringify(this.tableOptions));
await getTableOptions(params);
localOptions.value = JSON.parse(JSON.stringify(tableOptions.value));
}
catch (err) {
console.error(err);
@ -344,7 +293,7 @@ export default {
try { // Columns data
const { status, response } = await Tables.getTableColumns(params);
if (status === 'success') {
this.originalFields = response.map(field => {
originalFields.value = response.map((field: TableField) => {
if (field.autoIncrement)
field.defaultType = 'autoincrement';
else if (field.default === null)
@ -361,30 +310,31 @@ export default {
return { ...field, _antares_id: uidGen() };
});
this.localFields = JSON.parse(JSON.stringify(this.originalFields));
localFields.value = JSON.parse(JSON.stringify(originalFields.value));
}
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
addNotification({ status: 'error', message: err.stack });
}
try { // Indexes
const { status, response } = await Tables.getTableIndexes(params);
if (status === 'success') {
const indexesObj = response.reduce((acc, curr) => {
const indexesObj = response.reduce((acc: {[key: string]: TableIndex[]}, curr: TableIndex) => {
acc[curr.name] = acc[curr.name] || [];
acc[curr.name].push(curr);
return acc;
}, {});
this.originalIndexes = Object.keys(indexesObj).map(index => {
originalIndexes.value = Object.keys(indexesObj).map(index => {
return {
_antares_id: uidGen(),
name: index,
fields: indexesObj[index].map(field => field.column),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fields: indexesObj[index].map((field: any) => field.column),
type: indexesObj[index][0].type,
comment: indexesObj[index][0].comment,
indexType: indexesObj[index][0].indexType,
@ -393,91 +343,93 @@ export default {
};
});
this.localIndexes = JSON.parse(JSON.stringify(this.originalIndexes));
localIndexes.value = JSON.parse(JSON.stringify(originalIndexes.value));
}
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
addNotification({ status: 'error', message: err.stack });
}
try { // Key usage (foreign keys)
const { status, response } = await Tables.getKeyUsage(params);
if (status === 'success') {
this.originalKeyUsage = response.map(foreign => {
originalKeyUsage.value = response.map((foreign: TableForeign) => {
return {
_antares_id: uidGen(),
...foreign
};
});
this.localKeyUsage = JSON.parse(JSON.stringify(this.originalKeyUsage));
localKeyUsage.value = JSON.parse(JSON.stringify(originalKeyUsage.value));
}
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
addNotification({ status: 'error', message: err.stack });
}
this.isLoading = false;
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
isLoading.value = false;
};
const saveChanges = async () => {
if (isSaving.value) return;
isSaving.value = true;
// FIELDS
const originalIDs = this.originalFields.reduce((acc, curr) => [...acc, curr._antares_id], []);
const localIDs = this.localFields.reduce((acc, curr) => [...acc, curr._antares_id], []);
const originalIDs = originalFields.value.reduce((acc, curr) => [...acc, curr._antares_id], []);
const localIDs = localFields.value.reduce((acc, curr) => [...acc, curr._antares_id], []);
// Fields Additions
const additions = this.localFields.filter(field => !originalIDs.includes(field._antares_id)).map(field => {
const lI = this.localFields.findIndex(localField => localField._antares_id === field._antares_id);
const after = lI > 0 ? this.localFields[lI - 1].name : false;
const additions = localFields.value.filter(field => !originalIDs.includes(field._antares_id)).map(field => {
const lI = localFields.value.findIndex(localField => localField._antares_id === field._antares_id);
const after = lI > 0 ? localFields.value[lI - 1].name : false;
return { ...field, after };
});
// Fields Deletions
const deletions = this.originalFields.filter(field => !localIDs.includes(field._antares_id));
const deletions = originalFields.value.filter(field => !localIDs.includes(field._antares_id));
// Fields Changes
const changes = [];
this.localFields.forEach((field, i) => {
const originalField = this.originalFields.find(oField => oField._antares_id === field._antares_id);
const changes: TableField[] & {after: string | boolean; orgName: string}[] = [];
localFields.value.forEach((field, i) => {
const originalField = originalFields.value.find(oField => oField._antares_id === field._antares_id);
if (!originalField) return;
const after = i > 0 ? this.localFields[i - 1].name : false;
const after = i > 0 ? localFields.value[i - 1].name : false;
const orgName = originalField.name;
changes.push({ ...field, after, orgName });
});
// OPTIONS
const options = Object.keys(this.localOptions).reduce((acc, option) => {
if (this.localOptions[option] !== this.tableOptions[option])
acc[option] = this.localOptions[option];
const options = Object.keys(localOptions.value).reduce((acc: {[key:string]: TableInfos}, option: keyof TableInfos) => {
if (localOptions.value[option] !== tableOptions.value[option])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
acc[option] = localOptions.value[option] as any;
return acc;
}, {});
// INDEXES
const indexChanges = {
additions: [],
changes: [],
deletions: []
additions: [] as TableIndex[],
changes: [] as TableIndex[],
deletions: [] as TableIndex[]
};
const originalIndexIDs = this.originalIndexes.reduce((acc, curr) => [...acc, curr._antares_id], []);
const localIndexIDs = this.localIndexes.reduce((acc, curr) => [...acc, curr._antares_id], []);
const originalIndexIDs = originalIndexes.value.reduce((acc, curr) => [...acc, curr._antares_id], []);
const localIndexIDs = localIndexes.value.reduce((acc, curr) => [...acc, curr._antares_id], []);
// Index Additions
indexChanges.additions = this.localIndexes.filter(index => !originalIndexIDs.includes(index._antares_id));
indexChanges.additions = localIndexes.value.filter(index => !originalIndexIDs.includes(index._antares_id));
// Index Changes
this.originalIndexes.forEach(originalIndex => {
const lI = this.localIndexes.findIndex(localIndex => localIndex._antares_id === originalIndex._antares_id);
if (JSON.stringify(originalIndex) !== JSON.stringify(this.localIndexes[lI])) {
if (this.localIndexes[lI]) {
originalIndexes.value.forEach(originalIndex => {
const lI = localIndexes.value.findIndex(localIndex => localIndex._antares_id === originalIndex._antares_id);
if (JSON.stringify(originalIndex) !== JSON.stringify(localIndexes.value[lI])) {
if (localIndexes.value[lI]) {
indexChanges.changes.push({
...this.localIndexes[lI],
...localIndexes.value[lI],
oldName: originalIndex.name,
oldType: originalIndex.type
});
@ -486,27 +438,27 @@ export default {
});
// Index Deletions
indexChanges.deletions = this.originalIndexes.filter(index => !localIndexIDs.includes(index._antares_id));
indexChanges.deletions = originalIndexes.value.filter(index => !localIndexIDs.includes(index._antares_id));
// FOREIGN KEYS
const foreignChanges = {
additions: [],
changes: [],
deletions: []
additions: [] as TableForeign[],
changes: [] as TableForeign[],
deletions: [] as TableForeign[]
};
const originalForeignIDs = this.originalKeyUsage.reduce((acc, curr) => [...acc, curr._antares_id], []);
const localForeignIDs = this.localKeyUsage.reduce((acc, curr) => [...acc, curr._antares_id], []);
const originalForeignIDs = originalKeyUsage.value.reduce((acc, curr) => [...acc, curr._antares_id], []);
const localForeignIDs = localKeyUsage.value.reduce((acc, curr) => [...acc, curr._antares_id], []);
// Foreigns Additions
foreignChanges.additions = this.localKeyUsage.filter(foreign => !originalForeignIDs.includes(foreign._antares_id));
foreignChanges.additions = localKeyUsage.value.filter(foreign => !originalForeignIDs.includes(foreign._antares_id));
// Foreigns Changes
this.originalKeyUsage.forEach(originalForeign => {
const lI = this.localKeyUsage.findIndex(localForeign => localForeign._antares_id === originalForeign._antares_id);
if (JSON.stringify(originalForeign) !== JSON.stringify(this.localKeyUsage[lI])) {
if (this.localKeyUsage[lI]) {
originalKeyUsage.value.forEach(originalForeign => {
const lI = localKeyUsage.value.findIndex(localForeign => localForeign._antares_id === originalForeign._antares_id);
if (JSON.stringify(originalForeign) !== JSON.stringify(localKeyUsage.value[lI])) {
if (localKeyUsage.value[lI]) {
foreignChanges.changes.push({
...this.localKeyUsage[lI],
...localKeyUsage.value[lI],
oldName: originalForeign.constraintName
});
}
@ -514,18 +466,18 @@ export default {
});
// Foreigns Deletions
foreignChanges.deletions = this.originalKeyUsage.filter(foreign => !localForeignIDs.includes(foreign._antares_id));
foreignChanges.deletions = originalKeyUsage.value.filter(foreign => !localForeignIDs.includes(foreign._antares_id));
// ALTER
const params = {
uid: this.connection.uid,
schema: this.schema,
table: this.table,
uid: props.connection.uid,
schema: props.schema,
table: props.table,
tableStructure: {
name: this.localOptions.name,
fields: this.localFields,
foreigns: this.localKeyUsage,
indexes: this.localIndexes
name: localOptions.value.name,
fields: localFields.value,
foreigns: localKeyUsage.value,
indexes: localIndexes.value
},
additions,
changes,
@ -533,115 +485,122 @@ export default {
indexChanges,
foreignChanges,
options
};
} as unknown as AlterTableParams;
try {
const { status, response } = await Tables.alterTable(params);
if (status === 'success') {
const oldName = this.tableOptions.name;
const oldName = tableOptions.value.name;
await this.refreshStructure(this.connection.uid);
await refreshStructure(props.connection.uid);
if (oldName !== this.localOptions.name) {
this.renameTabs({
uid: this.connection.uid,
schema: this.schema,
if (oldName !== localOptions.value.name) {
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: oldName,
elementNewName: this.localOptions.name,
elementNewName: localOptions.value.name,
elementType: 'table'
});
this.changeBreadcrumbs({ schema: this.schema, table: this.localOptions.name });
changeBreadcrumbs({ schema: props.schema, table: localOptions.value.name });
}
else
this.getFieldsData();
getFieldsData();
}
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
addNotification({ status: 'error', message: err.stack });
}
this.isSaving = false;
this.newFieldsCounter = 0;
},
clearChanges () {
this.localFields = JSON.parse(JSON.stringify(this.originalFields));
this.localIndexes = JSON.parse(JSON.stringify(this.originalIndexes));
this.localKeyUsage = JSON.parse(JSON.stringify(this.originalKeyUsage));
this.localOptions = JSON.parse(JSON.stringify(this.tableOptions));
this.newFieldsCounter = 0;
},
addField () {
this.localFields.push({
isSaving.value = false;
newFieldsCounter.value = 0;
};
const clearChanges = () => {
localFields.value = JSON.parse(JSON.stringify(originalFields.value));
localIndexes.value = JSON.parse(JSON.stringify(originalIndexes.value));
localKeyUsage.value = JSON.parse(JSON.stringify(originalKeyUsage.value));
localOptions.value = JSON.parse(JSON.stringify(tableOptions.value));
newFieldsCounter.value = 0;
};
const addField = () => {
localFields.value.push({
_antares_id: uidGen(),
name: `${this.$tc('word.field', 1)}_${++this.newFieldsCounter}`,
name: `${t('word.field', 1)}_${++newFieldsCounter.value}`,
key: '',
type: this.workspace.dataTypes[0].types[0].name,
schema: this.schema,
table: this.table,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type: (workspace.value.dataTypes[0] as any).types[0].name,
schema: props.schema,
numPrecision: null,
numLength: this.workspace.dataTypes[0].types[0].length,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
numLength: (workspace.value.dataTypes[0] as any).types[0].length,
datePrecision: null,
charLength: null,
nullable: false,
unsigned: false,
zerofill: false,
order: this.localFields.length + 1,
order: localFields.value.length + 1,
default: null,
charset: null,
collation: this.defaultCollation,
collation: defaultCollation.value,
autoIncrement: false,
onUpdate: '',
comment: ''
});
setTimeout(() => {
const scrollable = this.$refs.indexTable.$refs.tableWrapper;
const scrollable = indexTable.value.tableWrapper;
scrollable.scrollTop = scrollable.scrollHeight + 30;
}, 20);
},
renameField (payload) {
this.localIndexes = this.localIndexes.map(index => {
};
const renameField = (payload: {index: string; new: string; old: string}) => {
localIndexes.value = localIndexes.value.map(index => {
const fi = index.fields.findIndex(field => field === payload.old);
if (fi !== -1)
index.fields[fi] = payload.new;
return index;
});
this.localKeyUsage = this.localKeyUsage.map(key => {
localKeyUsage.value = localKeyUsage.value.map(key => {
if (key.field === payload.old)
key.field = payload.new;
return key;
});
},
duplicateField (uid) {
const fieldToClone = Object.assign({}, this.localFields.find(field => field._antares_id === uid));
};
const duplicateField = (uid: string) => {
const fieldToClone = Object.assign({}, localFields.value.find(field => field._antares_id === uid));
fieldToClone._antares_id = uidGen();
fieldToClone.name = `${fieldToClone.name}_copy`;
fieldToClone.order = this.localFields.length + 1;
this.localFields = [...this.localFields, fieldToClone];
fieldToClone.order = localFields.value.length + 1;
localFields.value = [...localFields.value, fieldToClone];
setTimeout(() => {
const scrollable = this.$refs.indexTable.$refs.tableWrapper;
const scrollable = indexTable.value.tableWrapper;
scrollable.scrollTop = scrollable.scrollHeight + 30;
}, 20);
},
removeField (uid) {
this.localFields = this.localFields.filter(field => field._antares_id !== uid);
this.localKeyUsage = this.localKeyUsage.filter(fk =>// Clear foreign keys
this.localFields.some(field => field.name === fk.field)
};
const removeField = (uid: string) => {
localFields.value = localFields.value.filter(field => field._antares_id !== uid);
localKeyUsage.value = localKeyUsage.value.filter(fk =>// Clear foreign keys
localFields.value.some(field => field.name === fk.field)
);
this.localIndexes = this.localIndexes.filter(index =>// Clear indexes
this.localFields.some(field =>
localIndexes.value = localIndexes.value.filter(index =>// Clear indexes
localFields.value.some(field =>
index.fields.includes(field.name)
)
);
},
addNewIndex (payload) {
this.localIndexes = [...this.localIndexes, {
};
const addNewIndex = (payload: { index: string; field: string }) => {
localIndexes.value = [...localIndexes.value, {
_antares_id: uidGen(),
name: payload.index === 'PRIMARY' ? 'PRIMARY' : payload.field,
fields: [payload.field],
@ -651,43 +610,80 @@ export default {
indexComment: '',
cardinality: 0
}];
},
addToIndex (payload) {
this.localIndexes = this.localIndexes.map(index => {
};
const addToIndex = (payload: { index: string; field: string }) => {
localIndexes.value = localIndexes.value.map(index => {
if (index._antares_id === payload.index) index.fields.push(payload.field);
return index;
});
},
optionsUpdate (options) {
this.localOptions = options;
},
showIntdexesModal () {
this.isIndexesModal = true;
},
hideIndexesModal () {
this.isIndexesModal = false;
},
indexesUpdate (indexes) {
this.localIndexes = indexes;
},
showForeignModal () {
this.isForeignModal = true;
},
hideForeignModal () {
this.isForeignModal = false;
},
foreignsUpdate (foreigns) {
this.localKeyUsage = foreigns;
},
onKey (e) {
if (this.isSelected) {
};
const showIntdexesModal = () => {
isIndexesModal.value = true;
};
const hideIndexesModal = () => {
isIndexesModal.value = false;
};
const indexesUpdate = (indexes: TableIndex[]) => {
localIndexes.value = indexes;
};
const showForeignModal = () => {
isForeignModal.value = true;
};
const hideForeignModal = () => {
isForeignModal.value = false;
};
const foreignsUpdate = (foreigns: TableForeign[]) => {
localKeyUsage.value = foreigns;
};
const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (this.isChanged)
this.saveChanges();
}
}
if (e.ctrlKey && e.key === 's') { // CTRL + S
if (isChanged.value)
saveChanges();
}
}
};
watch(() => props.schema, () => {
if (props.isSelected) {
getFieldsData();
lastTable.value = props.table;
}
});
watch(() => props.table, () => {
if (props.isSelected) {
getFieldsData();
lastTable.value = props.table;
}
});
watch(() => props.isSelected, (val) => {
if (val) {
changeBreadcrumbs({ schema: props.schema, table: props.table });
if (lastTable.value !== props.table)
getFieldsData();
}
});
watch(isChanged, (val) => {
setUnsavedChanges({ uid: props.connection.uid, tUid: props.tabUid, isChanged: val });
});
getFieldsData();
window.addEventListener('keydown', onKey);
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
});
</script>

View File

@ -4,7 +4,7 @@
@close-context="closeContext"
>
<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" />
<div class="context-submenu">
<div
@ -19,7 +19,7 @@
</div>
</div>
<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" />
<div class="context-submenu">
<div
@ -34,54 +34,54 @@
</div>
</div>
<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 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>
</BaseContextMenu>
</template>
<script>
import BaseContextMenu from '@/components/BaseContextMenu';
<script setup lang="ts">
import { computed, Prop } from 'vue';
import { useI18n } from 'vue-i18n';
import BaseContextMenu from '@/components/BaseContextMenu.vue';
import { TableIndex } from 'common/interfaces/antares';
export default {
name: 'WorkspaceTabQueryTableContext',
components: {
BaseContextMenu
},
props: {
const { t } = useI18n();
const props = defineProps({
contextEvent: MouseEvent,
indexes: Array,
indexTypes: Array,
indexes: Array as Prop<TableIndex[]>,
indexTypes: Array as Prop<string[]>,
selectedField: Object
},
emits: ['close-context', 'duplicate-selected', 'delete-selected', 'add-new-index', 'add-to-index'],
computed: {
hasPrimary () {
return this.indexes.some(index => index.type === 'PRIMARY');
}
},
methods: {
closeContext () {
this.$emit('close-context');
},
duplicateField () {
this.$emit('duplicate-selected');
this.closeContext();
},
deleteField () {
this.$emit('delete-selected');
this.closeContext();
},
addNewIndex (index) {
this.$emit('add-new-index', { field: this.selectedField.name, index });
this.closeContext();
},
addToIndex (index) {
this.$emit('add-to-index', { field: this.selectedField.name, index });
this.closeContext();
}
}
});
const emit = defineEmits(['close-context', 'duplicate-selected', 'delete-selected', 'add-new-index', 'add-to-index']);
const hasPrimary = computed(() => props.indexes.some(index => index.type === 'PRIMARY'));
const closeContext = () => {
emit('close-context');
};
const duplicateField = () => {
emit('duplicate-selected');
closeContext();
};
const deleteField = () => {
emit('delete-selected');
closeContext();
};
const addNewIndex = (index: string) => {
emit('add-new-index', { field: props.selectedField.name, index });
closeContext();
};
const addToIndex = (index: string) => {
emit('add-to-index', { field: props.selectedField.name, index });
closeContext();
};
</script>

View File

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

View File

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

View File

@ -1,6 +1,6 @@
<template>
<ConfirmModal
:confirm-text="$t('word.confirm')"
:confirm-text="t('word.confirm')"
size="medium"
class="options-modal"
@confirm="confirmIndexesChange"
@ -9,7 +9,7 @@
<template #header>
<div class="d-flex">
<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>
</template>
<template #body>
@ -20,16 +20,16 @@
<div class="d-flex">
<button class="btn btn-dark btn-sm d-flex" @click="addIndex">
<i class="mdi mdi-24px mdi-key-plus mr-1" />
<span>{{ $t('word.add') }}</span>
<span>{{ t('word.add') }}</span>
</button>
<button
class="btn btn-dark btn-sm d-flex ml-2 mr-0"
:title="$t('message.clearChanges')"
:title="t('message.clearChanges')"
:disabled="!isChanged"
@click.prevent="clearChanges"
>
<i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span>
<span>{{ t('word.clear') }}</span>
</button>
</div>
</div>
@ -50,12 +50,12 @@
<div class="tile-title">
{{ index.name }}
</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 class="tile-action">
<button
class="btn btn-link remove-field p-0 mr-2"
:title="$t('word.delete')"
:title="t('word.delete')"
@click.prevent="removeIndex(index._antares_id)"
>
<i class="mdi mdi-close" />
@ -74,7 +74,7 @@
>
<div class="form-group">
<label class="form-label col-3">
{{ $t('word.name') }}
{{ t('word.name') }}
</label>
<div class="column">
<input
@ -86,20 +86,20 @@
</div>
<div class="form-group">
<label class="form-label col-3">
{{ $t('word.type') }}
{{ t('word.type') }}
</label>
<div class="column">
<BaseSelect
v-model="selectedIndexObj.type"
:options="indexTypes"
:option-disabled="(opt) => opt === 'PRIMARY'"
:option-disabled="(opt: any) => opt === 'PRIMARY'"
class="form-select"
/>
</div>
</div>
<div class="form-group">
<label class="form-label col-3">
{{ $tc('word.field', fields.length) }}
{{ t('word.field', fields.length) }}
</label>
<div class="fields-list column pt-1">
<label
@ -108,7 +108,7 @@
class="form-checkbox m-0"
@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 }}
</label>
</div>
@ -119,11 +119,11 @@
<i class="mdi mdi-key-outline mdi-48px" />
</div>
<p class="empty-title h5">
{{ $t('message.thereAreNoIndexes') }}
{{ t('message.thereAreNoIndexes') }}
</p>
<div class="empty-action">
<button class="btn btn-primary" @click="addIndex">
{{ $t('message.createNewIndex') }}
{{ t('message.createNewIndex') }}
</button>
</div>
</div>
@ -133,72 +133,53 @@
</ConfirmModal>
</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 ConfirmModal from '@/components/BaseConfirmModal';
import { useI18n } from 'vue-i18n';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue';
export default {
name: 'WorkspaceTabPropsTableIndexesModal',
components: {
ConfirmModal,
BaseSelect
},
props: {
const { t } = useI18n();
const props = defineProps({
localIndexes: Array,
table: String,
fields: Array,
fields: Array as Prop<TableField[]>,
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)
this.resetSelectedID();
const emit = defineEmits(['hide', 'indexes-update']);
this.getModalInnerHeight();
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 indexesPanel: Ref<HTMLDivElement> = ref(null);
const indexesProxy = ref([]);
const selectedIndexID = ref('');
const modalInnerHeight = ref(400);
const selectedIndexObj = computed(() => indexesProxy.value.find(index => index._antares_id === selectedIndexID.value));
const isChanged = computed(() => JSON.stringify(props.localIndexes) !== JSON.stringify(indexesProxy.value));
const confirmIndexesChange = () => {
indexesProxy.value = indexesProxy.value.filter(index => index.fields.length);
emit('indexes-update', indexesProxy.value);
};
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)
this.modalInnerHeight = modalBody.clientHeight - (parseFloat(getComputedStyle(modalBody).paddingTop) + parseFloat(getComputedStyle(modalBody).paddingBottom));
},
addIndex () {
this.indexesProxy = [...this.indexesProxy, {
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: [],
@ -209,40 +190,56 @@ export default {
cardinality: 0
}];
if (this.indexesProxy.length === 1)
this.resetSelectedID();
if (indexesProxy.value.length === 1)
resetSelectedID();
setTimeout(() => {
this.$refs.indexesPanel.scrollTop = this.$refs.indexesPanel.scrollHeight + 60;
indexesPanel.value.scrollTop = indexesPanel.value.scrollHeight + 60;
}, 20);
},
removeIndex (id) {
this.indexesProxy = this.indexesProxy.filter(index => index._antares_id !== id);
};
if (this.selectedIndexID === id && this.indexesProxy.length)
this.resetSelectedID();
},
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) {
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 => f !== field);
index.fields = index.fields.filter((f: string) => f !== field);
else
index.fields.push(field);
}
return index;
});
},
resetSelectedID () {
this.selectedIndexID = this.indexesProxy.length ? this.indexesProxy[0]._antares_id : '';
}
}
};
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>
<style lang="scss" scoped>

View File

@ -219,7 +219,7 @@
</div>
<ConfirmModal
v-if="isDefaultModal"
:confirm-text="$t('word.confirm')"
:confirm-text="t('word.confirm')"
size="400"
@confirm="editOFF"
@hide="hideDefaultModal"
@ -227,7 +227,7 @@
<template #header>
<div class="d-flex">
<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>
</template>
<template #body>
@ -250,7 +250,7 @@
value="custom"
type="radio"
name="default"
><i class="form-icon" /> {{ $t('message.customValue') }}
><i class="form-icon" /> {{ t('message.customValue') }}
</label>
<div class="column">
<input
@ -291,7 +291,7 @@
type="radio"
name="default"
value="expression"
><i class="form-icon" /> {{ $t('word.expression') }}
><i class="form-icon" /> {{ t('word.expression') }}
</label>
<div class="column">
<input
@ -306,7 +306,7 @@
<div v-if="customizations.onUpdate">
<div class="form-group">
<label class="form-label col-4">
{{ $t('message.onUpdate') }}
{{ t('message.onUpdate') }}
</label>
<div class="column">
<input
@ -323,89 +323,78 @@
</div>
</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 { useNotificationsStore } from '@/stores/notifications';
import { useWorkspacesStore } from '@/stores/workspaces';
import ConfirmModal from '@/components/BaseConfirmModal';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import { TableField, TableIndex, TypesGroup } from 'common/interfaces/antares';
export default {
name: 'WorkspaceTabPropsTableRow',
components: {
ConfirmModal,
BaseSelect
const { t } = useI18n();
const props = defineProps({
row: Object as Prop<TableField>,
dataTypes: {
type: Array as PropType<TypesGroup[]>,
default: () => []
},
props: {
row: Object,
dataTypes: { type: Array, default: () => [] },
indexes: Array,
foreigns: Array,
indexes: Array as Prop<TableIndex[]>,
foreigns: Array as Prop<string[]>,
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 {
addNotification,
selectedWorkspace,
getWorkspace
};
},
data () {
return {
localRow: {},
isInlineEditor: {},
isDefaultModal: false,
defaultValue: {
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore);
const { getWorkspace } = workspacesStore;
const localRow: Ref<TableField> = ref({} as TableField);
const isInlineEditor: Ref<TableField> = ref({} as TableField);
const isDefaultModal = ref(false);
const defaultValue = ref({
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;
});
const editingContent: Ref<string | number> = ref(null);
const originalContent = ref(null);
const editingField: Ref<keyof TableField> = ref(null);
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;
},
fieldType () {
const fieldType = this.dataTypes.reduce((acc, group) => [...acc, ...group.types], []).filter(type =>
type.name === (this.localRow.type ? this.localRow.type.toUpperCase() : '')
});
const fieldType = computed(() => {
const fieldType = props.dataTypes.reduce((acc, group) => [...acc, ...group.types], []).filter(type =>
type.name === (localRow.value.type ? localRow.value.type.toUpperCase() : '')
);
const group = this.dataTypes.filter(group => group.types.some(type =>
type.name === (this.localRow.type ? this.localRow.type.toUpperCase() : ''))
const group = props.dataTypes.filter(group => group.types.some(type =>
type.name === (localRow.value.type ? localRow.value.type.toUpperCase() : ''))
);
return fieldType.length ? { ...fieldType[0], group: group[0].group } : {};
},
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 fieldDefault = computed(() => {
if (localRow.value.autoIncrement) return 'AUTO_INCREMENT';
if (localRow.value.default === 'NULL') return 'NULL';
return localRow.value.default;
});
const collations = computed(() => getWorkspace(selectedWorkspace.value).collations);
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)));
const isInDataTypes = computed(() => {
let typeNames: string[] = [];
for (const group of props.dataTypes) {
const groupTypeNames = group.types.reduce((acc, curr) => {
acc.push(curr.name);
return acc;
@ -413,195 +402,190 @@ export default {
typeNames = [...groupTypeNames, ...typeNames];
}
return typeNames.includes(this.row.type);
},
types () {
const types = [...this.dataTypes];
if (!this.isInDataTypes)
types.unshift({ name: this.row });
return typeNames.includes(props.row.type);
});
const types = computed(() => {
const types = [...props.dataTypes];
if (!isInDataTypes.value)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(types as any).unshift({ name: props.row });
return types;
}
},
watch: {
localRow () {
this.initLocalRow();
},
row () {
this.localRow = this.row;
},
indexes () {
if (!this.canAutoincrement)
this.localRow.autoIncrement = false;
});
if (!this.isNullable)
this.localRow.nullable = false;
}
},
mounted () {
this.localRow = this.row;
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) {
const typeClass = (type: string) => {
if (type)
return `type-${type.toLowerCase().replaceAll(' ', '_').replaceAll('"', '')}`;
return '';
},
initLocalRow () {
Object.keys(this.localRow).forEach(key => {
this.isInlineEditor[key] = false;
};
const initLocalRow = () => {
Object.keys(localRow.value).forEach(key => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(isInlineEditor as any).value[key] = false;
});
this.defaultValue.onUpdate = this.localRow.onUpdate;
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
defaultValue.value.onUpdate = localRow.value.onUpdate;
defaultValue.value.type = localRow.value.defaultType || 'noval';
if (defaultValue.value.type === 'custom') {
defaultValue.value.custom = localRow.value.default
? localRow.value.default.includes('\'')
? localRow.value.default.split('\'')[1]
: localRow.value.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 if (defaultValue.value.type === 'expression') {
if (localRow.value.default.toUpperCase().includes('ON UPDATE'))
defaultValue.value.expression = localRow.value.default.replace(/ on update.*$/i, '');
else
this.defaultValue.expression = this.localRow.default;
defaultValue.value.expression = localRow.value.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') {
this.editingContent = this.localRow.enumValues;
this.originalContent = this.localRow.enumValues;
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 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
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 {
this.editingContent = content;
this.originalContent = content;
editingContent.value = content;
originalContent.value = content;
}
const obj = { [field]: true };
this.isInlineEditor = { ...this.isInlineEditor, ...obj };
isInlineEditor.value = { ...isInlineEditor.value, ...obj };
if (field === 'default')
this.isDefaultModal = true;
isDefaultModal.value = true;
else {
this.$nextTick(() => { // Focus on input
event.target.blur();
this.$nextTick(() => document.querySelector('.editable-field').focus());
});
await nextTick();
(event as MouseEvent & { target: HTMLInputElement }).target.blur();
await nextTick();
document.querySelector<HTMLInputElement>('.editable-field').focus();
}
},
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 [length, scale] = this.editingContent.split(',');
this.localRow.numLength = +length;
this.localRow.numScale = scale ? +scale : null;
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
this.localRow[this.editingField] = this.editingContent;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(localRow.value as any)[editingField.value] = editingContent.value;
if (this.editingField === 'type' && this.editingContent !== this.originalContent) {
this.localRow.numLength = null;
this.localRow.numScale = null;
this.localRow.charLength = null;
this.localRow.datePrecision = null;
this.localRow.enumValues = '';
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 (this.fieldType.length) {
if (['integer', 'float', 'binary', 'spatial'].includes(this.fieldType.group)) this.localRow.numLength = 11;
if (['string'].includes(this.fieldType.group)) this.localRow.charLength = 15;
if (['time'].includes(this.fieldType.group)) this.localRow.datePrecision = 0;
if (['other'].includes(this.fieldType.group)) this.localRow.enumValues = '\'valA\',\'valB\'';
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 (!this.fieldType.collation)
this.localRow.collation = null;
if (!fieldType.value.collation)
localRow.value.collation = null;
if (!this.fieldType.unsigned)
this.localRow.unsigned = false;
if (!fieldType.value.unsigned)
localRow.value.unsigned = false;
if (!this.fieldType.zerofill)
this.localRow.zerofill = false;
if (!fieldType.value.zerofill)
localRow.value.zerofill = false;
}
else if (this.editingField === 'default') {
switch (this.defaultValue.type) {
else if (editingField.value === 'default') {
switch (defaultValue.value.type) {
case 'autoincrement':
this.localRow.autoIncrement = true;
localRow.value.autoIncrement = true;
break;
case 'noval':
this.localRow.autoIncrement = false;
this.localRow.default = null;
localRow.value.autoIncrement = false;
localRow.value.default = null;
break;
case 'null':
this.localRow.autoIncrement = false;
this.localRow.default = 'NULL';
localRow.value.autoIncrement = false;
localRow.value.default = 'NULL';
break;
case 'custom':
this.localRow.autoIncrement = false;
this.localRow.default = Number.isNaN(+this.defaultValue.custom) ? `'${this.defaultValue.custom}'` : this.defaultValue.custom;
localRow.value.autoIncrement = false;
localRow.value.default = Number.isNaN(+defaultValue.value.custom) ? `'${defaultValue.value.custom}'` : defaultValue.value.custom;
break;
case 'expression':
this.localRow.autoIncrement = false;
this.localRow.default = this.defaultValue.expression;
localRow.value.autoIncrement = false;
localRow.value.default = defaultValue.value.expression;
break;
}
this.localRow.onUpdate = this.defaultValue.onUpdate;
localRow.value.onUpdate = defaultValue.value.onUpdate;
}
Object.keys(this.isInlineEditor).forEach(key => {
this.isInlineEditor = { ...this.isInlineEditor, [key]: false };
Object.keys(isInlineEditor.value).forEach(key => {
isInlineEditor.value = { ...isInlineEditor.value, [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;
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;
},
hideDefaultModal () {
this.isDefaultModal = false;
}
}
};
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>
<style lang="scss" scoped>

View File

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

View File

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

View File

@ -11,20 +11,20 @@
@click="saveChanges"
>
<i class="mdi mdi-24px mdi-content-save mr-1" />
<span>{{ $t('word.save') }}</span>
<span>{{ t('word.save') }}</span>
</button>
<button
:disabled="!isChanged"
class="btn btn-link btn-sm mr-0"
:title="$t('message.clearChanges')"
:title="t('message.clearChanges')"
@click="clearChanges"
>
<i class="mdi mdi-24px mdi-delete-sweep mr-1" />
<span>{{ $t('word.clear') }}</span>
<span>{{ t('word.clear') }}</span>
</button>
</div>
<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>
</div>
</div>
@ -34,7 +34,7 @@
<div class="columns">
<div class="column col-auto">
<div class="form-group">
<label class="form-label">{{ $t('word.name') }}</label>
<label class="form-label">{{ t('word.name') }}</label>
<input
v-model="localView.name"
class="form-input"
@ -44,19 +44,19 @@
</div>
<div class="column col-auto">
<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
v-model="localView.definer"
:options="users"
:option-label="(user) => user.value === '' ? $t('message.currentUser') : `${user.name}@${user.host}`"
:option-track-by="(user) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
:option-label="(user: any) => user.value === '' ? t('message.currentUser') : `${user.name}@${user.host}`"
:option-track-by="(user: any) => user.value === '' ? '' : `\`${user.name}\`@\`${user.host}\``"
class="form-select"
/>
</div>
</div>
<div class="column col-auto mr-2">
<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
v-model="localView.security"
:options="['DEFINER', 'INVOKER']"
@ -66,7 +66,7 @@
</div>
<div class="column col-auto mr-2">
<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
v-model="localView.algorithm"
:options="['UNDEFINED', 'MERGE', 'TEMPTABLE']"
@ -76,10 +76,10 @@
</div>
<div v-if="workspace.customizations.viewUpdateOption" class="column col-auto mr-2">
<div class="form-group">
<label class="form-label">{{ $t('message.updateOption') }}</label>
<label class="form-label">{{ t('message.updateOption') }}</label>
<BaseSelect
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'}]"
class="form-select"
/>
@ -89,7 +89,7 @@
</div>
<div class="workspace-query-results column col-12 mt-2 p-relative">
<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
v-show="isSelected"
ref="queryEditor"
@ -102,168 +102,100 @@
</div>
</template>
<script>
import { storeToRefs } from 'pinia';
<script setup lang="ts">
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 { useWorkspacesStore } from '@/stores/workspaces';
import BaseLoader from '@/components/BaseLoader';
import QueryEditor from '@/components/QueryEditor';
import Views from '@/ipc-api/Views';
import BaseLoader from '@/components/BaseLoader.vue';
import QueryEditor from '@/components/QueryEditor.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import Views from '@/ipc-api/Views';
export default {
name: 'WorkspaceTabPropsView',
components: {
BaseLoader,
QueryEditor,
BaseSelect
},
props: {
const { t } = useI18n();
const props = defineProps({
tabUid: String,
connection: Object,
isSelected: Boolean,
schema: String,
view: String
},
setup () {
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
});
const { getSelected: selectedWorkspace } = storeToRefs(workspacesStore);
const { addNotification } = useNotificationsStore();
const workspacesStore = useWorkspacesStore();
const {
const {
getWorkspace,
refreshStructure,
renameTabs,
changeBreadcrumbs,
setUnsavedChanges
} = workspacesStore;
} = workspacesStore;
return {
addNotification,
selectedWorkspace,
getWorkspace,
refreshStructure,
renameTabs,
changeBreadcrumbs,
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('@');
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;
}
},
watch: {
async schema () {
if (this.isSelected) {
await this.getViewData();
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(() => {
this.resizeQueryEditor();
}, 200);
if (this.lastView !== this.view)
this.getViewData();
}
},
isChanged (val) {
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: val });
}
},
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 getViewData = async () => {
if (!props.view) return;
isLoading.value = true;
localView.value = { sql: '' };
lastView.value = props.view;
const params = {
uid: this.connection.uid,
schema: this.schema,
view: this.view
uid: props.connection.uid,
schema: props.schema,
view: props.view
};
try {
const { status, response } = await Views.getViewInformations(params);
if (status === 'success') {
this.originalView = response;
this.localView = JSON.parse(JSON.stringify(this.originalView));
this.sqlProxy = this.localView.sql;
originalView.value = response;
localView.value = JSON.parse(JSON.stringify(originalView.value));
sqlProxy.value = localView.value.sql;
}
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
addNotification({ status: 'error', message: err.stack });
}
this.resizeQueryEditor();
this.isLoading = false;
},
async saveChanges () {
if (this.isSaving) return;
this.isSaving = true;
resizeQueryEditor();
isLoading.value = false;
};
const saveChanges = async () => {
if (isSaving.value) return;
isSaving.value = true;
const params = {
uid: this.connection.uid,
uid: props.connection.uid,
view: {
...this.localView,
schema: this.schema,
oldName: this.originalView.name
...localView.value,
schema: props.schema,
oldName: originalView.value.name
}
};
@ -271,54 +203,103 @@ export default {
const { status, response } = await Views.alterView(params);
if (status === 'success') {
const oldName = this.originalView.name;
const oldName = originalView.value.name;
await this.refreshStructure(this.connection.uid);
await refreshStructure(props.connection.uid);
if (oldName !== this.localView.name) {
this.renameTabs({
uid: this.connection.uid,
schema: this.schema,
if (oldName !== localView.value.name) {
renameTabs({
uid: props.connection.uid,
schema: props.schema,
elementName: oldName,
elementNewName: this.localView.name,
elementNewName: localView.value.name,
elementType: 'view'
});
this.changeBreadcrumbs({ schema: this.schema, view: this.localView.name });
changeBreadcrumbs({ schema: props.schema, view: localView.value.name });
}
else
this.getViewData();
getViewData();
}
else
this.addNotification({ status: 'error', message: response });
addNotification({ status: 'error', message: response });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
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) {
isSaving.value = false;
};
const clearChanges = () => {
localView.value = JSON.parse(JSON.stringify(originalView.value));
queryEditor.value.editor.session.setValue(localView.value.sql);
};
const resizeQueryEditor = () => {
if (queryEditor.value) {
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();
const size = window.innerHeight - queryEditor.value.$el.getBoundingClientRect().top - footer.offsetHeight;
editorHeight.value = size;
queryEditor.value.editor.resize();
}
},
onKey (e) {
if (this.isSelected) {
};
const onKey = (e: KeyboardEvent) => {
if (props.isSelected) {
e.stopPropagation();
if (e.ctrlKey && e.keyCode === 83) { // CTRL + S
if (this.isChanged)
this.saveChanges();
}
}
if (e.ctrlKey && e.key === 's') { // CTRL + S
if (isChanged.value)
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>

View File

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

View File

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

View File

@ -97,131 +97,120 @@
<template #header>
<div class="d-flex">
<i class="mdi mdi-24px mdi-delete mr-1" />
<span class="cut-text">{{ $tc('message.deleteRows', selectedRows.length) }}</span>
<span class="cut-text">{{ t('message.deleteRows', selectedRows.length) }}</span>
</div>
</template>
<template #body>
<div class="mb-2">
{{ $tc('message.confirmToDeleteRows', selectedRows.length) }}
{{ t('message.confirmToDeleteRows', selectedRows.length) }}
</div>
</template>
</ConfirmModal>
</div>
</template>
<script>
<script setup lang="ts">
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Component, computed, nextTick, onMounted, onUnmounted, onUpdated, Prop, ref, Ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { uidGen } from 'common/libs/uidGen';
import { useNotificationsStore } from '@/stores/notifications';
import { useSettingsStore } from '@/stores/settings';
import { useWorkspacesStore } from '@/stores/workspaces';
import { arrayToFile } from '../libs/arrayToFile';
import { TEXT, LONG_TEXT, BLOB } from 'common/fieldTypes';
import BaseVirtualScroll from '@/components/BaseVirtualScroll';
import WorkspaceTabQueryTableRow from '@/components/WorkspaceTabQueryTableRow';
import TableContext from '@/components/WorkspaceTabQueryTableContext';
import ConfirmModal from '@/components/BaseConfirmModal';
import BaseVirtualScroll from '@/components/BaseVirtualScroll.vue';
import WorkspaceTabQueryTableRow from '@/components/WorkspaceTabQueryTableRow.vue';
import TableContext from '@/components/WorkspaceTabQueryTableContext.vue';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import moment from 'moment';
import { useI18n } from 'vue-i18n';
import { TableField, QueryResult } from 'common/interfaces/antares';
import { TableUpdateParams } from 'common/interfaces/tableApis';
export default {
name: 'WorkspaceTabQueryTable',
components: {
BaseVirtualScroll,
WorkspaceTabQueryTableRow,
TableContext,
ConfirmModal
},
props: {
results: Array,
const { t } = useI18n();
const settingsStore = useSettingsStore();
const { getWorkspace } = useWorkspacesStore();
const { dataTabLimit: pageSize } = storeToRefs(settingsStore);
const props = defineProps({
results: Array as Prop<QueryResult[]>,
connUid: String,
mode: String,
isSelected: Boolean,
elementType: { type: String, default: 'table' }
},
emits: ['update-field', 'delete-selected', 'hard-sort'],
setup () {
const { addNotification } = useNotificationsStore();
const settingsStore = useSettingsStore();
const { getWorkspace } = useWorkspacesStore();
});
const { dataTabLimit: pageSize } = storeToRefs(settingsStore);
const emit = defineEmits(['update-field', 'delete-selected', 'hard-sort']);
return {
addNotification,
pageSize,
getWorkspace
};
},
data () {
return {
resultsSize: 0,
localResults: [],
isContext: false,
isDeleteConfirmModal: false,
contextEvent: null,
selectedCell: null,
selectedRows: [],
currentSort: '',
currentSortDir: 'asc',
resultsetIndex: 0,
scrollElement: null,
rowHeight: 23,
selectedField: null,
isEditingRow: false
};
},
computed: {
workspaceSchema () {
return this.getWorkspace(this.connUid).breadcrumbs.schema;
},
primaryField () {
const primaryFields = this.fields.filter(field => field.key === 'pri');
const uniqueFields = this.fields.filter(field => field.key === 'uni');
const resultTable: Ref<Component & {updateWindow: () => void}> = ref(null);
const tableWrapper: Ref<HTMLDivElement> = ref(null);
const table: Ref<HTMLDivElement> = ref(null);
const resultsSize = ref(0);
const localResults: Ref<QueryResult<any>[]> = ref([]);
const isContext = ref(false);
const isDeleteConfirmModal = ref(false);
const contextEvent = ref(null);
const selectedCell = ref(null);
const selectedRows = ref([]);
const currentSort = ref('');
const currentSortDir = ref('asc');
const resultsetIndex = ref(0);
const scrollElement = ref(null);
const rowHeight = ref(23);
const selectedField = ref(null);
const isEditingRow = ref(false);
const workspaceSchema = computed(() => getWorkspace(props.connUid).breadcrumbs.schema);
const primaryField = computed(() => {
const primaryFields = fields.value.filter(field => field.key === 'pri');
const uniqueFields = fields.value.filter(field => field.key === 'uni');
if ((primaryFields.length > 1 || !primaryFields.length) && (uniqueFields.length > 1 || !uniqueFields.length))
return false;
return null;
return primaryFields[0] || uniqueFields[0];
},
isSortable () {
return this.fields.every(field => field.name);
},
isHardSort () {
return this.mode === 'table' && this.localResults.length === this.pageSize;
},
sortedResults () {
if (this.currentSort && !this.isHardSort) {
return [...this.localResults].sort((a, b) => {
});
const isSortable = computed(() => {
return fields.value.every(field => field.name);
});
const isHardSort = computed(() => {
return props.mode === 'table' && localResults.value.length === pageSize.value;
});
const sortedResults = computed(() => {
if (currentSort.value && !isHardSort.value) {
return [...localResults.value].sort((a: any, b: any) => {
let modifier = 1;
let valA = typeof a[this.currentSort] === 'string' ? a[this.currentSort].toLowerCase() : a[this.currentSort];
let valA = typeof a[currentSort.value] === 'string' ? a[currentSort.value].toLowerCase() : a[currentSort.value];
if (!isNaN(valA)) valA = Number(valA);
let valB = typeof b[this.currentSort] === 'string' ? b[this.currentSort].toLowerCase() : b[this.currentSort];
let valB = typeof b[currentSort.value] === 'string' ? b[currentSort.value].toLowerCase() : b[currentSort.value];
if (!isNaN(valB)) valB = Number(valB);
if (this.currentSortDir === 'desc') modifier = -1;
if (currentSortDir.value === 'desc') modifier = -1;
if (valA < valB) return -1 * modifier;
if (valA > valB) return 1 * modifier;
return 0;
});
}
else
return this.localResults;
},
resultsWithRows () {
return this.results.filter(result => result.rows);
},
fields () {
return this.resultsWithRows.length ? this.resultsWithRows[this.resultsetIndex].fields : [];
},
keyUsage () {
return this.resultsWithRows.length ? this.resultsWithRows[this.resultsetIndex].keys : [];
},
fieldsObj () {
if (this.sortedResults.length) {
const fieldsObj = {};
for (const key in this.sortedResults[0]) {
return localResults.value;
});
const resultsWithRows = computed(() => props.results.filter(result => result.rows));
const fields = computed(() => resultsWithRows.value.length ? resultsWithRows.value[resultsetIndex.value].fields : []);
const keyUsage = computed(() => resultsWithRows.value.length ? resultsWithRows.value[resultsetIndex.value].keys : []);
const fieldsObj = computed(() => {
if (sortedResults.value.length) {
const fieldsObj: {[key: string]: TableField} = {};
for (const key in sortedResults.value[0]) {
if (key === '_antares_id') continue;
const fieldObj = this.fields.find(field => {
const fieldObj = fields.value.find(field => {
let fieldNames = [
field.name,
field.alias,
@ -245,64 +234,16 @@ export default {
return fieldsObj;
}
return {};
}
},
watch: {
results () {
this.setLocalResults();
this.resultsetIndex = 0;
},
resultsetIndex () {
this.setLocalResults();
},
isSelected (val) {
if (val) this.refreshScroller();
}
},
updated () {
if (this.$refs.table)
this.refreshScroller();
});
if (this.$refs.tableWrapper)
this.scrollElement = this.$refs.tableWrapper;
document.querySelectorAll('.column-resizable').forEach(element => {
if (element.clientWidth !== 0)
element.style.width = element.clientWidth + 'px';
});
},
mounted () {
window.addEventListener('resize', this.resizeResults);
window.addEventListener('keydown', this.onKey);
},
unmounted () {
window.removeEventListener('resize', this.resizeResults);
window.removeEventListener('keydown', this.onKey);
},
methods: {
fieldType (cKey) {
let type = 'unknown';
const field = this.fields.filter(field => field.name === cKey)[0];
if (field)
type = field.type;
return type;
},
fieldPrecision (cKey) {
let length = 0;
const field = this.fields.filter(field => field.name === cKey)[0];
if (field)
length = field.datePrecision;
return length;
},
fieldLength (field) {
const fieldLength = (field: TableField) => {
if ([...BLOB, ...LONG_TEXT].includes(field.type)) return null;
else if (TEXT.includes(field.type)) return field.charLength;
else if (field.numScale) return `${field.numPrecision}, ${field.numScale}`;
return field.length;
},
keyName (key) {
};
const keyName = (key: string) => {
switch (key) {
case 'pri':
return 'PRIMARY';
@ -313,57 +254,62 @@ export default {
default:
return 'UNKNOWN ' + key;
}
},
getTable (index) {
if (this.resultsWithRows[index] && this.resultsWithRows[index].fields && this.resultsWithRows[index].fields.length)
return this.resultsWithRows[index].fields[0].table;
};
const getTable = (index: number) => {
if (resultsWithRows.value[index] && resultsWithRows.value[index].fields && resultsWithRows.value[index].fields.length)
return resultsWithRows.value[index].fields[0].table;
return '';
},
getSchema (index) {
if (this.resultsWithRows[index] && this.resultsWithRows[index].fields && this.resultsWithRows[index].fields.length)
return this.resultsWithRows[index].fields[0].schema;
return this.workspaceSchema;
},
getPrimaryValue (row) {
};
const getSchema = (index: number) => {
if (resultsWithRows.value[index] && resultsWithRows.value[index].fields && resultsWithRows.value[index].fields.length)
return resultsWithRows.value[index].fields[0].schema;
return workspaceSchema.value;
};
const getPrimaryValue = (row: any) => {
const primaryFieldName = Object.keys(row).find(prop => [
this.primaryField.alias,
this.primaryField.name,
`${this.primaryField.table}.${this.primaryField.alias}`,
`${this.primaryField.table}.${this.primaryField.name}`,
`${this.primaryField.tableAlias}.${this.primaryField.alias}`,
`${this.primaryField.tableAlias}.${this.primaryField.name}`
primaryField.value.alias,
primaryField.value.name,
`${primaryField.value.table}.${primaryField.value.alias}`,
`${primaryField.value.table}.${primaryField.value.name}`,
`${primaryField.value.tableAlias}.${primaryField.value.alias}`,
`${primaryField.value.tableAlias}.${primaryField.value.name}`
].includes(prop));
return row[primaryFieldName];
},
setLocalResults () {
this.localResults = this.resultsWithRows[this.resultsetIndex] && this.resultsWithRows[this.resultsetIndex].rows
? this.resultsWithRows[this.resultsetIndex].rows.map(item => {
};
const setLocalResults = () => {
localResults.value = resultsWithRows.value[resultsetIndex.value] && resultsWithRows.value[resultsetIndex.value].rows
? resultsWithRows.value[resultsetIndex.value].rows.map(item => {
return { ...item, _antares_id: uidGen() };
})
: [];
},
resizeResults () {
if (this.$refs.resultTable && this.isSelected) {
const el = this.$refs.tableWrapper;
};
const resizeResults = () => {
if (resultTable.value && props.isSelected) {
const el = tableWrapper.value;
if (el) {
const footer = document.getElementById('footer');
const size = window.innerHeight - el.getBoundingClientRect().top - footer.offsetHeight;
this.resultsSize = size;
resultsSize.value = size;
}
this.$refs.resultTable.updateWindow();
resultTable.value.updateWindow();
}
},
refreshScroller () {
this.resizeResults();
},
updateField (payload, row) {
const orgRow = this.localResults.find(lr => lr._antares_id === row._antares_id);
};
const refreshScroller = () => resizeResults();
const updateField = (payload: { field: string; type: string; content: any }, row: {[key: string]: any}) => {
const orgRow: any = localResults.value.find((lr: any) => lr._antares_id === row._antares_id);
Object.keys(orgRow).forEach(key => { // remap the row
if (orgRow[key] instanceof Date && moment(orgRow[key]).isValid()) { // if datetime
let datePrecision = '';
const precision = this.fields.find(field => field.name === key).datePrecision;
const precision = fields.value.find(field => field.name === key)?.datePrecision;
for (let i = 0; i < precision; i++)
datePrecision += i === 0 ? '.S' : 'S';
@ -372,80 +318,88 @@ export default {
});
const params = {
primary: this.primaryField.name,
schema: this.getSchema(this.resultsetIndex),
table: this.getTable(this.resultsetIndex),
id: this.getPrimaryValue(orgRow),
primary: primaryField.value.name,
schema: getSchema(resultsetIndex.value),
table: getTable(resultsetIndex.value),
id: getPrimaryValue(orgRow),
row,
orgRow,
...payload
};
this.$emit('update-field', params);
},
closeContext () {
this.isContext = false;
},
showDeleteConfirmModal (e) {
emit('update-field', params);
};
const closeContext = () => {
isContext.value = false;
};
const showDeleteConfirmModal = (e: any) => {
if (e && e.path && ['INPUT', 'TEXTAREA', 'SELECT'].includes(e.path[0].tagName))
return;
this.isDeleteConfirmModal = true;
},
hideDeleteConfirmModal () {
this.isDeleteConfirmModal = false;
},
deleteSelected () {
this.closeContext();
const rows = JSON.parse(JSON.stringify(this.localResults)).filter(row => this.selectedRows.includes(row._antares_id)).map(row => {
isDeleteConfirmModal.value = true;
};
const hideDeleteConfirmModal = () => {
isDeleteConfirmModal.value = false;
};
const deleteSelected = () => {
closeContext();
const rows = JSON.parse(JSON.stringify(localResults.value)).filter((row: any) => selectedRows.value.includes(row._antares_id)).map((row: any) => {
delete row._antares_id;
return row;
});
const params = {
primary: this.primaryField.name,
schema: this.getSchema(this.resultsetIndex),
table: this.getTable(this.resultsetIndex),
primary: primaryField.value.name,
schema: getSchema(resultsetIndex.value),
table: getTable(resultsetIndex.value),
rows
};
this.$emit('delete-selected', params);
},
setNull () {
const row = this.localResults.find(row => this.selectedRows.includes(row._antares_id));
emit('delete-selected', params);
};
const setNull = () => {
const row = localResults.value.find((row: any) => selectedRows.value.includes(row._antares_id));
const params = {
primary: this.primaryField.name,
schema: this.getSchema(this.resultsetIndex),
table: this.getTable(this.resultsetIndex),
id: this.getPrimaryValue(row),
primary: primaryField.value.name,
schema: getSchema(resultsetIndex.value),
table: getTable(resultsetIndex.value),
id: getPrimaryValue(row),
row,
orgRow: row,
field: this.selectedCell.field,
content: null
field: selectedCell.value.field,
content: null as string
};
this.$emit('update-field', params);
},
copyCell () {
const row = this.localResults.find(row => this.selectedRows.includes(row._antares_id));
emit('update-field', params);
};
const copyCell = () => {
const row: any = localResults.value.find((row: any) => selectedRows.value.includes(row._antares_id));
const cellName = Object.keys(row).find(prop => [
this.selectedCell.field,
this.selectedCell.orgField,
`${this.fields[0].table}.${this.selectedCell.field}`,
`${this.fields[0].tableAlias}.${this.selectedCell.field}`
selectedCell.value.field,
selectedCell.value.orgField,
`${fields.value[0].table}.${selectedCell.value.field}`,
`${fields.value[0].tableAlias}.${selectedCell.value.field}`
].includes(prop));
let valueToCopy = row[cellName];
if (typeof valueToCopy === 'object')
valueToCopy = JSON.stringify(valueToCopy);
navigator.clipboard.writeText(valueToCopy);
},
copyRow () {
const row = this.localResults.find(row => this.selectedRows.includes(row._antares_id));
};
const copyRow = () => {
const row = localResults.value.find((row: any) => selectedRows.value.includes(row._antares_id));
const rowToCopy = JSON.parse(JSON.stringify(row));
delete rowToCopy._antares_id;
navigator.clipboard.writeText(JSON.stringify(rowToCopy));
},
applyUpdate (params) {
};
const applyUpdate = (params: TableUpdateParams) => {
const { primary, id, field, table, content } = params;
this.localResults = this.localResults.map(row => {
localResults.value = localResults.value.map((row: any) => {
if (row[primary] === id)// only fieldName
row[field] = content;
else if (row[`${table}.${primary}`] === id)// table.fieldName
@ -453,92 +407,100 @@ export default {
return row;
});
},
selectRow (event, row, field) {
this.selectedField = field;
};
const selectRow = (event: KeyboardEvent, row: any, field: string) => {
selectedField.value = field;
const selectedRowId = row._antares_id;
if (event.ctrlKey || event.metaKey) {
if (this.selectedRows.includes(selectedRowId))
this.selectedRows = this.selectedRows.filter(el => el !== selectedRowId);
if (selectedRows.value.includes(selectedRowId))
selectedRows.value = selectedRows.value.filter(el => el !== selectedRowId);
else
this.selectedRows.push(selectedRowId);
selectedRows.value.push(selectedRowId);
}
else if (event.shiftKey) {
if (!this.selectedRows.length)
this.selectedRows.push(selectedRowId);
if (!selectedRows.value.length)
selectedRows.value.push(selectedRowId);
else {
const lastID = this.selectedRows.slice(-1)[0];
const lastIndex = this.sortedResults.findIndex(el => el._antares_id === lastID);
const clickedIndex = this.sortedResults.findIndex(el => el._antares_id === selectedRowId);
const lastID = selectedRows.value.slice(-1)[0];
const lastIndex = sortedResults.value.findIndex((el: any) => el._antares_id === lastID);
const clickedIndex = sortedResults.value.findIndex((el: any) => el._antares_id === selectedRowId);
if (lastIndex > clickedIndex) {
for (let i = clickedIndex; i < lastIndex; i++)
this.selectedRows.push(this.sortedResults[i]._antares_id);
selectedRows.value.push((sortedResults.value[i] as any)._antares_id);
}
else if (lastIndex < clickedIndex) {
for (let i = clickedIndex; i > lastIndex; i--)
this.selectedRows.push(this.sortedResults[i]._antares_id);
selectedRows.value.push((sortedResults.value[i] as any)._antares_id);
}
}
}
else
this.selectedRows = [selectedRowId];
},
selectAllRows (e) {
if (e.target.classList.contains('editable-field')) return;
selectedRows.value = [selectedRowId];
};
this.selectedField = 0;
this.selectedRows = this.localResults.reduce((acc, curr) => {
const selectAllRows = (e: KeyboardEvent) => {
if ((e.target as HTMLElement).classList.contains('editable-field')) return;
selectedField.value = 0;
selectedRows.value = localResults.value.reduce((acc, curr: any) => {
acc.push(curr._antares_id);
return acc;
}, []);
},
deselectRows () {
if (!this.isEditingRow)
this.selectedRows = [];
},
contextMenu (event, cell) {
if (event.target.localName === 'input') return;
};
this.selectedCell = cell;
if (!this.selectedRows.includes(cell.id))
this.selectedRows = [cell.id];
this.contextEvent = event;
this.isContext = true;
},
sort (field) {
if (!this.isSortable) return;
const deselectRows = () => {
if (!isEditingRow.value)
selectedRows.value = [];
};
this.selectedRows = [];
const contextMenu = (event: MouseEvent, cell: any) => {
if ((event.target as HTMLElement).localName === 'input') return;
if (this.mode === 'query')
field = `${this.getTable(this.resultsetIndex)}.${field}`;
selectedCell.value = cell;
if (!selectedRows.value.includes(cell.id))
selectedRows.value = [cell.id];
contextEvent.value = event;
isContext.value = true;
};
if (field === this.currentSort) {
if (this.currentSortDir === 'asc')
this.currentSortDir = 'desc';
const sort = (field: string) => {
if (!isSortable.value) return;
selectedRows.value = [];
if (props.mode === 'query')
field = `${getTable(resultsetIndex.value)}.${field}`;
if (field === currentSort.value) {
if (currentSortDir.value === 'asc')
currentSortDir.value = 'desc';
else
this.resetSort();
resetSort();
}
else {
this.currentSortDir = 'asc';
this.currentSort = field;
currentSortDir.value = 'asc';
currentSort.value = field;
}
if (this.isHardSort)
this.$emit('hard-sort', { field: this.currentSort, dir: this.currentSortDir });
},
resetSort () {
this.currentSort = '';
this.currentSortDir = 'asc';
},
selectResultset (index) {
this.resultsetIndex = index;
},
downloadTable (format, filename) {
if (!this.sortedResults) return;
if (isHardSort.value)
emit('hard-sort', { field: currentSort.value, dir: currentSortDir.value });
};
const rows = JSON.parse(JSON.stringify(this.sortedResults)).map(row => {
const resetSort = () => {
currentSort.value = '';
currentSortDir.value = 'asc';
};
const selectResultset = (index: number) => {
resultsetIndex.value = index;
};
const downloadTable = (format: 'csv' | 'json', filename: string) => {
if (!sortedResults.value) return;
const rows = JSON.parse(JSON.stringify(sortedResults.value)).map((row: any) => {
delete row._antares_id;
return row;
});
@ -548,29 +510,30 @@ export default {
content: rows,
filename
});
},
onKey (e) {
if (!this.isSelected)
};
const onKey = async (e: KeyboardEvent) => {
if (!props.isSelected)
return;
if (this.isEditingRow)
if (isEditingRow.value)
return;
if ((e.ctrlKey || e.metaKey) && e.code === 'KeyA' && !e.altKey)
this.selectAllRows(e);
selectAllRows(e);
// row naviation stuff
if ((e.code.includes('Arrow') || e.code === 'Tab') && this.sortedResults.length > 0 && !e.altKey) {
// row navigation stuff
if ((e.code.includes('Arrow') || e.code === 'Tab') && sortedResults.value.length > 0 && !e.altKey) {
e.preventDefault();
const aviableFields= Object.keys(this.sortedResults[0]).slice(0, -1); // removes _antares_id
const aviableFields= Object.keys(sortedResults.value[0]).slice(0, -1); // removes _antares_id
if (!this.selectedField)
this.selectedField = aviableFields[0];
if (!selectedField.value)
selectedField.value = aviableFields[0];
const selectedId = this.selectedRows[0];
const selectedIndex = this.sortedResults.findIndex(row => row._antares_id === selectedId);
const selectedFieldIndex = aviableFields.findIndex(field => field === this.selectedField);
const selectedId = selectedRows.value[0];
const selectedIndex = sortedResults.value.findIndex((row: any) => row._antares_id === selectedId);
const selectedFieldIndex = aviableFields.findIndex(field => field === selectedField.value);
let nextIndex = 0;
let nextFieldIndex = 0;
@ -580,8 +543,8 @@ export default {
nextIndex = selectedIndex + 1;
nextFieldIndex = selectedFieldIndex;
if (nextIndex > this.sortedResults.length -1)
nextIndex = this.sortedResults.length -1;
if (nextIndex > sortedResults.value.length -1)
nextIndex = sortedResults.value.length -1;
break;
case 'ArrowUp':
@ -626,38 +589,78 @@ export default {
}
}
if (this.sortedResults[nextIndex] && nextIndex !== selectedIndex) {
this.selectedRows = [this.sortedResults[nextIndex]._antares_id];
this.$nextTick(() => this.scrollToCell(this.scrollElement.querySelector('.td.selected')));
if (sortedResults.value[nextIndex] && nextIndex !== selectedIndex) {
selectedRows.value = [(sortedResults.value[nextIndex] as any)._antares_id];
await nextTick();
scrollToCell(scrollElement.value.querySelector('.td.selected'));
}
if (aviableFields[nextFieldIndex] && nextFieldIndex !== selectedFieldIndex) {
this.selectedField = aviableFields[nextFieldIndex];
this.$nextTick(() => this.scrollToCell(this.scrollElement.querySelector('.td.selected')));
}
}
},
scrollToCell (el) {
if (!el) return;
const visYMin = this.scrollElement.scrollTop;
const visYMax = this.scrollElement.scrollTop + this.scrollElement.clientHeight - el.clientHeight;
const visXMin = this.scrollElement.scrollLeft;
const visXMax = this.scrollElement.scrollLeft + this.scrollElement.clientWidth - el.clientWidth;
if (el.offsetTop < visYMin)
this.scrollElement.scrollTop = el.offsetTop;
else if (el.offsetTop >= visYMax)
this.scrollElement.scrollTop = el.offsetTop - this.scrollElement.clientHeight + el.clientHeight;
if (el.offsetLeft < visXMin)
this.scrollElement.scrollLeft = el.offsetLeft;
else if (el.offsetLeft >= visXMax)
this.scrollElement.scrollLeft = el.offsetLeft - this.scrollElement.clientWidth + el.clientWidth;
selectedField.value = aviableFields[nextFieldIndex];
await nextTick();
scrollToCell(scrollElement.value.querySelector('.td.selected'));
}
}
};
const scrollToCell = (el: HTMLElement) => {
if (!el) return;
const visYMin = scrollElement.value.scrollTop;
const visYMax = scrollElement.value.scrollTop + scrollElement.value.clientHeight - el.clientHeight;
const visXMin = scrollElement.value.scrollLeft;
const visXMax = scrollElement.value.scrollLeft + scrollElement.value.clientWidth - el.clientWidth;
if (el.offsetTop < visYMin)
scrollElement.value.scrollTop = el.offsetTop;
else if (el.offsetTop >= visYMax)
scrollElement.value.scrollTop = el.offsetTop - scrollElement.value.clientHeight + el.clientHeight;
if (el.offsetLeft < visXMin)
scrollElement.value.scrollLeft = el.offsetLeft;
else if (el.offsetLeft >= visXMax)
scrollElement.value.scrollLeft = el.offsetLeft - scrollElement.value.clientWidth + el.clientWidth;
};
defineExpose({ applyUpdate, refreshScroller, resetSort, resizeResults, downloadTable });
watch(() => props.results, () => {
setLocalResults();
resultsetIndex.value = 0;
});
watch(resultsetIndex, () => {
setLocalResults();
});
watch(() => props.isSelected, (val) => {
if (val) refreshScroller();
});
onUpdated(() => {
if (table.value)
refreshScroller();
if (tableWrapper.value)
scrollElement.value = tableWrapper.value;
document.querySelectorAll<HTMLElement>('.column-resizable').forEach(element => {
if (element.clientWidth !== 0)
element.style.width = element.clientWidth + 'px';
});
});
onMounted(() => {
window.addEventListener('resize', resizeResults);
window.addEventListener('keydown', onKey);
});
onUnmounted(() => {
window.removeEventListener('resize', resizeResults);
window.removeEventListener('keydown', onKey);
});
</script>
<style lang="scss" scoped>

View File

@ -4,7 +4,7 @@
@close-context="closeContext"
>
<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" />
<div class="context-submenu">
<div
@ -13,7 +13,7 @@
@click="copyCell"
>
<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>
</div>
<div
@ -22,7 +22,7 @@
@click="copyRow"
>
<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>
</div>
</div>
@ -33,7 +33,7 @@
@click="setNull"
>
<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>
</div>
<div
@ -42,45 +42,46 @@
@click="showConfirmModal"
>
<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>
</div>
</BaseContextMenu>
</template>
<script>
import BaseContextMenu from '@/components/BaseContextMenu';
<script setup lang="ts">
import BaseContextMenu from '@/components/BaseContextMenu.vue';
import { useI18n } from 'vue-i18n';
export default {
name: 'WorkspaceTabQueryTableContext',
components: {
BaseContextMenu
},
props: {
const { t } = useI18n();
defineProps({
contextEvent: MouseEvent,
selectedRows: Array,
selectedCell: Object
},
emits: ['show-delete-modal', 'close-context', 'set-null', 'copy-cell', 'copy-row'],
methods: {
showConfirmModal () {
this.$emit('show-delete-modal');
},
closeContext () {
this.$emit('close-context');
},
setNull () {
this.$emit('set-null');
this.closeContext();
},
copyCell () {
this.$emit('copy-cell');
this.closeContext();
},
copyRow () {
this.$emit('copy-row');
this.closeContext();
}
}
});
const emit = defineEmits(['show-delete-modal', 'close-context', 'set-null', 'copy-cell', 'copy-row']);
const showConfirmModal = () => {
emit('show-delete-modal');
};
const closeContext = () => {
emit('close-context');
};
const setNull = () => {
emit('set-null');
closeContext();
};
const copyCell = () => {
emit('copy-cell');
closeContext();
};
const copyRow = () => {
emit('copy-row');
closeContext();
};
</script>

View File

@ -19,7 +19,7 @@
class="cell-content"
:class="`${isNull(col)} ${typeClass(fields[cKey].type)}`"
@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
v-else-if="isForeignKey(cKey)"
v-model="editingContent"
@ -68,14 +68,14 @@
</div>
<ConfirmModal
v-if="isTextareaEditor"
:confirm-text="$t('word.update')"
:confirm-text="t('word.update')"
size="medium"
@confirm="editOFF"
@hide="hideEditorModal"
>
<template #header>
<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>
</template>
<template #body>
@ -90,7 +90,7 @@
<div class="editor-field-info p-vcentered">
<div class="d-flex p-vcentered">
<label for="editorMode" class="form-label mr-2">
<b>{{ $t('word.content') }}</b>:
<b>{{ t('word.content') }}</b>:
</label>
<BaseSelect
id="editorMode"
@ -104,10 +104,10 @@
<div class="d-flex">
<div class="p-vcentered">
<div class="mr-4">
<b>{{ $t('word.size') }}</b>: {{ editingContent ? editingContent.length : 0 }}
<b>{{ t('word.size') }}</b>: {{ editingContent ? editingContent.length : 0 }}
</div>
<div v-if="editingType">
<b>{{ $t('word.type') }}</b>: {{ editingType.toUpperCase() }}
<b>{{ t('word.type') }}</b>: {{ editingType.toUpperCase() }}
</div>
</div>
</div>
@ -132,14 +132,14 @@
</ConfirmModal>
<ConfirmModal
v-if="isBlobEditor"
:confirm-text="$t('word.update')"
:confirm-text="t('word.update')"
@confirm="editOFF"
@hide="hideEditorModal"
>
<template #header>
<div class="d-flex">
<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>
</template>
<template #body>
@ -156,11 +156,11 @@
</div>
<div class="editor-buttons mt-2">
<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" />
</button>
<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" />
</button>
</div>
@ -168,19 +168,19 @@
</Transition>
<div class="editor-field-info">
<div>
<b>{{ $t('word.size') }}</b>: {{ formatBytes(editingContent.length) }}<br>
<b>{{ $t('word.mimeType') }}</b>: {{ contentInfo.mime }}
<b>{{ t('word.size') }}</b>: {{ formatBytes(editingContent.length) }}<br>
<b>{{ t('word.mimeType') }}</b>: {{ contentInfo.mime }}
</div>
<div v-if="editingType">
<b>{{ $t('word.type') }}</b>: {{ editingType.toUpperCase() }}
<b>{{ t('word.type') }}</b>: {{ editingType.toUpperCase() }}
</div>
</div>
<div class="mt-3">
<label>{{ $t('message.uploadFile') }}</label>
<label>{{ t('message.uploadFile') }}</label>
<input
class="form-input"
type="file"
@change="filesChange($event)"
@change="filesChange($event as any)"
>
</div>
</div>
@ -189,13 +189,15 @@
</div>
</template>
<script>
import moment from 'moment';
<script setup lang="ts">
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 { mimeFromHex } from 'common/libs/mimeFromHex';
import { formatBytes } from 'common/libs/formatBytes';
import { bufferToBase64 } from 'common/libs/bufferToBase64';
import hexToBinary from 'common/libs/hexToBinary';
import hexToBinary, { HexChar } from 'common/libs/hexToBinary';
import {
TEXT,
LONG_TEXT,
@ -213,52 +215,49 @@ import {
SPATIAL,
IS_MULTI_SPATIAL
} from 'common/fieldTypes';
import ConfirmModal from '@/components/BaseConfirmModal';
import TextEditor from '@/components/BaseTextEditor';
import BaseMap from '@/components/BaseMap';
import ForeignKeySelect from '@/components/ForeignKeySelect';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import TextEditor from '@/components/BaseTextEditor.vue';
import BaseMap from '@/components/BaseMap.vue';
import ForeignKeySelect from '@/components/ForeignKeySelect.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import { QueryForeign, TableField } from 'common/interfaces/antares';
export default {
name: 'WorkspaceTabQueryTableRow',
components: {
ConfirmModal,
TextEditor,
ForeignKeySelect,
BaseMap,
BaseSelect
},
props: {
const { t } = useI18n();
const props = defineProps({
row: Object,
fields: Object,
keyUsage: Array,
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 }
},
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: {
});
const emit = defineEmits(['update-field', 'select-row', 'contextmenu', 'start-editing', 'stop-editing']);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
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
},
fileToUpload: null,
availableLanguages: [
});
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' },
@ -267,313 +266,291 @@ export default {
{ 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))
]);
const inputProps = computed(() => {
if ([...TEXT, ...LONG_TEXT].includes(editingType.value))
return { type: 'text', mask: false };
if ([...NUMBER, ...FLOAT].includes(this.editingType))
if ([...NUMBER, ...FLOAT].includes(editingType.value))
return { type: 'number', mask: false };
if (TIME.includes(this.editingType)) {
if (TIME.includes(editingType.value)) {
let timeMask = '##:##:##';
const precision = this.fields[this.editingField].length;
const precision = props.fields[editingField.value].length;
for (let i = 0; i < precision; i++)
timeMask += i === 0 ? '.#' : '#';
if (HAS_TIMEZONE.includes(this.editingType))
if (HAS_TIMEZONE.includes(editingType.value))
timeMask += 'X##';
return { type: 'text', mask: timeMask };
}
if (DATE.includes(this.editingType))
if (DATE.includes(editingType.value))
return { type: 'text', mask: '####-##-##' };
if (DATETIME.includes(this.editingType)) {
if (DATETIME.includes(editingType.value)) {
let datetimeMask = '####-##-## ##:##:##';
const precision = this.fields[this.editingField].length;
const precision = props.fields[editingField.value].length;
for (let i = 0; i < precision; i++)
datetimeMask += i === 0 ? '.#' : '#';
if (HAS_TIMEZONE.includes(this.editingType))
if (HAS_TIMEZONE.includes(editingType.value))
datetimeMask += 'X##';
return { type: 'text', mask: datetimeMask };
}
if (BLOB.includes(this.editingType))
if (BLOB.includes(editingType.value))
return { type: 'file', mask: false };
if (BOOLEAN.includes(this.editingType))
if (BOOLEAN.includes(editingType.value))
return { type: 'boolean', mask: false };
if (SPATIAL.includes(this.editingType))
if (SPATIAL.includes(editingType.value))
return { type: 'map', mask: false };
return { type: 'text', mask: false };
},
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) {
const nElements = Object.keys(this.fields).reduce((acc, curr) => {
acc.add(this.fields[curr].table);
acc.add(this.fields[curr].schema);
const isImage = computed(() => {
return ['gif', 'jpg', 'png', 'bmp', 'ico', 'tif'].includes(contentInfo.value.ext);
});
const foreignKeys = computed(() => {
return props.keyUsage.map(key => key.field);
});
const isEditable = computed(() => {
if (props.elementType === 'view') return false;
if (props.fields) {
const nElements = Object.keys(props.fields).reduce((acc, curr) => {
acc.add(props.fields[curr].table);
acc.add(props.fields[curr].schema);
return acc;
}, new Set([]));
if (nElements.size > 2) return false;
return !!(this.fields[Object.keys(this.fields)[0]].schema && this.fields[Object.keys(this.fields)[0]].table);
return !!(props.fields[Object.keys(props.fields)[0]].schema && props.fields[Object.keys(props.fields)[0]].table);
}
return 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(',');
});
const isBaseSelectField = computed(() => {
return isForeignKey(editingField.value) || inputProps.value.type === 'boolean' || enumArray.value;
});
const enumArray = computed(() => {
if (props.fields[editingField.value] && props.fields[editingField.value].enumValues)
return props.fields[editingField.value].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)
this.editorMode = this.availableLanguages.find(lang => lang.id === filteredLanguages[0].languageId).slug;
})();
}
},
selected (isSelected) {
if (isSelected)
window.addEventListener('keydown', this.onKey);
else {
this.editOFF();
window.removeEventListener('keydown', this.onKey);
}
}
},
beforeUnmount () {
if (this.selected)
window.removeEventListener('keydown', this.onKey);
},
methods: {
isForeignKey (key) {
const isForeignKey = (key: string) => {
if (key) {
if (key.includes('.'))
key = key.split('.').pop();
return this.foreignKeys.includes(key);
},
isNull (value) {
return foreignKeys.value.includes(key);
}
};
const isNull = (value: null | string | number) => {
return value === null ? ' is-null' : '';
},
typeClass (type) {
};
const typeClass = (type: string) => {
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];
const type = this.fields[field].type.toUpperCase();
this.originalContent = this.typeFormat(content, type, this.fields[field].length);
this.editingType = type;
this.editingField = field;
this.editingLength = this.fields[field].length;
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)) {
this.isTextareaEditor = true;
this.editingContent = this.typeFormat(content, type);
this.$emit('start-editing', field);
isTextareaEditor.value = true;
editingContent.value = typeFormat(content, type);
emit('start-editing', field);
return;
}
if (SPATIAL.includes(type)) {
if (content) {
this.isMultiSpatial = IS_MULTI_SPATIAL.includes(type);
this.isMapModal = true;
this.editingContent = this.typeFormat(content, type);
isMultiSpatial.value = IS_MULTI_SPATIAL.includes(type);
isMapModal.value = true;
editingContent.value = typeFormat(content, type);
}
this.$emit('start-editing', field);
emit('start-editing', field);
return;
}
if (BLOB.includes(type)) {
this.isBlobEditor = true;
this.editingContent = content || '';
this.fileToUpload = null;
this.willBeDeleted = false;
isBlobEditor.value = true;
editingContent.value = content || '';
fileToUpload.value = null;
willBeDeleted.value = false;
if (content !== null) {
const buff = Buffer.from(this.editingContent);
const buff = Buffer.from(editingContent.value);
if (buff.length) {
const hex = buff.toString('hex').substring(0, 8).toUpperCase();
const { ext, mime } = mimeFromHex(hex);
this.contentInfo = {
contentInfo.value = {
ext,
mime,
size: this.editingContent.length
size: editingContent.value.length
};
}
}
this.$emit('start-editing', field);
emit('start-editing', field);
return;
}
// Inline editable fields
this.editingContent = this.originalContent;
editingContent.value = originalContent.value;
const obj = { [field]: true };
this.isInlineEditor = { ...this.isInlineEditor, ...obj };
this.$nextTick(() => { // Focus on input
document.querySelector('.editable-field').focus();
isInlineEditor.value = { ...isInlineEditor.value, ...obj };
nextTick(() => {
document.querySelector<HTMLInputElement>('.editable-field').focus();
});
this.$emit('start-editing', field);
},
editOFF () {
if (!this.editingField) return;
emit('start-editing', field);
};
this.isInlineEditor[this.editingField] = false;
const editOFF = () => {
if (!editingField.value) return;
isInlineEditor.value[editingField.value] = 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 (!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 (this.editingContent === this.typeFormat(this.originalContent, this.editingType, this.editingLength)) {
this.editingType = null;
this.editingField = null;
this.$emit('stop-editing', this.editingField);
if (editingContent.value === typeFormat(originalContent.value, editingType.value, editingLength.value)) {
editingType.value = null;
editingField.value = null;
emit('stop-editing', editingField.value);
return;
}
content = this.editingContent;
content = editingContent.value;
}
else { // Handle file upload
if (this.willBeDeleted) {
if (willBeDeleted.value) {
content = '';
this.willBeDeleted = false;
willBeDeleted.value = false;
}
else {
if (!this.fileToUpload) return;
content = this.fileToUpload.file.path;
if (!fileToUpload.value) return;
content = fileToUpload.value.file.path;
}
}
this.$emit('update-field', {
field: this.fields[this.editingField].name,
type: this.editingType,
emit('update-field', {
field: props.fields[editingField.value].name,
type: editingType.value,
content
});
this.$emit('stop-editing', this.editingField);
emit('stop-editing', editingField.value);
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 () {
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:${this.contentInfo.mime};base64, ${bufferToBase64(this.editingContent)}`;
downloadLink.setAttribute('download', `${this.editingField}.${this.contentInfo.ext}`);
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();
},
filesChange (event) {
};
const filesChange = (event: Event & {target: {files: {name: string}[]}}) => {
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 = {
fileToUpload.value = { name: files[0].name, file: files[0] };
willBeDeleted.value = false;
};
const prepareToDelete = () => {
editingContent.value = '';
contentInfo.value = {
ext: '',
mime: '',
size: null
};
this.willBeDeleted = true;
},
selectRow (event, field) {
this.$emit('select-row', event, this.row, field);
},
getKeyUsage (keyName) {
willBeDeleted.value = true;
};
const selectRow = (event: Event, field: string) => {
emit('select-row', event, props.row, field);
};
const getKeyUsage = (keyName: string) => {
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) {
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 (!this.editingField && e.key === 'Enter')
return this.editON(this.selectedCell);
if (!editingField.value && e.key === 'Enter')
return editON(props.selectedCell);
if (this.editingField && e.key === 'Enter' && !this.isBaseSelectField)
return this.editOFF();
if (editingField.value && e.key === 'Enter' && !isBaseSelectField.value)
return editOFF();
if (this.editingField && e.key === 'Escape') {
this.isInlineEditor[this.editingField] = false;
this.editingField = null;
this.$emit('stop-editing', this.editingField);
if (editingField.value && e.key === 'Escape') {
isInlineEditor.value[editingField.value] = false;
editingField.value = null;
emit('stop-editing', editingField.value);
}
},
formatBytes,
cutText (val) {
};
const cutText = (val: string) => {
if (typeof val !== 'string') return val;
return val.length > 128 ? `${val.substring(0, 128)}[...]` : val;
},
typeFormat (val, type, precision) {
};
const typeFormat = (val: string | number | Date | number[], type: string, precision?: number | false) => {
if (!val) return val;
type = type.toUpperCase();
@ -593,7 +570,7 @@ export default {
}
if (BLOB.includes(type)) {
const buff = Buffer.from(val);
const buff = Buffer.from(val as string);
if (!buff.length) return '';
const hex = buff.toString('hex').substring(0, 8).toUpperCase();
@ -601,10 +578,10 @@ export default {
}
if (BIT.includes(type)) {
if (typeof val === 'number') val = [val];
const hex = Buffer.from(val).toString('hex');
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(precision, '0');
return parseInt(bitString).toString().padStart(Number(precision), '0');
}
if (ARRAY.includes(type)) {
@ -617,9 +594,44 @@ export default {
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>
<style lang="scss">

View File

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

View File

@ -64,53 +64,47 @@
</form>
</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 { NUMBER, FLOAT } from 'common/fieldTypes';
import BaseSelect from '@/components/BaseSelect.vue';
import { TableFilterClausole } from 'common/interfaces/tableApis';
export default {
components: {
BaseSelect
},
props: {
fields: Array,
connClient: String
},
emits: ['filter-change', 'filter'],
data () {
return {
rows: [],
operators: [
const props = defineProps({
fields: Array as Prop<TableField[]>,
connClient: String as Prop<ClientCode>
});
const emit = defineEmits(['filter-change', 'filter']);
const rows = ref([]);
const operators = ref([
'=', '!=', '>', '<', '>=', '<=', '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 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 } = this.customizations;
const { elementsWrapper: ew, stringsWrapper: sw } = clientCustomizations.value;
let value;
switch (filter.op) {
@ -146,9 +140,9 @@ export default {
value = `${sw}${sw}`;
return `${ew}${filter.field}${ew} ${filter.op} ${value}`;
}
}
};
addRow();
</script>
<style lang="scss">

View File

@ -1,12 +1,20 @@
// TODO: unfinished
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) {
const tableRef = ref(null);
export function useResultTables (uid: string, reloadTable: () => void) {
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);
async function updateField (payload) {
async function updateField (payload: TableUpdateParams) {
isQuering.value = true;
const params = {
@ -20,7 +28,7 @@ export default function useResultTables (uid, reloadTable, addNotification) {
if (response.reload)// Needed for blob fields
reloadTable();
else
tableRef.value.applyUpdate(payload);
queryTable.value.applyUpdate(payload);
}
else
addNotification({ status: 'error', message: response });
@ -32,7 +40,7 @@ export default function useResultTables (uid, reloadTable, addNotification) {
isQuering.value = false;
}
async function deleteSelected (payload) {
async function deleteSelected (payload: TableDeleteParams) {
isQuering.value = true;
const params = {
@ -56,7 +64,7 @@ export default function useResultTables (uid, reloadTable, addNotification) {
}
return {
tableRef,
queryTable,
isQuering,
updateField,
deleteSelected

View File

@ -15,7 +15,7 @@ export default class {
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));
}

View File

@ -11,7 +11,7 @@ export default class {
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));
}

View File

@ -1,9 +1,9 @@
import { ipcRenderer } from 'electron';
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 {
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));
}
@ -11,7 +11,7 @@ export default class {
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));
}

View File

@ -82,7 +82,7 @@ export default class {
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));
}

View File

@ -1,6 +1,6 @@
import { ipcRenderer } from 'electron';
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 {
static getTableColumns (params: {schema: string; table: string }): Promise<IpcResponse> {
@ -27,15 +27,15 @@ export default class {
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));
}
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));
}
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));
}

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;
}
}
}
};