0
1
Fork 0

improvements

This commit is contained in:
William Buezas 2024-07-22 13:51:54 -03:00
parent dcbc154caa
commit 07c5f64265
3 changed files with 80 additions and 53 deletions

View File

@ -3,6 +3,10 @@ import { ref, inject, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
import {
generateUpdateSqlQuery,
generateInsertSqlQuery
} from 'src/js/db/sqlService.js';
const props = defineProps({ const props = defineProps({
title: { title: {
@ -17,9 +21,11 @@ const props = defineProps({
type: String, type: String,
default: '' default: ''
}, },
// Objeto que define las pks de la tabla. Usado para generar las queries sql correspondientes.
// Debe ser definido como un objeto de pares key-value, donde la clave es el nombre de la columna de la pk.
pks: { pks: {
type: Object, type: Object,
default: () => {} // definidas como key: value, donde key es el nombre de la pk default: () => {}
}, },
createModelDefault: { createModelDefault: {
type: Object, type: Object,
@ -28,29 +34,33 @@ const props = defineProps({
value: '' value: ''
}) })
}, },
// Objeto que contiene la consulta SQL y los parámetros necesarios para obtener los datos iniciales del formulario.
// `query` debe ser una cadena de texto que representa la consulta SQL.
// `params` es un objeto que mapea los parámetros de la consulta a sus valores.
fetchFormDataSql: { fetchFormDataSql: {
type: Object, type: Object,
default: () => ({ default: () => ({
// Objeto con query y params para obtener los datos iniciales del form
query: '', query: '',
params: {} params: {}
}) })
}, },
// Objeto con los datos iniciales del form, si este objeto es definido, no se ejecuta la query fetchFormDataSql
formInitialData: { formInitialData: {
type: Object, type: Object,
default: () => {} // Objeto con los datos iniciales del form default: () => {}
}, },
// Array de columnas que no se deben actualizar
columnsToIgnoreUpdate: { columnsToIgnoreUpdate: {
type: Array, type: Array,
default: () => [] // Array de columnas que no se deben actualizar default: () => []
}, },
autoLoad: { autoLoad: {
type: Boolean, type: Boolean,
default: true default: true
}, },
mode: { isEditMode: {
type: String, type: Boolean,
default: 'update' default: true
}, },
defaultActions: { defaultActions: {
type: Boolean, type: Boolean,
@ -73,7 +83,7 @@ const tableColumns = computed(
() => modelInfo.value?.columns.map(col => col.name) || [] () => modelInfo.value?.columns.map(col => col.name) || []
); );
// Array de nombre de columnas que fueron actualizadas y no estan en columnsToIgnoreUpdate // Array de nombre de columnas que fueron actualizadas y no estan en columnsToIgnoreUpdate
const columnsUpdated = computed(() => { const updatedColumns = computed(() => {
return tableColumns.value.filter( return tableColumns.value.filter(
colName => colName =>
modelInfo.value?.data[0][colName] !== formData.value[colName] && modelInfo.value?.data[0][colName] !== formData.value[colName] &&
@ -106,7 +116,7 @@ const fetchFormData = async () => {
const submit = async () => { const submit = async () => {
try { try {
const sqlQuery = generateSqlQuery(props.table, props.schema, props.pks); const sqlQuery = generateSqlQuery();
await jApi.execQuery(sqlQuery, props.pks); await jApi.execQuery(sqlQuery, props.pks);
emit('onDataSaved'); emit('onDataSaved');
notify(t('dataSaved'), 'positive'); notify(t('dataSaved'), 'positive');
@ -116,51 +126,26 @@ const submit = async () => {
} }
}; };
const generateSqlQuery = (table, schema, pks) => { const generateSqlQuery = () => {
if (props.mode === 'update') { if (props.isEditMode) {
return generateUpdateSqlQuery(table, schema, pks); return generateUpdateSqlQuery(
props.schema,
props.table,
props.pks,
updatedColumns.value,
formData.value
);
} else { } else {
return generateCreateSqlQuery(table, schema, pks); return generateInsertSqlQuery(
props.schema,
props.table,
formData.value,
updatedColumns.value,
props.createModelDefault
);
} }
}; };
const generateUpdateSqlQuery = (table, schema, pks) => {
if (!columnsUpdated.value.length) return '';
const setClauses = columnsUpdated.value
.map(colName => `${colName} = '${formData.value[colName]}'`)
.join(', ');
const whereClause = Object.keys(props.pks)
.map(pk => `${pk} = ${pks[pk]}`)
.join(' AND ');
return `
START TRANSACTION;
UPDATE ${schema}.${table} SET ${setClauses} WHERE (${whereClause});
SELECT ${columnsUpdated.value.join(', ')} FROM ${schema}.${table} WHERE (${whereClause});
COMMIT;
`;
};
const generateCreateSqlQuery = (table, schema) => {
if (!columnsUpdated.value.length) return '';
const columns = [
props.createModelDefault.field,
...columnsUpdated.value
].join(', ');
const values = [
props.createModelDefault.value,
...columnsUpdated.value.map(colName => `'${formData.value[colName]}'`)
].join(', ');
return `
START TRANSACTION;
INSERT INTO ${schema}.${table} (${columns}) VALUES (${values});
SELECT id, ${columnsUpdated.value.join(', ')} FROM ${schema}.${table} WHERE ((id = LAST_INSERT_ID()));
COMMIT;
`;
};
onMounted(async () => { onMounted(async () => {
if (!props.formInitialData && props.autoLoad) { if (!props.formInitialData && props.autoLoad) {
fetchFormData(); fetchFormData();
@ -182,7 +167,7 @@ defineExpose({
icon="check" icon="check"
rounded rounded
no-caps no-caps
:disabled="!columnsUpdated.length" :disabled="!updatedColumns.length"
@click="addressFormRef.submit()" @click="addressFormRef.submit()"
/> />
</Teleport> </Teleport>

42
src/js/db/sqlService.js Normal file
View File

@ -0,0 +1,42 @@
export const generateUpdateSqlQuery = (
schema,
table,
pks,
columnsUpdated,
formData
) => {
const setClauses = columnsUpdated
.map(colName => `${colName} = '${formData[colName]}'`)
.join(', ');
const whereClause = Object.keys(pks)
.map(pk => `${pk} = ${pks[pk]}`)
.join(' AND ');
return `
START TRANSACTION;
UPDATE ${schema}.${table} SET ${setClauses} WHERE (${whereClause});
SELECT ${columnsUpdated.join(', ')} FROM ${schema}.${table} WHERE (${whereClause});
COMMIT;
`;
};
export const generateInsertSqlQuery = (
schema,
table,
formData,
columnsUpdated,
createModelDefault
) => {
const columns = [createModelDefault.field, ...columnsUpdated].join(', ');
const values = [
createModelDefault.value,
...columnsUpdated.map(colName => `'${formData[colName]}'`)
].join(', ');
return `
START TRANSACTION;
INSERT INTO ${schema}.${table} (${columns}) VALUES (${values});
SELECT id, ${columnsUpdated.join(', ')} FROM ${schema}.${table} WHERE (id = LAST_INSERT_ID());
COMMIT;
`;
};

View File

@ -16,7 +16,7 @@ const vnFormRef = ref(null);
const countriesOptions = ref([]); const countriesOptions = ref([]);
const provincesOptions = ref([]); const provincesOptions = ref([]);
const pks = { id: route.params.id }; const pks = { id: route.params.id };
const formMode = route.params.id === '0' ? 'create' : 'update'; const isEditMode = route.params.id !== '0';
const fetchAddressDataSql = { const fetchAddressDataSql = {
query: ` query: `
SELECT a.id, a.street, a.nickname, a.city, a.postalCode, a.provinceFk, p.countryFk SELECT a.id, a.street, a.nickname, a.city, a.postalCode, a.provinceFk, p.countryFk
@ -74,7 +74,7 @@ onMounted(() => getCountries());
value: 'account.myUser_getId()' value: 'account.myUser_getId()'
}" }"
:pks="pks" :pks="pks"
:mode="formMode" :isEditMode="isEditMode"
:title="t('addEditAddress')" :title="t('addEditAddress')"
table="myAddress" table="myAddress"
schema="hedera" schema="hedera"