From 02d13ba1642ddb3555a8cea14c20397bf14c49d9 Mon Sep 17 00:00:00 2001 From: Rishichandra Wawhal Date: Fri, 10 Jan 2020 10:32:44 +0530 Subject: [PATCH] run sql queries refactor (close #3543) (#3662) --- .../src/components/Common/utils/sqlUtils.js | 7 + .../components/Common/utils/v1QueryUtils.js | 30 +- .../Services/Data/Add/AddActions.js | 18 +- .../components/Services/Data/DataActions.js | 34 +- .../Data/Function/customFunctionReducer.js | 13 +- .../Services/Data/RawSQL/Actions.js | 12 +- .../Services/Data/Schema/Actions.js | 28 +- .../Data/TableModify/ModifyActions.js | 650 ++++++------------ console/src/components/Services/Data/utils.js | 37 +- .../components/Services/EventTrigger/utils.js | 10 +- console/src/telemetry/Actions.js | 12 +- 11 files changed, 278 insertions(+), 573 deletions(-) diff --git a/console/src/components/Common/utils/sqlUtils.js b/console/src/components/Common/utils/sqlUtils.js index dc044d533e5..342d14e4e28 100644 --- a/console/src/components/Common/utils/sqlUtils.js +++ b/console/src/components/Common/utils/sqlUtils.js @@ -67,3 +67,10 @@ export const getCreatePkSql = ({ export const getDropPkSql = ({ schemaName, tableName, constraintName }) => { return `alter table "${schemaName}"."${tableName}" drop constraint "${constraintName}";`; }; + +export const terminateSql = sql => { + const sqlSanitised = sql.trim(); + return sqlSanitised[sqlSanitised.length - 1] !== ';' + ? sqlSanitised + ';' + : sqlSanitised; +}; diff --git a/console/src/components/Common/utils/v1QueryUtils.js b/console/src/components/Common/utils/v1QueryUtils.js index 8f83ec11b09..0db802bb808 100644 --- a/console/src/components/Common/utils/v1QueryUtils.js +++ b/console/src/components/Common/utils/v1QueryUtils.js @@ -1,8 +1,10 @@ +import { terminateSql } from './sqlUtils'; + export const getRunSqlQuery = (sql, shouldCascade, readOnly) => { return { type: 'run_sql', args: { - sql, + sql: terminateSql(sql), cascade: !!shouldCascade, read_only: !!readOnly, }, @@ -50,3 +52,29 @@ export const getSetCustomRootFieldsQuery = ( }, }; }; + +export const getSetTableEnumQuery = (tableDef, isEnum) => { + return { + type: 'set_table_is_enum', + args: { + table: tableDef, + is_enum: isEnum, + }, + }; +}; + +export const getTrackTableQuery = tableDef => { + return { + type: 'add_existing_table_or_view', + args: tableDef, + }; +}; + +export const getUntrackTableQuery = tableDef => { + return { + type: 'untrack_table', + args: { + table: tableDef, + }, + }; +}; diff --git a/console/src/components/Services/Data/Add/AddActions.js b/console/src/components/Services/Data/Add/AddActions.js index 48497f7dbfe..e41ee9a0052 100644 --- a/console/src/components/Services/Data/Add/AddActions.js +++ b/console/src/components/Services/Data/Add/AddActions.js @@ -11,6 +11,7 @@ import { setTable } from '../DataActions.js'; import { isPostgresFunction } from '../utils'; import { sqlEscapeText } from '../../../Common/utils/sqlUtils'; +import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils'; import { getTableModifyRoute } from '../../../Common/utils/routesUtils'; const SET_DEFAULTS = 'AddTable/SET_DEFAULTS'; @@ -315,16 +316,10 @@ const createTableSql = () => { if (hasUUIDDefault) { const sqlCreateExtension = 'CREATE EXTENSION IF NOT EXISTS pgcrypto;'; - upQueryArgs.push({ - type: 'run_sql', - args: { sql: sqlCreateExtension }, - }); + upQueryArgs.push(getRunSqlQuery(sqlCreateExtension)); } - upQueryArgs.push({ - type: 'run_sql', - args: { sql: sqlCreateTable }, - }); + upQueryArgs.push(getRunSqlQuery(sqlCreateTable)); upQueryArgs.push({ type: 'add_existing_table_or_view', @@ -345,12 +340,7 @@ const createTableSql = () => { const downQuery = { type: 'bulk', - args: [ - { - type: 'run_sql', - args: { sql: sqlDropTable }, - }, - ], + args: [getRunSqlQuery(sqlDropTable)], }; // make request diff --git a/console/src/components/Services/Data/DataActions.js b/console/src/components/Services/Data/DataActions.js index 9949803feff..9b246e2ae7f 100644 --- a/console/src/components/Services/Data/DataActions.js +++ b/console/src/components/Services/Data/DataActions.js @@ -1,6 +1,7 @@ import sanitize from 'sanitize-filename'; import { getSchemaBaseRoute } from '../../Common/utils/routesUtils'; +import { getRunSqlQuery } from '../../Common/utils/v1QueryUtils'; import Endpoints, { globalCookiePolicy } from '../../../Endpoints'; import requestAction from '../../../utils/requestAction'; import defaultState from './DataState'; @@ -547,28 +548,17 @@ const makeMigrationCall = ( }; const getBulkColumnInfoFetchQuery = schema => { - const fetchColumnTypes = { - type: 'run_sql', - args: { - sql: fetchColumnTypesQuery, - read_only: true, - }, - }; - const fetchTypeDefaultValues = { - type: 'run_sql', - args: { - sql: fetchColumnDefaultFunctions(schema), - read_only: true, - }, - }; - - const fetchValidTypeCasts = { - type: 'run_sql', - args: { - sql: fetchColumnCastsQuery, - read_only: true, - }, - }; + const fetchColumnTypes = getRunSqlQuery(fetchColumnTypesQuery, false, true); + const fetchTypeDefaultValues = getRunSqlQuery( + fetchColumnDefaultFunctions(schema), + false, + true + ); + const fetchValidTypeCasts = getRunSqlQuery( + fetchColumnCastsQuery, + false, + true + ); return { type: 'bulk', diff --git a/console/src/components/Services/Data/Function/customFunctionReducer.js b/console/src/components/Services/Data/Function/customFunctionReducer.js index 43ddaecf6bb..c62c8de804d 100644 --- a/console/src/components/Services/Data/Function/customFunctionReducer.js +++ b/console/src/components/Services/Data/Function/customFunctionReducer.js @@ -20,6 +20,7 @@ import { fetchTrackedFunctions } from '../DataActions'; import _push from '../push'; import { getSchemaBaseRoute } from '../../../Common/utils/routesUtils'; +import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils'; /* Constants */ @@ -193,19 +194,11 @@ const deleteFunctionSql = () => { const sqlDropFunction = 'DROP FUNCTION ' + functionNameWithSchema + functionArgString; - const sqlUpQueries = [ - { - type: 'run_sql', - args: { sql: sqlDropFunction }, - }, - ]; + const sqlUpQueries = [getRunSqlQuery(sqlDropFunction)]; const sqlDownQueries = []; if (functionDefinition && functionDefinition.length > 0) { - sqlDownQueries.push({ - type: 'run_sql', - args: { sql: functionDefinition }, - }); + sqlDownQueries.push(getRunSqlQuery(functionDefinition)); } // Apply migrations diff --git a/console/src/components/Services/Data/RawSQL/Actions.js b/console/src/components/Services/Data/RawSQL/Actions.js index 3037109eaf5..4074c6746da 100644 --- a/console/src/components/Services/Data/RawSQL/Actions.js +++ b/console/src/components/Services/Data/RawSQL/Actions.js @@ -16,6 +16,7 @@ import { import { parseCreateSQL } from './utils'; import dataHeaders from '../Common/Headers'; import returnMigrateUrl from '../Common/getMigrateUrl'; +import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils'; const MAKING_REQUEST = 'RawSQL/MAKING_REQUEST'; const SET_SQL = 'RawSQL/SET_SQL'; @@ -43,16 +44,7 @@ const executeSQL = (isMigration, migrationName) => (dispatch, getState) => { const isCascadeChecked = getState().rawSQL.isCascadeChecked; let url = Endpoints.rawSQL; - const schemaChangesUp = [ - { - type: 'run_sql', - args: { - sql: sql, - cascade: isCascadeChecked, - read_only: readOnlyMode, - }, - }, - ]; + const schemaChangesUp = [getRunSqlQuery(sql, isCascadeChecked, readOnlyMode)]; // check if track view enabled if (getState().rawSQL.isTableTrackChecked) { diff --git a/console/src/components/Services/Data/Schema/Actions.js b/console/src/components/Services/Data/Schema/Actions.js index 7a9f139e394..fb09fc54cc0 100644 --- a/console/src/components/Services/Data/Schema/Actions.js +++ b/console/src/components/Services/Data/Schema/Actions.js @@ -2,6 +2,7 @@ import gqlPattern, { gqlSchemaErrorNotif } from '../Common/GraphQLValidation'; import { showErrorNotification } from '../../Common/Notification'; import { makeMigrationCall, fetchSchemaList } from '../DataActions'; import { getConfirmation } from '../../../Common/utils/jsUtils'; +import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils'; const getDropSchemaSql = schemaName => `drop schema "${schemaName}" cascade;`; @@ -19,23 +20,9 @@ export const createNewSchema = (schemaName, successCb, errorCb) => { ); } - const migrationUp = [ - { - type: 'run_sql', - args: { - sql: getCreateSchemaSql(schemaName), - }, - }, - ]; + const migrationUp = [getRunSqlQuery(getCreateSchemaSql(schemaName))]; - const migrationDown = [ - { - type: 'run_sql', - args: { - sql: getDropSchemaSql(schemaName), - }, - }, - ]; + const migrationDown = [getRunSqlQuery(getDropSchemaSql(schemaName))]; const migrationName = `create_schema_${schemaName}`; const requestMsg = 'Creating schema'; @@ -86,14 +73,7 @@ export const deleteCurrentSchema = (successCb, errorCb) => { return; } - const migrationUp = [ - { - type: 'run_sql', - args: { - sql: getDropSchemaSql(currentSchema), - }, - }, - ]; + const migrationUp = [getRunSqlQuery(getDropSchemaSql(currentSchema))]; const migrationName = `drop_schema_${currentSchema}`; const requestMsg = 'Dropping schema'; const successMsg = 'Successfully dropped schema'; diff --git a/console/src/components/Services/Data/TableModify/ModifyActions.js b/console/src/components/Services/Data/TableModify/ModifyActions.js index 2adfd2a0bed..7442f728518 100644 --- a/console/src/components/Services/Data/TableModify/ModifyActions.js +++ b/console/src/components/Services/Data/TableModify/ModifyActions.js @@ -47,6 +47,9 @@ import { import { getSetCustomRootFieldsQuery, getRunSqlQuery, + getSetTableEnumQuery, + getUntrackTableQuery, + getTrackTableQuery, } from '../../../Common/utils/v1QueryUtils'; import { @@ -239,20 +242,17 @@ export const removeCheckConstraint = (constraintName, successCb, errorCb) => ( constraintName ); - const upQuery = { - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${constraintName}"`, - }, - }; - const downQuery = { - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" add constraint "${constraintName}" ${ - constraint.check - };`, - }, - }; + const upQuery = getRunSqlQuery( + getDropConstraintSql(tableName, currentSchema, constraintName) + ); + const downQuery = getRunSqlQuery( + getCreateCheckConstraintSql( + tableName, + currentSchema, + constraintName, + constraint.check + ) + ); const migrationName = `drop_check_constraint_${currentSchema}_${tableName}_${constraintName}`; const requestMsg = 'Deleting check constraint...'; @@ -269,7 +269,6 @@ export const removeCheckConstraint = (constraintName, successCb, errorCb) => ( } dispatch({ type: UPDATE_MIGRATION_STATUS_ERROR, data: err }); }; - makeMigrationCall( dispatch, getState, @@ -326,54 +325,50 @@ const savePrimaryKeys = (tableName, schemaName, constraintName) => { const migrationUp = []; // skip dropping existing constraint if there is none if (constraintName) { - migrationUp.push({ - type: 'run_sql', - args: { - sql: getDropPkSql({ schemaName, tableName, constraintName }), - }, - }); + migrationUp.push( + getRunSqlQuery(getDropPkSql({ schemaName, tableName, constraintName })) + ); } // skip creating a new config if no columns were selected if (numSelectedPkColumns) { - migrationUp.push({ - type: 'run_sql', - args: { - sql: getCreatePkSql({ + migrationUp.push( + getRunSqlQuery( + getCreatePkSql({ schemaName, tableName, selectedPkColumns, constraintName: `${tableName}_pkey`, - }), - }, - }); + }) + ) + ); } const migrationDown = []; // skip dropping in down migration if no constraint was created if (numSelectedPkColumns) { - migrationDown.push({ - type: 'run_sql', - args: { - sql: getDropPkSql({ + migrationDown.push( + getRunSqlQuery( + getDropPkSql({ schemaName, tableName, constraintName: `${tableName}_pkey`, - }), - }, - }); + }) + ) + ); } // skip creating in down migration if no constraint was dropped in up migration if (constraintName) { - migrationDown.push({ - type: 'run_sql', - sql: getCreatePkSql({ - schemaName, - tableName, - selectedPkColumns: tableSchema.primary_key.columns, - constraintName, - }), - }); + migrationDown.push( + getRunSqlQuery( + getCreatePkSql({ + schemaName, + tableName, + selectedPkColumns: tableSchema.primary_key.columns, + constraintName, + }) + ) + ); } const pkAction = numSelectedPkColumns ? 'Updating' : 'Deleting'; @@ -454,13 +449,7 @@ const saveForeignKeys = (index, tableSchema, columns) => { references "${refSchemaName}"."${refTableName}" (${rcols.join(', ')}) on update ${onUpdate} on delete ${onDelete}; `; - - migrationUp.push({ - type: 'run_sql', - args: { - sql: migrationUpAlterFKeySql, - }, - }); + migrationUp.push(getRunSqlQuery(migrationUpAlterFKeySql)); } else { // foreign key not found, create a new one const migrationUpCreateFKeySql = ` @@ -471,12 +460,7 @@ const saveForeignKeys = (index, tableSchema, columns) => { (${rcols.join(', ')}) on update ${onUpdate} on delete ${onDelete}; `; - migrationUp.push({ - type: 'run_sql', - args: { - sql: migrationUpCreateFKeySql, - }, - }); + migrationUp.push(getRunSqlQuery(migrationUpCreateFKeySql)); } const migrationDown = []; @@ -500,24 +484,14 @@ const saveForeignKeys = (index, tableSchema, columns) => { on delete ${pgConfTypes[oldConstraint.on_delete]}; `; - migrationDown.push({ - type: 'run_sql', - args: { - sql: migrationDownAlterFKeySql, - }, - }); + migrationDown.push(getRunSqlQuery(migrationDownAlterFKeySql)); } else { // when foreign key is created const migrationDownDeleteFKeySql = ` alter table "${schemaName}"."${tableName}" drop constraint "${generatedConstraintName}" `; - migrationDown.push({ - type: 'run_sql', - args: { - sql: migrationDownDeleteFKeySql, - }, - }); + migrationDown.push(getRunSqlQuery(migrationDownDeleteFKeySql)); } const migrationName = `set_fk_${schemaName}_${tableName}_${lcols.join( @@ -576,36 +550,22 @@ const removeForeignKey = (index, tableSchema) => { const tableName = tableSchema.table_name; const schemaName = tableSchema.table_schema; const oldConstraint = tableSchema.foreign_key_constraints[index]; - const migrationUp = [ - { - type: 'run_sql', - args: { - sql: `alter table "${schemaName}"."${tableName}" drop constraint "${ - oldConstraint.constraint_name - }";`, - }, - }, - ]; - const migrationDown = [ - { - type: 'run_sql', - args: { - sql: `alter table "${schemaName}"."${tableName}" add foreign key (${Object.keys( - oldConstraint.column_mapping - ) - .map(lc => `"${lc}"`) - .join(', ')}) references "${ - oldConstraint.ref_table_table_schema - }"."${oldConstraint.ref_table}"(${Object.values( - oldConstraint.column_mapping - ) - .map(rc => `"${rc}"`) - .join(', ')}) on update ${ - pgConfTypes[oldConstraint.on_update] - } on delete ${pgConfTypes[oldConstraint.on_delete]};`, - }, - }, - ]; + const upSql = `alter table "${schemaName}"."${tableName}" drop constraint "${ + oldConstraint.constraint_name + }";`; + const downSql = `alter table "${schemaName}"."${tableName}" add foreign key (${Object.keys( + oldConstraint.column_mapping + ) + .map(lc => `"${lc}"`) + .join(', ')}) references "${oldConstraint.ref_table_table_schema}"."${ + oldConstraint.ref_table + }"(${Object.values(oldConstraint.column_mapping) + .map(rc => `"${rc}"`) + .join(', ')}) on update ${ + pgConfTypes[oldConstraint.on_update] + } on delete ${pgConfTypes[oldConstraint.on_delete]};`; + const migrationUp = [getRunSqlQuery(upSql)]; + const migrationDown = [getRunSqlQuery(downSql)]; const migrationName = `delete_fk_${schemaName}_${tableName}_${ oldConstraint.constraint_name }`; @@ -673,22 +633,10 @@ const changeTableName = (oldName, newName, isTable) => { ); } const currentSchema = getState().tables.currentSchema; - const migrateUp = [ - { - type: 'run_sql', - args: { - sql: `alter ${property} "${currentSchema}"."${oldName}" rename to "${newName}";`, - }, - }, - ]; - const migrateDown = [ - { - type: 'run_sql', - args: { - sql: `alter ${property} "${currentSchema}"."${newName}" rename to "${oldName}";`, - }, - }, - ]; + const upSql = `alter ${property} "${currentSchema}"."${oldName}" rename to "${newName}";`; + const downSql = `alter ${property} "${currentSchema}"."${newName}" rename to "${oldName}";`; + const migrateUp = [getRunSqlQuery(upSql)]; + const migrateDown = [getRunSqlQuery(downSql)]; // apply migrations const migrationName = `rename_${property}_` + currentSchema + '_' + oldName; @@ -730,14 +678,7 @@ const deleteTrigger = (trigger, table) => { const upMigrationSql = `DROP TRIGGER "${triggerName}" ON "${tableSchema}"."${tableName}";`; - const migrationUp = [ - { - type: 'run_sql', - args: { - sql: upMigrationSql, - }, - }, - ]; + const migrationUp = [getRunSqlQuery(upMigrationSql)]; let downMigrationSql = ''; @@ -751,14 +692,7 @@ FOR EACH ${trigger.action_orientation} ${trigger.action_statement};`; downMigrationSql += `COMMENT ON TRIGGER "${triggerName}" ON "${tableSchema}"."${tableName}" IS ${sqlEscapeText(trigger.comment)};`; } - const migrationDown = [ - { - type: 'run_sql', - args: { - sql: downMigrationSql, - }, - }, - ]; + const migrationDown = [getRunSqlQuery(downMigrationSql)]; const migrationName = `delete_trigger_${triggerSchema}_${triggerName}`; @@ -792,20 +726,7 @@ const deleteTableSql = tableName => { // handle no primary key const sqlDropTable = 'DROP TABLE ' + '"' + currentSchema + '"' + '.' + '"' + tableName + '"'; - const sqlUpQueries = [ - { - type: 'run_sql', - args: { sql: sqlDropTable }, - }, - ]; - // const sqlCreateTable = 'CREATE TABLE ' + '"' + tableName + '"' + '(' + tableColumns + ')'; - // const sqlDownQueries = [ - // { - // type: 'run_sql', - // args: { 'sql': sqlCreateTable } - // } - // ]; - + const sqlUpQueries = [getRunSqlQuery(sqlDropTable)]; // apply migrations const migrationName = 'drop_table_' + currentSchema + '_' + tableName; @@ -842,26 +763,9 @@ const deleteTableSql = tableName => { const untrackTableSql = tableName => { return (dispatch, getState) => { const currentSchema = getState().tables.currentSchema; - const upQueries = [ - { - type: 'untrack_table', - args: { - table: { - name: tableName.trim(), - schema: currentSchema, - }, - }, - }, - ]; - const downQueries = [ - { - type: 'add_existing_table_or_view', - args: { - name: tableName.trim(), - schema: currentSchema, - }, - }, - ]; + const tableDef = generateTableDef(tableName, currentSchema); + const upQueries = [getUntrackTableQuery(tableDef)]; + const downQueries = [getTrackTableQuery(tableDef)]; // apply migrations const migrationName = 'untrack_table_' + currentSchema + '_' + tableName; @@ -931,13 +835,7 @@ const fetchViewDefinition = (viewName, isRedirect) => { "'" + viewName + "'"; - const reqBody = { - type: 'run_sql', - args: { - sql: sqlQuery, - read_only: true, - }, - }; + const reqBody = getRunSqlQuery(sqlQuery, false, true); const url = Endpoints.query; const options = { @@ -988,12 +886,7 @@ const deleteViewSql = viewName => { const currentSchema = getState().tables.currentSchema; const sqlDropView = 'DROP VIEW ' + '"' + currentSchema + '"' + '.' + '"' + viewName + '"'; - const sqlUpQueries = [ - { - type: 'run_sql', - args: { sql: sqlDropView }, - }, - ]; + const sqlUpQueries = [getRunSqlQuery(sqlDropView)]; // const sqlCreateView = ''; //pending // const sqlDownQueries = [ // { @@ -1056,48 +949,30 @@ const deleteColumnSql = (column, tableSchema) => { 'ALTER TABLE ' + '"' + currentSchema + '"' + '.' + '"' + tableName + '" '; const schemaChangesUp = [ - { - type: 'run_sql', - args: { - sql: alterStatement + 'DROP COLUMN ' + '"' + name + '" CASCADE', - }, - }, + getRunSqlQuery( + alterStatement + 'DROP COLUMN ' + '"' + name + '" CASCADE' + ), ]; const schemaChangesDown = []; - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: alterStatement + 'ADD COLUMN ' + '"' + name + '"' + ' ' + col_type, - }, - }); + schemaChangesDown.push( + getRunSqlQuery( + alterStatement + 'ADD COLUMN ' + '"' + name + '"' + ' ' + col_type + ) + ); if (is_nullable) { - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: - alterStatement + - 'ALTER COLUMN ' + - '"' + - name + - '" ' + - 'DROP NOT NULL', - }, - }); + schemaChangesDown.push( + getRunSqlQuery( + alterStatement + 'ALTER COLUMN ' + '"' + name + '" ' + 'DROP NOT NULL' + ) + ); } else { - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: - alterStatement + - 'ALTER COLUMN ' + - '"' + - name + - '" ' + - 'SET NOT NULL', - }, - }); + schemaChangesDown.push( + getRunSqlQuery( + alterStatement + 'ALTER COLUMN ' + '"' + name + '" ' + 'SET NOT NULL' + ) + ); } const merged_fkc = foreign_key_constraints.concat( @@ -1110,11 +985,9 @@ const deleteColumnSql = (column, tableSchema) => { const rcol = Object.values(fkc.column_mapping); const onUpdate = pgConfTypes[fkc.on_update]; const onDelete = pgConfTypes[fkc.on_delete]; - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: - alterStatement + + schemaChangesDown.push( + getRunSqlQuery( + alterStatement + 'ADD CONSTRAINT ' + `${fkc.constraint_name} ` + 'FOREIGN KEY ' + @@ -1123,51 +996,45 @@ const deleteColumnSql = (column, tableSchema) => { `"${fkc.ref_table_table_schema}"."${fkc.ref_table}" ` + `(${rcol.join(', ')}) ` + `ON DELETE ${onDelete} ` + - `ON UPDATE ${onUpdate}`, - }, - }); + `ON UPDATE ${onUpdate}` + ) + ); }); } if (unique_constraints.length > 0) { unique_constraints.forEach(uc => { // add unique constraint to down migration - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: - alterStatement + + schemaChangesDown.push( + getRunSqlQuery( + alterStatement + 'ADD CONSTRAINT ' + `${uc.constraint_name} ` + 'UNIQUE ' + - `(${uc.columns.join(', ')})`, - }, - }); + `(${uc.columns.join(', ')})` + ) + ); }); } if (column.column_default !== null) { // add column default to down migration - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: - alterStatement + + schemaChangesDown.push( + getRunSqlQuery( + alterStatement + 'ALTER COLUMN ' + `"${name}" ` + 'SET DEFAULT ' + - column.column_default, - }, - }); + column.column_default + ) + ); } // COMMENT ON COLUMN my_table.my_column IS 'Employee ID number'; if (comment) { - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: - 'COMMENT ON COLUMN ' + + schemaChangesDown.push( + getRunSqlQuery( + 'COMMENT ON COLUMN ' + '"' + currentSchema + '"' + @@ -1181,9 +1048,9 @@ const deleteColumnSql = (column, tableSchema) => { '"' + ' ' + 'IS ' + - sqlEscapeText(comment), - }, - }); + sqlEscapeText(comment) + ) + ); } // Apply migrations @@ -1294,20 +1161,12 @@ const addColSql = ( const schemaChangesUp = []; if (colType === 'uuid' && colDefault !== '') { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: 'CREATE EXTENSION IF NOT EXISTS pgcrypto;', - }, - }); + schemaChangesUp.push( + getRunSqlQuery('CREATE EXTENSION IF NOT EXISTS pgcrypto;') + ); } - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: runSqlQueryUp, - }, - }); + schemaChangesUp.push(getRunSqlQuery(runSqlQueryUp)); let runSqlQueryDown = ''; @@ -1330,14 +1189,7 @@ const addColSql = ( colName + '";'; - const schemaChangesDown = [ - { - type: 'run_sql', - args: { - sql: runSqlQueryDown, - }, - }, - ]; + const schemaChangesDown = [getRunSqlQuery(runSqlQueryDown)]; // Apply migrations const migrationName = @@ -1397,14 +1249,7 @@ const deleteConstraintSql = (tableName, cName) => { '"' + cName + '"'; - const schemaChangesUp = [ - { - type: 'run_sql', - args: { - sql: dropContraintQuery, - }, - }, - ]; + const schemaChangesUp = [getRunSqlQuery(dropContraintQuery)]; // pending const schemaChangesDown = []; @@ -1462,22 +1307,8 @@ const saveTableCommentSql = isTable => { : commentQueryBase + sqlEscapeText(updatedComment); const commentDownQuery = commentQueryBase + 'NULL'; - const schemaChangesUp = [ - { - type: 'run_sql', - args: { - sql: commentUpQuery, - }, - }, - ]; - const schemaChangesDown = [ - { - type: 'run_sql', - args: { - sql: commentDownQuery, - }, - }, - ]; + const schemaChangesUp = [getRunSqlQuery(commentUpQuery)]; + const schemaChangesDown = [getRunSqlQuery(commentDownQuery)]; // Apply migrations const migrationName = @@ -1595,26 +1426,10 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { column.data_type + ';'; const schemaChangesUp = - originalColType !== colType - ? [ - { - type: 'run_sql', - args: { - sql: columnChangesUpQuery, - }, - }, - ] - : []; + originalColType !== colType ? [getRunSqlQuery(columnChangesUpQuery)] : []; const schemaChangesDown = originalColType !== colType - ? [ - { - type: 'run_sql', - args: { - sql: columnChangesDownQuery, - }, - }, - ] + ? [getRunSqlQuery(columnChangesDownQuery)] : []; /* column custom field up/down migration*/ @@ -1735,18 +1550,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { // check if default is unchanged and then do a drop. if not skip if (originalColDefault !== colDefault) { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: columnDefaultUpQuery, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: columnDefaultDownQuery, - }, - }); + schemaChangesUp.push(getRunSqlQuery(columnDefaultUpQuery)); + schemaChangesDown.push(getRunSqlQuery(columnDefaultDownQuery)); } /* column nullable up/down migration */ @@ -1782,18 +1587,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { ' SET NOT NULL;'; // check with original null if (originalColNullable !== 'YES') { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: nullableUpQuery, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: nullableDownQuery, - }, - }); + schemaChangesUp.push(getRunSqlQuery(nullableUpQuery)); + schemaChangesDown.push(getRunSqlQuery(nullableDownQuery)); } } else { // ALTER TABLE ALTER COLUMN SET NOT NULL; @@ -1827,18 +1622,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { ' DROP NOT NULL;'; // check with original null if (originalColNullable !== 'NO') { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: nullableUpQuery, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: nullableDownQuery, - }, - }); + schemaChangesUp.push(getRunSqlQuery(nullableUpQuery)); + schemaChangesDown.push(getRunSqlQuery(nullableDownQuery)); } } @@ -1880,18 +1665,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { '_key"'; // check with original unique if (!originalColUnique) { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: uniqueUpQuery, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: uniqueDownQuery, - }, - }); + schemaChangesUp.push(getRunSqlQuery(uniqueUpQuery)); + schemaChangesDown.push(getRunSqlQuery(uniqueDownQuery)); } } else { const uniqueDownQuery = @@ -1930,18 +1705,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { '_key"'; // check with original unique if (originalColUnique) { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: uniqueUpQuery, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: uniqueDownQuery, - }, - }); + schemaChangesUp.push(getRunSqlQuery(uniqueUpQuery)); + schemaChangesDown.push(getRunSqlQuery(uniqueDownQuery)); } } @@ -1980,18 +1745,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { // check if comment is unchanged and then do an update. if not skip if (originalColComment !== comment) { - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: columnCommentUpQuery, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: columnCommentDownQuery, - }, - }); + schemaChangesUp.push(getRunSqlQuery(columnCommentUpQuery)); + schemaChangesDown.push(getRunSqlQuery(columnCommentDownQuery)); } /* rename column */ @@ -2005,18 +1760,16 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { ) ); } - schemaChangesUp.push({ - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" rename column "${colName}" to "${newName}";`, - }, - }); - schemaChangesDown.push({ - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" rename column "${newName}" to "${colName}";`, - }, - }); + schemaChangesUp.push( + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" rename column "${colName}" to "${newName}";` + ) + ); + schemaChangesDown.push( + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" rename column "${newName}" to "${colName}";` + ) + ); } // Apply migrations @@ -2064,12 +1817,7 @@ const saveColumnChangesSql = (colName, column, onSuccess) => { const fetchColumnCasts = () => { return (dispatch, getState) => { const url = Endpoints.getSchema; - const reqQuery = { - type: 'run_sql', - args: { - sql: fetchColumnCastsQuery, - }, - }; + const reqQuery = getRunSqlQuery(fetchColumnCastsQuery); const options = { credentials: globalCookiePolicy, method: 'POST', @@ -2108,29 +1856,23 @@ const removeUniqueKey = (index, tableName, existingConstraints, callback) => { // Up migration: Drop the constraint const sqlUp = [ - { - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${ - existingConstraint.constraint_name - }";`, - }, - }, + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" drop constraint "${ + existingConstraint.constraint_name + }";` + ), ]; // Down Migration: Create the constraint that is being dropped const sqlDown = [ - { - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( - tableName, - existingConstraint.columns - )}" unique (${existingConstraint.columns - .map(c => `"${c}"`) - .join(', ')});`, - }, - }, + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( + tableName, + existingConstraint.columns + )}" unique (${existingConstraint.columns + .map(c => `"${c}"`) + .join(', ')});` + ), ]; const migrationName = @@ -2195,19 +1937,15 @@ export const toggleTableAsEnum = (isEnum, successCallback, failureCallback) => ( const { currentTable, currentSchema } = getState().tables; const { allSchemas } = getState().tables; - const getEnumQuery = is_enum => ({ - type: 'set_table_is_enum', - args: { - table: { - schema: currentSchema, - name: currentTable, - }, - is_enum, - }, - }); - - const upQuery = [getEnumQuery(!isEnum)]; - const downQuery = [getEnumQuery(isEnum)]; + const upQuery = [ + getSetTableEnumQuery( + generateTableDef(currentTable, currentSchema), + !isEnum + ), + ]; + const downQuery = [ + getSetTableEnumQuery(generateTableDef(currentTable, currentSchema), isEnum), + ]; const migrationName = 'alter_table_' + @@ -2392,54 +2130,50 @@ const saveUniqueKey = ( // Down migration const downMigration = []; // drop the newly created constraint - downMigration.push({ - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${getUniqueConstraintName( + downMigration.push( + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" drop constraint "${getUniqueConstraintName( tableName, columns - )}";`, - }, - }); + )}";` + ) + ); // if any constraint is being dropped, create it back if (index < numUniqueKeys - 1) { - downMigration.push({ - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( + downMigration.push( + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( tableName, existingConstraint.columns )}" unique (${existingConstraint.columns .map(c => `"${c}"`) - .join(', ')});`, - }, - }); + .join(', ')});` + ) + ); } // up migration const upMigration = []; // drop the old constraint if there is any if (index < numUniqueKeys - 1) { - upMigration.push({ - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${ + upMigration.push( + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" drop constraint "${ existingConstraint.constraint_name - }";`, - }, - }); + }";` + ) + ); } // create the new constraint - upMigration.push({ - type: 'run_sql', - args: { - sql: `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( + upMigration.push( + getRunSqlQuery( + `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( tableName, columns - )}" unique (${columns.map(c => `"${c}"`).join(', ')});`, - }, - }); + )}" unique (${columns.map(c => `"${c}"`).join(', ')});` + ) + ); const migrationName = 'alter_table_' + diff --git a/console/src/components/Services/Data/utils.js b/console/src/components/Services/Data/utils.js index 657d0687ed2..14808883263 100644 --- a/console/src/components/Services/Data/utils.js +++ b/console/src/components/Services/Data/utils.js @@ -2,6 +2,7 @@ import { READ_ONLY_RUN_SQL_QUERIES, checkFeatureSupport, } from '../../../helpers/versionUtils'; +import { getRunSqlQuery } from '../../Common/utils/v1QueryUtils'; export const INTEGER = 'integer'; export const SERIAL = 'serial'; @@ -329,13 +330,11 @@ FROM ${whereQuery} ) as info `; - return { - type: 'run_sql', - args: { - sql: runSql, - read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false, - }, - }; + return getRunSqlQuery( + runSql, + false, + checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false + ); }; export const fetchTrackedTableReferencedFkQuery = options => { @@ -365,13 +364,11 @@ FROM ${whereQuery} ) as info `; - return { - type: 'run_sql', - args: { - sql: runSql, - read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false, - }, - }; + return getRunSqlQuery( + runSql, + false, + checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false + ); }; export const fetchTableListQuery = options => { @@ -444,13 +441,11 @@ FROM is_views.* ) AS info `; - return { - type: 'run_sql', - args: { - sql: runSql, - read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false, - }, - }; + return getRunSqlQuery( + runSql, + false, + checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false + ); }; export const mergeLoadSchemaData = ( diff --git a/console/src/components/Services/EventTrigger/utils.js b/console/src/components/Services/EventTrigger/utils.js index 0d39bac6d90..7689efb1a79 100644 --- a/console/src/components/Services/EventTrigger/utils.js +++ b/console/src/components/Services/EventTrigger/utils.js @@ -1,3 +1,5 @@ +import { getRunSqlQuery } from '../../Common/utils/v1QueryUtils'; + // check 2xx success status codes export const verifySuccessStatus = status => { return /^2[0-9][0-9]$/.test(status.toString()); @@ -136,13 +138,7 @@ FROM hdb_et.name ASC NULLS LAST ) AS info `; - return { - type: 'run_sql', - args: { - sql: runSql, - read_only: true, - }, - }; + return getRunSqlQuery(runSql, false, true); }; export const parseRowData = (row, dataType) => { diff --git a/console/src/telemetry/Actions.js b/console/src/telemetry/Actions.js index 007b4a7897e..00344da7f9c 100644 --- a/console/src/telemetry/Actions.js +++ b/console/src/telemetry/Actions.js @@ -3,6 +3,7 @@ import requestAction from '../utils/requestAction'; import dataHeaders from '../components/Services/Data/Common/Headers'; import defaultTelemetryState from './State'; import globals from '../Globals'; +import { getRunSqlQuery } from '../components/Common/utils/v1QueryUtils'; const SET_CONSOLE_OPTS = 'Telemetry/SET_CONSOLE_OPTS'; const SET_NOTIFICATION_SHOWN = 'Telemetry/SET_NOTIFICATION_SHOWN'; @@ -20,12 +21,11 @@ const setNotificationShownInDB = () => (dispatch, getState) => { credentials: globalCookiePolicy, method: 'POST', headers: dataHeaders(getState), - body: JSON.stringify({ - type: 'run_sql', - args: { - sql: `update hdb_catalog.hdb_version set console_state = console_state || jsonb_build_object('telemetryNotificationShown', true) where hasura_uuid='${uuid}';`, - }, - }), + body: JSON.stringify( + getRunSqlQuery( + `update hdb_catalog.hdb_version set console_state = console_state || jsonb_build_object('telemetryNotificationShown', true) where hasura_uuid='${uuid}';` + ) + ), }; return dispatch(requestAction(url, options)).then( data => {