UNPKG

autosql

Version:

An auto-parser of JSON into SQL.

52 lines (51 loc) 3.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getUsingClause = getUsingClause; const groupings_1 = require("../../../config/groupings"); // Generates a `USING` clause for ALTER COLUMN to safely convert data types. function getUsingClause(columnName, oldType, newType, tableName, schema) { const schemaPrefix = schema ? `\`${schema}\`.` : ""; if (oldType === newType) return `"${columnName}"`; // ✅ BOOLEAN → NUMERIC if ((0, groupings_1.isBoolean)(oldType) && (0, groupings_1.isNumeric)(newType)) { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = CASE WHEN \`${columnName}\` THEN 1 ELSE 0 END WHERE \`${columnName}\` IS NOT NULL;`; } // ✅ NUMERIC → BOOLEAN if ((0, groupings_1.isNumeric)(oldType) && (0, groupings_1.isBoolean)(newType)) { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = CASE WHEN \`${columnName}\` = 1 THEN TRUE ELSE FALSE END WHERE \`${columnName}\` IS NOT NULL;`; } // ✅ TEXT → BOOLEAN if ((0, groupings_1.isText)(oldType) && (0, groupings_1.isBoolean)(newType)) { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = CASE WHEN LOWER(TRIM(\`${columnName}\`)) IN ('true', 't', 'yes', 'y', '1', 'on') THEN TRUE WHEN LOWER(TRIM(\`${columnName}\`)) IN ('false', 'f', 'no', 'n', '0', 'off') THEN FALSE ELSE NULL END WHERE \`${columnName}\` IS NOT NULL;`; } // ✅ INTEGER → FLOATING POINT if ((0, groupings_1.isInteger)(oldType) && (0, groupings_1.isFloating)(newType)) { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = \`${columnName}\` * 1.0 WHERE \`${columnName}\` IS NOT NULL;`; } // ✅ FLOATING POINT → INTEGER if ((0, groupings_1.isFloating)(oldType) && (0, groupings_1.isInteger)(newType)) { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = ROUND(\`${columnName}\`) WHERE \`${columnName}\` IS NOT NULL;`; } // ✅ TEXT → NUMERIC if ((0, groupings_1.isText)(oldType) && (0, groupings_1.isNumeric)(newType)) { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = NULLIF(\`${columnName}\`, '') WHERE \`${columnName}\` IS NOT NULL;`; } // ✅ TEXT → DATE/TIME if ((0, groupings_1.isText)(oldType) && newType === "datetime") { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = STR_TO_DATE(\`${columnName}\`, '%Y-%m-%d %H:%i:%s') WHERE \`${columnName}\` IS NOT NULL;`; } if ((0, groupings_1.isText)(oldType) && newType === "date") { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = STR_TO_DATE(\`${columnName}\`, '%Y-%m-%d') WHERE \`${columnName}\` IS NOT NULL;`; } if ((0, groupings_1.isText)(oldType) && newType === "time") { return `UPDATE ${schemaPrefix}\`${tableName}\` SET \`${columnName}\` = STR_TO_DATE(\`${columnName}\`, '%H:%i:%s') WHERE \`${columnName}\` IS NOT NULL;`; } return null; }