@palmares/drizzle-engine
Version:
This is the engine that wraps the hole drizzle interface in a way palmares can understand and have full control of
107 lines (102 loc) • 5.42 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
// src/model.ts
import { std } from "@palmares/core";
import { adapterModels } from "@palmares/databases";
var models = adapterModels({
// eslint-disable-next-line ts/require-await
translateOptions: /* @__PURE__ */ __name(async (_engine, modelName, options) => {
const optionsWithConjunctiveIndexes = options;
if (options.indexes) optionsWithConjunctiveIndexes.conjunctiveIndexes = options.indexes.map((index) => {
const indexFields = index.fields.join("_");
const indexAsCamel = indexFields.toLowerCase().replace(/(^([a-z]+))|([-_][a-z])/g, (group) => {
const groupWithoutDash = group.replace(/[-_]/, "");
const firstLetterUpper = groupWithoutDash[0].toUpperCase();
return firstLetterUpper + groupWithoutDash.slice(1);
});
const indexFieldsForOnClause = index.fields.map((field) => `table.${field}`).join(", ");
return ` ${modelName.slice(0, 1).toLowerCase() + modelName.slice(1)}${indexAsCamel}: d.${index.unique ? "uniqueIndex" : "index"}('${options.tableName || modelName}_${indexFields}').on(${indexFieldsForOnClause})`;
});
return {
...options
};
}, "translateOptions"),
translate: /* @__PURE__ */ __name(async (_engine, _modelName, _model, _fieldEntriesOfModel, _modelOptions, _customModelOptions, defaultTranslateCallback, _, __) => {
const { options: translatedOptions, fields: translatedAttributes } = await defaultTranslateCallback();
return {
fields: translatedAttributes,
options: translatedOptions
};
}, "translate"),
afterModelsTranslation: /* @__PURE__ */ __name(async (engine, models2) => {
let fileContent = "";
const cwd = await std.os.cwd();
const directoryName = std.files.dirname(engine.instance.output);
const [folderName, locationToRequire] = await Promise.all([
std.files.join(cwd, directoryName),
std.files.join(cwd, engine.instance.output)
]);
const imports = /* @__PURE__ */ new Set([
`/** Automatically generated by @palmares/drizzle-engine on ${(/* @__PURE__ */ new Date()).toISOString()} */
`,
`import * as d from '@palmares/drizzle-engine/${engine.instance.mainType === "postgres" ? "pg" : engine.instance.mainType === "sqlite" ? "sqlite" : "mysql"}-core';`
]);
const relationships = /* @__PURE__ */ new Map();
const tableType = engine.instance.mainType === "postgres" ? "pgTable" : engine.instance.mainType === "sqlite" ? "sqliteTable" : "mysqlTable";
for (let i = 0; i < models2.length; i++) {
const [modelName, model] = models2[i];
for (const [relationModelName, relations] of Object.entries(model.options.relationships || {})) {
relationships.set(relationModelName, {
...relationships.get(relationModelName) || {},
...relations
});
}
const indexesOfModel = model.options.drizzleIndexes || [];
const entriesOfFields = Object.entries(model.fields);
const hasEnums = (model.options.enums || []).length > 0;
if (model.options.imports) Array.from(model.options.imports || []).forEach((importString) => imports.add(importString));
const modelContentStarter = hasEnums ? model.options.enums.map((enumColumn) => enumColumn).join("\n") + "\n\n" : "";
const modelContent = `${modelContentStarter}export const ${modelName} = d.${tableType}('${model.options.tableName}', {
${entriesOfFields.map(([fieldName, fieldString]) => ` ${fieldName}: ${fieldString}`).join(",\n")}
}${indexesOfModel.length > 0 ? `, (table) => ({
${indexesOfModel.map((index) => ` ${index.fieldName}Idx: d.${index.unique ? "uniqueIndex" : "index"}('${model.options.tableName}_${index.databaseName}_idx').on(table.${index.fieldName})`).concat(model.options.conjunctiveIndexes || []).join(",\n")}
})` : ""});
`;
fileContent += modelContent;
models2[i] = [
modelName,
async () => {
try {
return Promise.resolve(__require(std.files.getPathToFileURL(locationToRequire))[modelName]);
} catch (e) {
return (await import(std.files.getPathToFileURL(locationToRequire)))[modelName];
}
}
];
}
if (relationships.size > 0) imports.add(`import * as drzl from '@palmares/drizzle-engine/drizzle';`);
for (const [modelName, relations] of relationships.entries()) {
fileContent += `export const ${modelName}Relations = drzl.relations(${modelName}, (args) => ({
${Object.entries(relations).map(([relationName, relation]) => ` ${relationName}: ${relation}`).join(",\n")}
}));
`;
}
await std.files.makeDirectory(folderName);
await std.files.writeFile(locationToRequire, `${Array.from(imports).join("\n")}
${fileContent}`);
const modelsImported = await Promise.all(models2.map(async ([modelName, model]) => [
modelName,
await model()
]));
return modelsImported;
}, "afterModelsTranslation")
});
export {
models
};