WMS_MAIN/script/tmp-compare-order-schema.cjs

172 lines
5.5 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const { createRequire } = require('module');
function extractTopLevelFieldsFromObjectBody(body) {
const fields = [];
let i = 0;
let depth = 0;
while (i < body.length) {
const ch = body[i];
if (ch === '{') {
depth++;
i++;
continue;
}
if (ch === '}') {
depth--;
i++;
continue;
}
if (depth === 0) {
const m = body.slice(i).match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*\{/);
if (m) {
const key = m[1];
fields.push(key);
i += m[0].length;
let inner = 1;
while (i < body.length && inner > 0) {
const c = body[i++];
if (c === '{') inner++;
if (c === '}') inner--;
}
continue;
}
}
i++;
}
return [...new Set(fields)];
}
function getObjectBodyByMarker(text, marker) {
const start = text.indexOf(marker);
if (start < 0) return null;
const braceStart = text.indexOf('{', start + marker.length);
if (braceStart < 0) return null;
let i = braceStart + 1;
let depth = 1;
let body = '';
while (i < text.length && depth > 0) {
const ch = text[i++];
if (ch === '{') depth++;
if (ch === '}') depth--;
if (depth > 0) body += ch;
}
return body;
}
function extractDefineFields(text) {
const definePos = text.indexOf('define(');
if (definePos < 0) return [];
const firstBrace = text.indexOf('{', definePos);
if (firstBrace < 0) return [];
let i = firstBrace + 1;
let depth = 1;
let body = '';
while (i < text.length && depth > 0) {
const ch = text[i++];
if (ch === '{') depth++;
if (ch === '}') depth--;
if (depth > 0) body += ch;
}
return extractTopLevelFieldsFromObjectBody(body);
}
async function main() {
const root = process.cwd();
const projectRequire = createRequire(path.join(root, 'package.json'));
const mysql = projectRequire('mysql2/promise');
const cfgFactory = require(path.join(root, 'config', 'config.local.js'));
const cfg = typeof cfgFactory === 'function' ? cfgFactory({ name: 'wms-debug' }) : cfgFactory;
const client = cfg?.mysql?.clients?.wms;
if (!client) throw new Error('mysql client wms not found');
const conn = await mysql.createConnection({
host: client.host,
port: Number(client.port),
user: client.user,
password: client.password,
database: client.database,
charset: client.charset || 'utf8mb4',
});
const [tableRows] = await conn.query(
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME IN ('wms_order_delivery','wms_order_items','wms_entry_order') OR TABLE_NAME LIKE 'wms_order_delivery_%' OR TABLE_NAME LIKE 'wms_order_items_%') ORDER BY TABLE_NAME"
);
const tableSchemas = {};
for (const t of tableRows.map(x => x.TABLE_NAME)) {
const [cols] = await conn.query(
"SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",
[t]
);
tableSchemas[t] = cols;
}
const targets = [
{ table: 'wms_order_delivery', modelFile: 'app/model/order_delivery.js', type: 'baseModel' },
{ table: 'wms_order_items', modelFile: 'app/model/order_items.js', type: 'define' },
{ table: 'wms_entry_order', modelFile: 'app/model/entry_order.js', type: 'define' },
];
const compareWithModel = targets.map(t => {
const txt = fs.readFileSync(path.join(root, t.modelFile), 'utf8');
let modelFields = [];
if (t.type === 'baseModel') {
const body = getObjectBodyByMarker(txt, 'const baseModel =');
modelFields = body ? extractTopLevelFieldsFromObjectBody(body) : [];
} else {
modelFields = extractDefineFields(txt);
}
const dbColumns = (tableSchemas[t.table] || []).map(c => c.COLUMN_NAME);
const modelOnly = modelFields.filter(f => !dbColumns.includes(f));
const dbOnly = dbColumns.filter(c => !modelFields.includes(c));
return {
table: t.table,
modelFile: t.modelFile,
modelFieldCount: modelFields.length,
dbFieldCount: dbColumns.length,
modelOnly,
dbOnly,
allMatched: modelOnly.length === 0 && dbOnly.length === 0,
};
});
const dynamicTableCheck = [];
const dynamicTables = Object.keys(tableSchemas).filter(t => t.endsWith('_100000'));
for (const dt of dynamicTables) {
const baseTable = dt.startsWith('wms_order_delivery_') ? 'wms_order_delivery' : dt.startsWith('wms_order_items_') ? 'wms_order_items' : null;
if (!baseTable) continue;
const baseCols = (tableSchemas[baseTable] || []).map(c => c.COLUMN_NAME);
const dynCols = (tableSchemas[dt] || []).map(c => c.COLUMN_NAME);
dynamicTableCheck.push({
table: dt,
baseTable,
missingFromDynamic: baseCols.filter(c => !dynCols.includes(c)),
extraInDynamic: dynCols.filter(c => !baseCols.includes(c)),
allMatched: baseCols.length === dynCols.length && baseCols.every(c => dynCols.includes(c)),
});
}
const out = {
generatedAt: new Date().toISOString(),
dbName: client.database,
tables: tableRows.map(x => x.TABLE_NAME),
compareWithModel,
dynamicTableCheck,
schema: tableSchemas,
};
fs.writeFileSync(path.join(root, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2));
await conn.end();
console.log('WROTE tmp-order-schema-compare.json');
}
main().catch(err => {
console.error(err && err.stack ? err.stack : String(err));
process.exit(1);
});