MCPcopy
hub / github.com/drawdb-io/drawdb / generateMigrationSQL

Function generateMigrationSQL

src/utils/migrations/diffToSQL.js:241–948  ·  view source on GitHub ↗
(
  diff,
  database = DB.POSTGRES,
  diagrams,
)

Source from the content-addressed store, hash-verified

239}
240
241export const generateMigrationSQL = (
242 diff,
243 database = DB.POSTGRES,
244 diagrams,
245) => {
246 const q = getQuote(database);
247 let up = [];
248 let down = [];
249
250 for (const [path, change] of Object.entries(diff)) {
251 const keys = path.split("#");
252 const bracketStart = keys[0].indexOf("[");
253 const element =
254 bracketStart >= 0 ? keys[0].substring(0, bracketStart) : keys[0];
255 const nameStart = keys[0].indexOf("name=");
256 const name =
257 nameStart >= 0
258 ? keys[0].substring(nameStart + 5, keys[0].indexOf("]", nameStart))
259 : "";
260
261 switch (element) {
262 case "tables": {
263 if (keys.length === 1 && change.from && !change.to) {
264 up.push(`DROP TABLE ${q(change.from.name)};`);
265 down.push(toTable(change.from, database));
266 }
267 if (keys.length === 1 && change.to && !change.from) {
268 up.push(toTable(change.to, database));
269 down.push(`DROP TABLE ${q(change.to.name)};`);
270 }
271
272 if (keys.length > 1) {
273 const childPart = keys[1];
274
275 if (childPart.startsWith("fields")) {
276 const columnName = childPart.substring(
277 childPart.indexOf("name=") + 5,
278 childPart.indexOf(",type="),
279 );
280 const columnType = childPart.substring(
281 childPart.indexOf("type=") + 5,
282 childPart.indexOf("]"),
283 );
284
285 const property = keys[2];
286
287 if (!property) {
288 if (change.from && !change.to) {
289 up.push(`ALTER TABLE ${q(name)} DROP COLUMN ${q(columnName)};`);
290 const addCol =
291 database === DB.MSSQL
292 ? `ADD ${q(columnName)} ${columnDefinition(change.from, database)}`
293 : database === DB.ORACLESQL
294 ? `ADD (${q(columnName)} ${columnDefinition(change.from, database)})`
295 : `ADD COLUMN ${q(columnName)} ${columnDefinition(change.from, database)}`;
296 down.push(`ALTER TABLE ${q(name)} ${addCol};`);
297 }
298 if (change.to && !change.from) {

Callers 1

MigrationFunction · 0.90

Calls 15

escapeQuotesFunction · 0.90
getQuoteFunction · 0.85
toTableFunction · 0.85
columnDefinitionFunction · 0.85
defValFunction · 0.85
idxFieldsFunction · 0.85
mkCreateFunction · 0.85
addUCFunction · 0.85
dropUCFunction · 0.85
resolveRelFunction · 0.85
fkColsFunction · 0.85
normalizeFkActionFunction · 0.85

Tested by

no test coverage detected