sql-code-generator
Version:
Generate code from your SQL schema and queries for type safety and development speed.
36 lines • 1.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractResourceTypeAndNameFromDDL = void 0;
const domain_1 = require("../../../domain");
// TODO: generalize to other databases with adapter pattern
const MYSQL_TYPE_NAME_CAPTURE_REGEX = /(?:CREATE|create)(?: OR REPLACE)?(?:\s+)(?:DEFINER=`[a-zA-Z0-9_]+`@`[a-zA-Z0-9_%]+`)?(?:\s*)(PROCEDURE|procedure|FUNCTION|function|TABLE|table|VIEW|view)(?:\s+)(?:`?)(\w+)(?:`?)(?:\s*)(?:\(|AS|as)/g; // captures type and name from create statements of resources
const regexTypeMatchToTypeEnum = {
PROCEDURE: domain_1.ResourceType.PROCEDURE,
procedure: domain_1.ResourceType.PROCEDURE,
FUNCTION: domain_1.ResourceType.FUNCTION,
function: domain_1.ResourceType.FUNCTION,
TABLE: domain_1.ResourceType.TABLE,
table: domain_1.ResourceType.TABLE,
VIEW: domain_1.ResourceType.VIEW,
view: domain_1.ResourceType.VIEW,
};
const extractResourceTypeAndNameFromDDL = ({ ddl }) => {
// get name and type with regex
const captureRegex = new RegExp(MYSQL_TYPE_NAME_CAPTURE_REGEX, 'gm'); // note, we reinstantiate so as to not share regex object (i.e., state) between calls
const extractionMatches = captureRegex.exec(ddl);
// if no matches, throw error
if (!extractionMatches)
throw new Error('resource creation type and name could not be found in ddl');
// format the type
const regexTypeMatch = extractionMatches[1]; // the first capture group is the type match
const type = regexTypeMatchToTypeEnum[regexTypeMatch];
// extract the name
const name = extractionMatches[2];
// return type and name
return {
type,
name,
};
};
exports.extractResourceTypeAndNameFromDDL = extractResourceTypeAndNameFromDDL;
//# sourceMappingURL=extractResourceTypeAndNameFromDDL.js.map