run sql queries refactor (close #3543) (#3662)

This commit is contained in:
Rishichandra Wawhal 2020-01-10 10:32:44 +05:30 committed by Rikin Kachhia
parent 6a4d643c8d
commit 02d13ba164
11 changed files with 278 additions and 573 deletions

View File

@ -67,3 +67,10 @@ export const getCreatePkSql = ({
export const getDropPkSql = ({ schemaName, tableName, constraintName }) => { export const getDropPkSql = ({ schemaName, tableName, constraintName }) => {
return `alter table "${schemaName}"."${tableName}" drop constraint "${constraintName}";`; return `alter table "${schemaName}"."${tableName}" drop constraint "${constraintName}";`;
}; };
export const terminateSql = sql => {
const sqlSanitised = sql.trim();
return sqlSanitised[sqlSanitised.length - 1] !== ';'
? sqlSanitised + ';'
: sqlSanitised;
};

View File

@ -1,8 +1,10 @@
import { terminateSql } from './sqlUtils';
export const getRunSqlQuery = (sql, shouldCascade, readOnly) => { export const getRunSqlQuery = (sql, shouldCascade, readOnly) => {
return { return {
type: 'run_sql', type: 'run_sql',
args: { args: {
sql, sql: terminateSql(sql),
cascade: !!shouldCascade, cascade: !!shouldCascade,
read_only: !!readOnly, 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,
},
};
};

View File

@ -11,6 +11,7 @@ import { setTable } from '../DataActions.js';
import { isPostgresFunction } from '../utils'; import { isPostgresFunction } from '../utils';
import { sqlEscapeText } from '../../../Common/utils/sqlUtils'; import { sqlEscapeText } from '../../../Common/utils/sqlUtils';
import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils';
import { getTableModifyRoute } from '../../../Common/utils/routesUtils'; import { getTableModifyRoute } from '../../../Common/utils/routesUtils';
const SET_DEFAULTS = 'AddTable/SET_DEFAULTS'; const SET_DEFAULTS = 'AddTable/SET_DEFAULTS';
@ -315,16 +316,10 @@ const createTableSql = () => {
if (hasUUIDDefault) { if (hasUUIDDefault) {
const sqlCreateExtension = 'CREATE EXTENSION IF NOT EXISTS pgcrypto;'; const sqlCreateExtension = 'CREATE EXTENSION IF NOT EXISTS pgcrypto;';
upQueryArgs.push({ upQueryArgs.push(getRunSqlQuery(sqlCreateExtension));
type: 'run_sql',
args: { sql: sqlCreateExtension },
});
} }
upQueryArgs.push({ upQueryArgs.push(getRunSqlQuery(sqlCreateTable));
type: 'run_sql',
args: { sql: sqlCreateTable },
});
upQueryArgs.push({ upQueryArgs.push({
type: 'add_existing_table_or_view', type: 'add_existing_table_or_view',
@ -345,12 +340,7 @@ const createTableSql = () => {
const downQuery = { const downQuery = {
type: 'bulk', type: 'bulk',
args: [ args: [getRunSqlQuery(sqlDropTable)],
{
type: 'run_sql',
args: { sql: sqlDropTable },
},
],
}; };
// make request // make request

View File

@ -1,6 +1,7 @@
import sanitize from 'sanitize-filename'; import sanitize from 'sanitize-filename';
import { getSchemaBaseRoute } from '../../Common/utils/routesUtils'; import { getSchemaBaseRoute } from '../../Common/utils/routesUtils';
import { getRunSqlQuery } from '../../Common/utils/v1QueryUtils';
import Endpoints, { globalCookiePolicy } from '../../../Endpoints'; import Endpoints, { globalCookiePolicy } from '../../../Endpoints';
import requestAction from '../../../utils/requestAction'; import requestAction from '../../../utils/requestAction';
import defaultState from './DataState'; import defaultState from './DataState';
@ -547,28 +548,17 @@ const makeMigrationCall = (
}; };
const getBulkColumnInfoFetchQuery = schema => { const getBulkColumnInfoFetchQuery = schema => {
const fetchColumnTypes = { const fetchColumnTypes = getRunSqlQuery(fetchColumnTypesQuery, false, true);
type: 'run_sql', const fetchTypeDefaultValues = getRunSqlQuery(
args: { fetchColumnDefaultFunctions(schema),
sql: fetchColumnTypesQuery, false,
read_only: true, true
}, );
}; const fetchValidTypeCasts = getRunSqlQuery(
const fetchTypeDefaultValues = { fetchColumnCastsQuery,
type: 'run_sql', false,
args: { true
sql: fetchColumnDefaultFunctions(schema), );
read_only: true,
},
};
const fetchValidTypeCasts = {
type: 'run_sql',
args: {
sql: fetchColumnCastsQuery,
read_only: true,
},
};
return { return {
type: 'bulk', type: 'bulk',

View File

@ -20,6 +20,7 @@ import { fetchTrackedFunctions } from '../DataActions';
import _push from '../push'; import _push from '../push';
import { getSchemaBaseRoute } from '../../../Common/utils/routesUtils'; import { getSchemaBaseRoute } from '../../../Common/utils/routesUtils';
import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils';
/* Constants */ /* Constants */
@ -193,19 +194,11 @@ const deleteFunctionSql = () => {
const sqlDropFunction = const sqlDropFunction =
'DROP FUNCTION ' + functionNameWithSchema + functionArgString; 'DROP FUNCTION ' + functionNameWithSchema + functionArgString;
const sqlUpQueries = [ const sqlUpQueries = [getRunSqlQuery(sqlDropFunction)];
{
type: 'run_sql',
args: { sql: sqlDropFunction },
},
];
const sqlDownQueries = []; const sqlDownQueries = [];
if (functionDefinition && functionDefinition.length > 0) { if (functionDefinition && functionDefinition.length > 0) {
sqlDownQueries.push({ sqlDownQueries.push(getRunSqlQuery(functionDefinition));
type: 'run_sql',
args: { sql: functionDefinition },
});
} }
// Apply migrations // Apply migrations

View File

@ -16,6 +16,7 @@ import {
import { parseCreateSQL } from './utils'; import { parseCreateSQL } from './utils';
import dataHeaders from '../Common/Headers'; import dataHeaders from '../Common/Headers';
import returnMigrateUrl from '../Common/getMigrateUrl'; import returnMigrateUrl from '../Common/getMigrateUrl';
import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils';
const MAKING_REQUEST = 'RawSQL/MAKING_REQUEST'; const MAKING_REQUEST = 'RawSQL/MAKING_REQUEST';
const SET_SQL = 'RawSQL/SET_SQL'; const SET_SQL = 'RawSQL/SET_SQL';
@ -43,16 +44,7 @@ const executeSQL = (isMigration, migrationName) => (dispatch, getState) => {
const isCascadeChecked = getState().rawSQL.isCascadeChecked; const isCascadeChecked = getState().rawSQL.isCascadeChecked;
let url = Endpoints.rawSQL; let url = Endpoints.rawSQL;
const schemaChangesUp = [ const schemaChangesUp = [getRunSqlQuery(sql, isCascadeChecked, readOnlyMode)];
{
type: 'run_sql',
args: {
sql: sql,
cascade: isCascadeChecked,
read_only: readOnlyMode,
},
},
];
// check if track view enabled // check if track view enabled
if (getState().rawSQL.isTableTrackChecked) { if (getState().rawSQL.isTableTrackChecked) {

View File

@ -2,6 +2,7 @@ import gqlPattern, { gqlSchemaErrorNotif } from '../Common/GraphQLValidation';
import { showErrorNotification } from '../../Common/Notification'; import { showErrorNotification } from '../../Common/Notification';
import { makeMigrationCall, fetchSchemaList } from '../DataActions'; import { makeMigrationCall, fetchSchemaList } from '../DataActions';
import { getConfirmation } from '../../../Common/utils/jsUtils'; import { getConfirmation } from '../../../Common/utils/jsUtils';
import { getRunSqlQuery } from '../../../Common/utils/v1QueryUtils';
const getDropSchemaSql = schemaName => `drop schema "${schemaName}" cascade;`; const getDropSchemaSql = schemaName => `drop schema "${schemaName}" cascade;`;
@ -19,23 +20,9 @@ export const createNewSchema = (schemaName, successCb, errorCb) => {
); );
} }
const migrationUp = [ const migrationUp = [getRunSqlQuery(getCreateSchemaSql(schemaName))];
{
type: 'run_sql',
args: {
sql: getCreateSchemaSql(schemaName),
},
},
];
const migrationDown = [ const migrationDown = [getRunSqlQuery(getDropSchemaSql(schemaName))];
{
type: 'run_sql',
args: {
sql: getDropSchemaSql(schemaName),
},
},
];
const migrationName = `create_schema_${schemaName}`; const migrationName = `create_schema_${schemaName}`;
const requestMsg = 'Creating schema'; const requestMsg = 'Creating schema';
@ -86,14 +73,7 @@ export const deleteCurrentSchema = (successCb, errorCb) => {
return; return;
} }
const migrationUp = [ const migrationUp = [getRunSqlQuery(getDropSchemaSql(currentSchema))];
{
type: 'run_sql',
args: {
sql: getDropSchemaSql(currentSchema),
},
},
];
const migrationName = `drop_schema_${currentSchema}`; const migrationName = `drop_schema_${currentSchema}`;
const requestMsg = 'Dropping schema'; const requestMsg = 'Dropping schema';
const successMsg = 'Successfully dropped schema'; const successMsg = 'Successfully dropped schema';

View File

@ -47,6 +47,9 @@ import {
import { import {
getSetCustomRootFieldsQuery, getSetCustomRootFieldsQuery,
getRunSqlQuery, getRunSqlQuery,
getSetTableEnumQuery,
getUntrackTableQuery,
getTrackTableQuery,
} from '../../../Common/utils/v1QueryUtils'; } from '../../../Common/utils/v1QueryUtils';
import { import {
@ -239,20 +242,17 @@ export const removeCheckConstraint = (constraintName, successCb, errorCb) => (
constraintName constraintName
); );
const upQuery = { const upQuery = getRunSqlQuery(
type: 'run_sql', getDropConstraintSql(tableName, currentSchema, constraintName)
args: { );
sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${constraintName}"`, const downQuery = getRunSqlQuery(
}, getCreateCheckConstraintSql(
}; tableName,
const downQuery = { currentSchema,
type: 'run_sql', constraintName,
args: { constraint.check
sql: `alter table "${currentSchema}"."${tableName}" add constraint "${constraintName}" ${ )
constraint.check );
};`,
},
};
const migrationName = `drop_check_constraint_${currentSchema}_${tableName}_${constraintName}`; const migrationName = `drop_check_constraint_${currentSchema}_${tableName}_${constraintName}`;
const requestMsg = 'Deleting check constraint...'; const requestMsg = 'Deleting check constraint...';
@ -269,7 +269,6 @@ export const removeCheckConstraint = (constraintName, successCb, errorCb) => (
} }
dispatch({ type: UPDATE_MIGRATION_STATUS_ERROR, data: err }); dispatch({ type: UPDATE_MIGRATION_STATUS_ERROR, data: err });
}; };
makeMigrationCall( makeMigrationCall(
dispatch, dispatch,
getState, getState,
@ -326,54 +325,50 @@ const savePrimaryKeys = (tableName, schemaName, constraintName) => {
const migrationUp = []; const migrationUp = [];
// skip dropping existing constraint if there is none // skip dropping existing constraint if there is none
if (constraintName) { if (constraintName) {
migrationUp.push({ migrationUp.push(
type: 'run_sql', getRunSqlQuery(getDropPkSql({ schemaName, tableName, constraintName }))
args: { );
sql: getDropPkSql({ schemaName, tableName, constraintName }),
},
});
} }
// skip creating a new config if no columns were selected // skip creating a new config if no columns were selected
if (numSelectedPkColumns) { if (numSelectedPkColumns) {
migrationUp.push({ migrationUp.push(
type: 'run_sql', getRunSqlQuery(
args: { getCreatePkSql({
sql: getCreatePkSql({
schemaName, schemaName,
tableName, tableName,
selectedPkColumns, selectedPkColumns,
constraintName: `${tableName}_pkey`, constraintName: `${tableName}_pkey`,
}), })
}, )
}); );
} }
const migrationDown = []; const migrationDown = [];
// skip dropping in down migration if no constraint was created // skip dropping in down migration if no constraint was created
if (numSelectedPkColumns) { if (numSelectedPkColumns) {
migrationDown.push({ migrationDown.push(
type: 'run_sql', getRunSqlQuery(
args: { getDropPkSql({
sql: getDropPkSql({
schemaName, schemaName,
tableName, tableName,
constraintName: `${tableName}_pkey`, constraintName: `${tableName}_pkey`,
}), })
}, )
}); );
} }
// skip creating in down migration if no constraint was dropped in up migration // skip creating in down migration if no constraint was dropped in up migration
if (constraintName) { if (constraintName) {
migrationDown.push({ migrationDown.push(
type: 'run_sql', getRunSqlQuery(
sql: getCreatePkSql({ getCreatePkSql({
schemaName, schemaName,
tableName, tableName,
selectedPkColumns: tableSchema.primary_key.columns, selectedPkColumns: tableSchema.primary_key.columns,
constraintName, constraintName,
}), })
}); )
);
} }
const pkAction = numSelectedPkColumns ? 'Updating' : 'Deleting'; const pkAction = numSelectedPkColumns ? 'Updating' : 'Deleting';
@ -454,13 +449,7 @@ const saveForeignKeys = (index, tableSchema, columns) => {
references "${refSchemaName}"."${refTableName}" references "${refSchemaName}"."${refTableName}"
(${rcols.join(', ')}) on update ${onUpdate} on delete ${onDelete}; (${rcols.join(', ')}) on update ${onUpdate} on delete ${onDelete};
`; `;
migrationUp.push(getRunSqlQuery(migrationUpAlterFKeySql));
migrationUp.push({
type: 'run_sql',
args: {
sql: migrationUpAlterFKeySql,
},
});
} else { } else {
// foreign key not found, create a new one // foreign key not found, create a new one
const migrationUpCreateFKeySql = ` const migrationUpCreateFKeySql = `
@ -471,12 +460,7 @@ const saveForeignKeys = (index, tableSchema, columns) => {
(${rcols.join(', ')}) on update ${onUpdate} on delete ${onDelete}; (${rcols.join(', ')}) on update ${onUpdate} on delete ${onDelete};
`; `;
migrationUp.push({ migrationUp.push(getRunSqlQuery(migrationUpCreateFKeySql));
type: 'run_sql',
args: {
sql: migrationUpCreateFKeySql,
},
});
} }
const migrationDown = []; const migrationDown = [];
@ -500,24 +484,14 @@ const saveForeignKeys = (index, tableSchema, columns) => {
on delete ${pgConfTypes[oldConstraint.on_delete]}; on delete ${pgConfTypes[oldConstraint.on_delete]};
`; `;
migrationDown.push({ migrationDown.push(getRunSqlQuery(migrationDownAlterFKeySql));
type: 'run_sql',
args: {
sql: migrationDownAlterFKeySql,
},
});
} else { } else {
// when foreign key is created // when foreign key is created
const migrationDownDeleteFKeySql = ` const migrationDownDeleteFKeySql = `
alter table "${schemaName}"."${tableName}" drop constraint "${generatedConstraintName}" alter table "${schemaName}"."${tableName}" drop constraint "${generatedConstraintName}"
`; `;
migrationDown.push({ migrationDown.push(getRunSqlQuery(migrationDownDeleteFKeySql));
type: 'run_sql',
args: {
sql: migrationDownDeleteFKeySql,
},
});
} }
const migrationName = `set_fk_${schemaName}_${tableName}_${lcols.join( const migrationName = `set_fk_${schemaName}_${tableName}_${lcols.join(
@ -576,36 +550,22 @@ const removeForeignKey = (index, tableSchema) => {
const tableName = tableSchema.table_name; const tableName = tableSchema.table_name;
const schemaName = tableSchema.table_schema; const schemaName = tableSchema.table_schema;
const oldConstraint = tableSchema.foreign_key_constraints[index]; const oldConstraint = tableSchema.foreign_key_constraints[index];
const migrationUp = [ const upSql = `alter table "${schemaName}"."${tableName}" drop constraint "${
{ oldConstraint.constraint_name
type: 'run_sql', }";`;
args: { const downSql = `alter table "${schemaName}"."${tableName}" add foreign key (${Object.keys(
sql: `alter table "${schemaName}"."${tableName}" drop constraint "${ oldConstraint.column_mapping
oldConstraint.constraint_name )
}";`, .map(lc => `"${lc}"`)
}, .join(', ')}) references "${oldConstraint.ref_table_table_schema}"."${
}, oldConstraint.ref_table
]; }"(${Object.values(oldConstraint.column_mapping)
const migrationDown = [ .map(rc => `"${rc}"`)
{ .join(', ')}) on update ${
type: 'run_sql', pgConfTypes[oldConstraint.on_update]
args: { } on delete ${pgConfTypes[oldConstraint.on_delete]};`;
sql: `alter table "${schemaName}"."${tableName}" add foreign key (${Object.keys( const migrationUp = [getRunSqlQuery(upSql)];
oldConstraint.column_mapping const migrationDown = [getRunSqlQuery(downSql)];
)
.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 migrationName = `delete_fk_${schemaName}_${tableName}_${ const migrationName = `delete_fk_${schemaName}_${tableName}_${
oldConstraint.constraint_name oldConstraint.constraint_name
}`; }`;
@ -673,22 +633,10 @@ const changeTableName = (oldName, newName, isTable) => {
); );
} }
const currentSchema = getState().tables.currentSchema; const currentSchema = getState().tables.currentSchema;
const migrateUp = [ const upSql = `alter ${property} "${currentSchema}"."${oldName}" rename to "${newName}";`;
{ const downSql = `alter ${property} "${currentSchema}"."${newName}" rename to "${oldName}";`;
type: 'run_sql', const migrateUp = [getRunSqlQuery(upSql)];
args: { const migrateDown = [getRunSqlQuery(downSql)];
sql: `alter ${property} "${currentSchema}"."${oldName}" rename to "${newName}";`,
},
},
];
const migrateDown = [
{
type: 'run_sql',
args: {
sql: `alter ${property} "${currentSchema}"."${newName}" rename to "${oldName}";`,
},
},
];
// apply migrations // apply migrations
const migrationName = `rename_${property}_` + currentSchema + '_' + oldName; const migrationName = `rename_${property}_` + currentSchema + '_' + oldName;
@ -730,14 +678,7 @@ const deleteTrigger = (trigger, table) => {
const upMigrationSql = `DROP TRIGGER "${triggerName}" ON "${tableSchema}"."${tableName}";`; const upMigrationSql = `DROP TRIGGER "${triggerName}" ON "${tableSchema}"."${tableName}";`;
const migrationUp = [ const migrationUp = [getRunSqlQuery(upMigrationSql)];
{
type: 'run_sql',
args: {
sql: upMigrationSql,
},
},
];
let downMigrationSql = ''; let downMigrationSql = '';
@ -751,14 +692,7 @@ FOR EACH ${trigger.action_orientation} ${trigger.action_statement};`;
downMigrationSql += `COMMENT ON TRIGGER "${triggerName}" ON "${tableSchema}"."${tableName}" downMigrationSql += `COMMENT ON TRIGGER "${triggerName}" ON "${tableSchema}"."${tableName}"
IS ${sqlEscapeText(trigger.comment)};`; IS ${sqlEscapeText(trigger.comment)};`;
} }
const migrationDown = [ const migrationDown = [getRunSqlQuery(downMigrationSql)];
{
type: 'run_sql',
args: {
sql: downMigrationSql,
},
},
];
const migrationName = `delete_trigger_${triggerSchema}_${triggerName}`; const migrationName = `delete_trigger_${triggerSchema}_${triggerName}`;
@ -792,20 +726,7 @@ const deleteTableSql = tableName => {
// handle no primary key // handle no primary key
const sqlDropTable = const sqlDropTable =
'DROP TABLE ' + '"' + currentSchema + '"' + '.' + '"' + tableName + '"'; 'DROP TABLE ' + '"' + currentSchema + '"' + '.' + '"' + tableName + '"';
const sqlUpQueries = [ const sqlUpQueries = [getRunSqlQuery(sqlDropTable)];
{
type: 'run_sql',
args: { sql: sqlDropTable },
},
];
// const sqlCreateTable = 'CREATE TABLE ' + '"' + tableName + '"' + '(' + tableColumns + ')';
// const sqlDownQueries = [
// {
// type: 'run_sql',
// args: { 'sql': sqlCreateTable }
// }
// ];
// apply migrations // apply migrations
const migrationName = 'drop_table_' + currentSchema + '_' + tableName; const migrationName = 'drop_table_' + currentSchema + '_' + tableName;
@ -842,26 +763,9 @@ const deleteTableSql = tableName => {
const untrackTableSql = tableName => { const untrackTableSql = tableName => {
return (dispatch, getState) => { return (dispatch, getState) => {
const currentSchema = getState().tables.currentSchema; const currentSchema = getState().tables.currentSchema;
const upQueries = [ const tableDef = generateTableDef(tableName, currentSchema);
{ const upQueries = [getUntrackTableQuery(tableDef)];
type: 'untrack_table', const downQueries = [getTrackTableQuery(tableDef)];
args: {
table: {
name: tableName.trim(),
schema: currentSchema,
},
},
},
];
const downQueries = [
{
type: 'add_existing_table_or_view',
args: {
name: tableName.trim(),
schema: currentSchema,
},
},
];
// apply migrations // apply migrations
const migrationName = 'untrack_table_' + currentSchema + '_' + tableName; const migrationName = 'untrack_table_' + currentSchema + '_' + tableName;
@ -931,13 +835,7 @@ const fetchViewDefinition = (viewName, isRedirect) => {
"'" + "'" +
viewName + viewName +
"'"; "'";
const reqBody = { const reqBody = getRunSqlQuery(sqlQuery, false, true);
type: 'run_sql',
args: {
sql: sqlQuery,
read_only: true,
},
};
const url = Endpoints.query; const url = Endpoints.query;
const options = { const options = {
@ -988,12 +886,7 @@ const deleteViewSql = viewName => {
const currentSchema = getState().tables.currentSchema; const currentSchema = getState().tables.currentSchema;
const sqlDropView = const sqlDropView =
'DROP VIEW ' + '"' + currentSchema + '"' + '.' + '"' + viewName + '"'; 'DROP VIEW ' + '"' + currentSchema + '"' + '.' + '"' + viewName + '"';
const sqlUpQueries = [ const sqlUpQueries = [getRunSqlQuery(sqlDropView)];
{
type: 'run_sql',
args: { sql: sqlDropView },
},
];
// const sqlCreateView = ''; //pending // const sqlCreateView = ''; //pending
// const sqlDownQueries = [ // const sqlDownQueries = [
// { // {
@ -1056,48 +949,30 @@ const deleteColumnSql = (column, tableSchema) => {
'ALTER TABLE ' + '"' + currentSchema + '"' + '.' + '"' + tableName + '" '; 'ALTER TABLE ' + '"' + currentSchema + '"' + '.' + '"' + tableName + '" ';
const schemaChangesUp = [ const schemaChangesUp = [
{ getRunSqlQuery(
type: 'run_sql', alterStatement + 'DROP COLUMN ' + '"' + name + '" CASCADE'
args: { ),
sql: alterStatement + 'DROP COLUMN ' + '"' + name + '" CASCADE',
},
},
]; ];
const schemaChangesDown = []; const schemaChangesDown = [];
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { alterStatement + 'ADD COLUMN ' + '"' + name + '"' + ' ' + col_type
sql: alterStatement + 'ADD COLUMN ' + '"' + name + '"' + ' ' + col_type, )
}, );
});
if (is_nullable) { if (is_nullable) {
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { alterStatement + 'ALTER COLUMN ' + '"' + name + '" ' + 'DROP NOT NULL'
sql: )
alterStatement + );
'ALTER COLUMN ' +
'"' +
name +
'" ' +
'DROP NOT NULL',
},
});
} else { } else {
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { alterStatement + 'ALTER COLUMN ' + '"' + name + '" ' + 'SET NOT NULL'
sql: )
alterStatement + );
'ALTER COLUMN ' +
'"' +
name +
'" ' +
'SET NOT NULL',
},
});
} }
const merged_fkc = foreign_key_constraints.concat( const merged_fkc = foreign_key_constraints.concat(
@ -1110,11 +985,9 @@ const deleteColumnSql = (column, tableSchema) => {
const rcol = Object.values(fkc.column_mapping); const rcol = Object.values(fkc.column_mapping);
const onUpdate = pgConfTypes[fkc.on_update]; const onUpdate = pgConfTypes[fkc.on_update];
const onDelete = pgConfTypes[fkc.on_delete]; const onDelete = pgConfTypes[fkc.on_delete];
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { alterStatement +
sql:
alterStatement +
'ADD CONSTRAINT ' + 'ADD CONSTRAINT ' +
`${fkc.constraint_name} ` + `${fkc.constraint_name} ` +
'FOREIGN KEY ' + 'FOREIGN KEY ' +
@ -1123,51 +996,45 @@ const deleteColumnSql = (column, tableSchema) => {
`"${fkc.ref_table_table_schema}"."${fkc.ref_table}" ` + `"${fkc.ref_table_table_schema}"."${fkc.ref_table}" ` +
`(${rcol.join(', ')}) ` + `(${rcol.join(', ')}) ` +
`ON DELETE ${onDelete} ` + `ON DELETE ${onDelete} ` +
`ON UPDATE ${onUpdate}`, `ON UPDATE ${onUpdate}`
}, )
}); );
}); });
} }
if (unique_constraints.length > 0) { if (unique_constraints.length > 0) {
unique_constraints.forEach(uc => { unique_constraints.forEach(uc => {
// add unique constraint to down migration // add unique constraint to down migration
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { alterStatement +
sql:
alterStatement +
'ADD CONSTRAINT ' + 'ADD CONSTRAINT ' +
`${uc.constraint_name} ` + `${uc.constraint_name} ` +
'UNIQUE ' + 'UNIQUE ' +
`(${uc.columns.join(', ')})`, `(${uc.columns.join(', ')})`
}, )
}); );
}); });
} }
if (column.column_default !== null) { if (column.column_default !== null) {
// add column default to down migration // add column default to down migration
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { alterStatement +
sql:
alterStatement +
'ALTER COLUMN ' + 'ALTER COLUMN ' +
`"${name}" ` + `"${name}" ` +
'SET DEFAULT ' + 'SET DEFAULT ' +
column.column_default, column.column_default
}, )
}); );
} }
// COMMENT ON COLUMN my_table.my_column IS 'Employee ID number'; // COMMENT ON COLUMN my_table.my_column IS 'Employee ID number';
if (comment) { if (comment) {
schemaChangesDown.push({ schemaChangesDown.push(
type: 'run_sql', getRunSqlQuery(
args: { 'COMMENT ON COLUMN ' +
sql:
'COMMENT ON COLUMN ' +
'"' + '"' +
currentSchema + currentSchema +
'"' + '"' +
@ -1181,9 +1048,9 @@ const deleteColumnSql = (column, tableSchema) => {
'"' + '"' +
' ' + ' ' +
'IS ' + 'IS ' +
sqlEscapeText(comment), sqlEscapeText(comment)
}, )
}); );
} }
// Apply migrations // Apply migrations
@ -1294,20 +1161,12 @@ const addColSql = (
const schemaChangesUp = []; const schemaChangesUp = [];
if (colType === 'uuid' && colDefault !== '') { if (colType === 'uuid' && colDefault !== '') {
schemaChangesUp.push({ schemaChangesUp.push(
type: 'run_sql', getRunSqlQuery('CREATE EXTENSION IF NOT EXISTS pgcrypto;')
args: { );
sql: 'CREATE EXTENSION IF NOT EXISTS pgcrypto;',
},
});
} }
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(runSqlQueryUp));
type: 'run_sql',
args: {
sql: runSqlQueryUp,
},
});
let runSqlQueryDown = ''; let runSqlQueryDown = '';
@ -1330,14 +1189,7 @@ const addColSql = (
colName + colName +
'";'; '";';
const schemaChangesDown = [ const schemaChangesDown = [getRunSqlQuery(runSqlQueryDown)];
{
type: 'run_sql',
args: {
sql: runSqlQueryDown,
},
},
];
// Apply migrations // Apply migrations
const migrationName = const migrationName =
@ -1397,14 +1249,7 @@ const deleteConstraintSql = (tableName, cName) => {
'"' + '"' +
cName + cName +
'"'; '"';
const schemaChangesUp = [ const schemaChangesUp = [getRunSqlQuery(dropContraintQuery)];
{
type: 'run_sql',
args: {
sql: dropContraintQuery,
},
},
];
// pending // pending
const schemaChangesDown = []; const schemaChangesDown = [];
@ -1462,22 +1307,8 @@ const saveTableCommentSql = isTable => {
: commentQueryBase + sqlEscapeText(updatedComment); : commentQueryBase + sqlEscapeText(updatedComment);
const commentDownQuery = commentQueryBase + 'NULL'; const commentDownQuery = commentQueryBase + 'NULL';
const schemaChangesUp = [ const schemaChangesUp = [getRunSqlQuery(commentUpQuery)];
{ const schemaChangesDown = [getRunSqlQuery(commentDownQuery)];
type: 'run_sql',
args: {
sql: commentUpQuery,
},
},
];
const schemaChangesDown = [
{
type: 'run_sql',
args: {
sql: commentDownQuery,
},
},
];
// Apply migrations // Apply migrations
const migrationName = const migrationName =
@ -1595,26 +1426,10 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
column.data_type + column.data_type +
';'; ';';
const schemaChangesUp = const schemaChangesUp =
originalColType !== colType originalColType !== colType ? [getRunSqlQuery(columnChangesUpQuery)] : [];
? [
{
type: 'run_sql',
args: {
sql: columnChangesUpQuery,
},
},
]
: [];
const schemaChangesDown = const schemaChangesDown =
originalColType !== colType originalColType !== colType
? [ ? [getRunSqlQuery(columnChangesDownQuery)]
{
type: 'run_sql',
args: {
sql: columnChangesDownQuery,
},
},
]
: []; : [];
/* column custom field up/down migration*/ /* 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 // check if default is unchanged and then do a drop. if not skip
if (originalColDefault !== colDefault) { if (originalColDefault !== colDefault) {
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(columnDefaultUpQuery));
type: 'run_sql', schemaChangesDown.push(getRunSqlQuery(columnDefaultDownQuery));
args: {
sql: columnDefaultUpQuery,
},
});
schemaChangesDown.push({
type: 'run_sql',
args: {
sql: columnDefaultDownQuery,
},
});
} }
/* column nullable up/down migration */ /* column nullable up/down migration */
@ -1782,18 +1587,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
' SET NOT NULL;'; ' SET NOT NULL;';
// check with original null // check with original null
if (originalColNullable !== 'YES') { if (originalColNullable !== 'YES') {
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(nullableUpQuery));
type: 'run_sql', schemaChangesDown.push(getRunSqlQuery(nullableDownQuery));
args: {
sql: nullableUpQuery,
},
});
schemaChangesDown.push({
type: 'run_sql',
args: {
sql: nullableDownQuery,
},
});
} }
} else { } else {
// ALTER TABLE <table> ALTER COLUMN <column> SET NOT NULL; // ALTER TABLE <table> ALTER COLUMN <column> SET NOT NULL;
@ -1827,18 +1622,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
' DROP NOT NULL;'; ' DROP NOT NULL;';
// check with original null // check with original null
if (originalColNullable !== 'NO') { if (originalColNullable !== 'NO') {
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(nullableUpQuery));
type: 'run_sql', schemaChangesDown.push(getRunSqlQuery(nullableDownQuery));
args: {
sql: nullableUpQuery,
},
});
schemaChangesDown.push({
type: 'run_sql',
args: {
sql: nullableDownQuery,
},
});
} }
} }
@ -1880,18 +1665,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
'_key"'; '_key"';
// check with original unique // check with original unique
if (!originalColUnique) { if (!originalColUnique) {
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(uniqueUpQuery));
type: 'run_sql', schemaChangesDown.push(getRunSqlQuery(uniqueDownQuery));
args: {
sql: uniqueUpQuery,
},
});
schemaChangesDown.push({
type: 'run_sql',
args: {
sql: uniqueDownQuery,
},
});
} }
} else { } else {
const uniqueDownQuery = const uniqueDownQuery =
@ -1930,18 +1705,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
'_key"'; '_key"';
// check with original unique // check with original unique
if (originalColUnique) { if (originalColUnique) {
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(uniqueUpQuery));
type: 'run_sql', schemaChangesDown.push(getRunSqlQuery(uniqueDownQuery));
args: {
sql: uniqueUpQuery,
},
});
schemaChangesDown.push({
type: 'run_sql',
args: {
sql: uniqueDownQuery,
},
});
} }
} }
@ -1980,18 +1745,8 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
// check if comment is unchanged and then do an update. if not skip // check if comment is unchanged and then do an update. if not skip
if (originalColComment !== comment) { if (originalColComment !== comment) {
schemaChangesUp.push({ schemaChangesUp.push(getRunSqlQuery(columnCommentUpQuery));
type: 'run_sql', schemaChangesDown.push(getRunSqlQuery(columnCommentDownQuery));
args: {
sql: columnCommentUpQuery,
},
});
schemaChangesDown.push({
type: 'run_sql',
args: {
sql: columnCommentDownQuery,
},
});
} }
/* rename column */ /* rename column */
@ -2005,18 +1760,16 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
) )
); );
} }
schemaChangesUp.push({ schemaChangesUp.push(
type: 'run_sql', getRunSqlQuery(
args: { `alter table "${currentSchema}"."${tableName}" rename column "${colName}" to "${newName}";`
sql: `alter table "${currentSchema}"."${tableName}" rename column "${colName}" to "${newName}";`, )
}, );
}); schemaChangesDown.push(
schemaChangesDown.push({ getRunSqlQuery(
type: 'run_sql', `alter table "${currentSchema}"."${tableName}" rename column "${newName}" to "${colName}";`
args: { )
sql: `alter table "${currentSchema}"."${tableName}" rename column "${newName}" to "${colName}";`, );
},
});
} }
// Apply migrations // Apply migrations
@ -2064,12 +1817,7 @@ const saveColumnChangesSql = (colName, column, onSuccess) => {
const fetchColumnCasts = () => { const fetchColumnCasts = () => {
return (dispatch, getState) => { return (dispatch, getState) => {
const url = Endpoints.getSchema; const url = Endpoints.getSchema;
const reqQuery = { const reqQuery = getRunSqlQuery(fetchColumnCastsQuery);
type: 'run_sql',
args: {
sql: fetchColumnCastsQuery,
},
};
const options = { const options = {
credentials: globalCookiePolicy, credentials: globalCookiePolicy,
method: 'POST', method: 'POST',
@ -2108,29 +1856,23 @@ const removeUniqueKey = (index, tableName, existingConstraints, callback) => {
// Up migration: Drop the constraint // Up migration: Drop the constraint
const sqlUp = [ const sqlUp = [
{ getRunSqlQuery(
type: 'run_sql', `alter table "${currentSchema}"."${tableName}" drop constraint "${
args: { existingConstraint.constraint_name
sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${ }";`
existingConstraint.constraint_name ),
}";`,
},
},
]; ];
// Down Migration: Create the constraint that is being dropped // Down Migration: Create the constraint that is being dropped
const sqlDown = [ const sqlDown = [
{ getRunSqlQuery(
type: 'run_sql', `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName(
args: { tableName,
sql: `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName( existingConstraint.columns
tableName, )}" unique (${existingConstraint.columns
existingConstraint.columns .map(c => `"${c}"`)
)}" unique (${existingConstraint.columns .join(', ')});`
.map(c => `"${c}"`) ),
.join(', ')});`,
},
},
]; ];
const migrationName = const migrationName =
@ -2195,19 +1937,15 @@ export const toggleTableAsEnum = (isEnum, successCallback, failureCallback) => (
const { currentTable, currentSchema } = getState().tables; const { currentTable, currentSchema } = getState().tables;
const { allSchemas } = getState().tables; const { allSchemas } = getState().tables;
const getEnumQuery = is_enum => ({ const upQuery = [
type: 'set_table_is_enum', getSetTableEnumQuery(
args: { generateTableDef(currentTable, currentSchema),
table: { !isEnum
schema: currentSchema, ),
name: currentTable, ];
}, const downQuery = [
is_enum, getSetTableEnumQuery(generateTableDef(currentTable, currentSchema), isEnum),
}, ];
});
const upQuery = [getEnumQuery(!isEnum)];
const downQuery = [getEnumQuery(isEnum)];
const migrationName = const migrationName =
'alter_table_' + 'alter_table_' +
@ -2392,54 +2130,50 @@ const saveUniqueKey = (
// Down migration // Down migration
const downMigration = []; const downMigration = [];
// drop the newly created constraint // drop the newly created constraint
downMigration.push({ downMigration.push(
type: 'run_sql', getRunSqlQuery(
args: { `alter table "${currentSchema}"."${tableName}" drop constraint "${getUniqueConstraintName(
sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${getUniqueConstraintName(
tableName, tableName,
columns columns
)}";`, )}";`
}, )
}); );
// if any constraint is being dropped, create it back // if any constraint is being dropped, create it back
if (index < numUniqueKeys - 1) { if (index < numUniqueKeys - 1) {
downMigration.push({ downMigration.push(
type: 'run_sql', getRunSqlQuery(
args: { `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName(
sql: `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName(
tableName, tableName,
existingConstraint.columns existingConstraint.columns
)}" unique (${existingConstraint.columns )}" unique (${existingConstraint.columns
.map(c => `"${c}"`) .map(c => `"${c}"`)
.join(', ')});`, .join(', ')});`
}, )
}); );
} }
// up migration // up migration
const upMigration = []; const upMigration = [];
// drop the old constraint if there is any // drop the old constraint if there is any
if (index < numUniqueKeys - 1) { if (index < numUniqueKeys - 1) {
upMigration.push({ upMigration.push(
type: 'run_sql', getRunSqlQuery(
args: { `alter table "${currentSchema}"."${tableName}" drop constraint "${
sql: `alter table "${currentSchema}"."${tableName}" drop constraint "${
existingConstraint.constraint_name existingConstraint.constraint_name
}";`, }";`
}, )
}); );
} }
// create the new constraint // create the new constraint
upMigration.push({ upMigration.push(
type: 'run_sql', getRunSqlQuery(
args: { `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName(
sql: `alter table "${currentSchema}"."${tableName}" add constraint "${getUniqueConstraintName(
tableName, tableName,
columns columns
)}" unique (${columns.map(c => `"${c}"`).join(', ')});`, )}" unique (${columns.map(c => `"${c}"`).join(', ')});`
}, )
}); );
const migrationName = const migrationName =
'alter_table_' + 'alter_table_' +

View File

@ -2,6 +2,7 @@ import {
READ_ONLY_RUN_SQL_QUERIES, READ_ONLY_RUN_SQL_QUERIES,
checkFeatureSupport, checkFeatureSupport,
} from '../../../helpers/versionUtils'; } from '../../../helpers/versionUtils';
import { getRunSqlQuery } from '../../Common/utils/v1QueryUtils';
export const INTEGER = 'integer'; export const INTEGER = 'integer';
export const SERIAL = 'serial'; export const SERIAL = 'serial';
@ -329,13 +330,11 @@ FROM
${whereQuery} ${whereQuery}
) as info ) as info
`; `;
return { return getRunSqlQuery(
type: 'run_sql', runSql,
args: { false,
sql: runSql, checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false
read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false, );
},
};
}; };
export const fetchTrackedTableReferencedFkQuery = options => { export const fetchTrackedTableReferencedFkQuery = options => {
@ -365,13 +364,11 @@ FROM
${whereQuery} ${whereQuery}
) as info ) as info
`; `;
return { return getRunSqlQuery(
type: 'run_sql', runSql,
args: { false,
sql: runSql, checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false
read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false, );
},
};
}; };
export const fetchTableListQuery = options => { export const fetchTableListQuery = options => {
@ -444,13 +441,11 @@ FROM
is_views.* is_views.*
) AS info ) AS info
`; `;
return { return getRunSqlQuery(
type: 'run_sql', runSql,
args: { false,
sql: runSql, checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false
read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false, );
},
};
}; };
export const mergeLoadSchemaData = ( export const mergeLoadSchemaData = (

View File

@ -1,3 +1,5 @@
import { getRunSqlQuery } from '../../Common/utils/v1QueryUtils';
// check 2xx success status codes // check 2xx success status codes
export const verifySuccessStatus = status => { export const verifySuccessStatus = status => {
return /^2[0-9][0-9]$/.test(status.toString()); return /^2[0-9][0-9]$/.test(status.toString());
@ -136,13 +138,7 @@ FROM
hdb_et.name ASC NULLS LAST hdb_et.name ASC NULLS LAST
) AS info ) AS info
`; `;
return { return getRunSqlQuery(runSql, false, true);
type: 'run_sql',
args: {
sql: runSql,
read_only: true,
},
};
}; };
export const parseRowData = (row, dataType) => { export const parseRowData = (row, dataType) => {

View File

@ -3,6 +3,7 @@ import requestAction from '../utils/requestAction';
import dataHeaders from '../components/Services/Data/Common/Headers'; import dataHeaders from '../components/Services/Data/Common/Headers';
import defaultTelemetryState from './State'; import defaultTelemetryState from './State';
import globals from '../Globals'; import globals from '../Globals';
import { getRunSqlQuery } from '../components/Common/utils/v1QueryUtils';
const SET_CONSOLE_OPTS = 'Telemetry/SET_CONSOLE_OPTS'; const SET_CONSOLE_OPTS = 'Telemetry/SET_CONSOLE_OPTS';
const SET_NOTIFICATION_SHOWN = 'Telemetry/SET_NOTIFICATION_SHOWN'; const SET_NOTIFICATION_SHOWN = 'Telemetry/SET_NOTIFICATION_SHOWN';
@ -20,12 +21,11 @@ const setNotificationShownInDB = () => (dispatch, getState) => {
credentials: globalCookiePolicy, credentials: globalCookiePolicy,
method: 'POST', method: 'POST',
headers: dataHeaders(getState), headers: dataHeaders(getState),
body: JSON.stringify({ body: JSON.stringify(
type: 'run_sql', getRunSqlQuery(
args: { `update hdb_catalog.hdb_version set console_state = console_state || jsonb_build_object('telemetryNotificationShown', true) where hasura_uuid='${uuid}';`
sql: `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( return dispatch(requestAction(url, options)).then(
data => { data => {