lite-ui-sql-parser
Version:
simple node sql parser
77 lines (70 loc) • 2.16 kB
JavaScript
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports", "./util", "./expr"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("./util"), require("./expr"));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.util, global.expr);
global.tables = mod.exports;
}
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _util, _expr) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.tablesToSQL = tablesToSQL;
_exports.tableOptionToSQL = tableOptionToSQL;
_exports.tableToSQL = tableToSQL;
function tableToSQL(tableInfo) {
const {
table,
db,
as,
expr
} = tableInfo;
const database = (0, _util.identifierToSql)(db);
const tableName = table ? (0, _util.identifierToSql)(table) : (0, _expr.exprToSQL)(expr);
const str = database ? `${database}.${tableName}` : tableName;
if (as) return `${str} AS ${(0, _util.identifierToSql)(as)}`;
return str;
}
/**
* @param {Array} tables
* @return {string}
*/
function tablesToSQL(tables) {
const baseTable = tables[0];
const clauses = [];
if (baseTable.type === 'dual') return 'DUAL';
clauses.push(tableToSQL(baseTable));
for (let i = 1; i < tables.length; ++i) {
const joinExpr = tables[i];
const {
on,
using,
join
} = joinExpr;
const str = [];
str.push(join ? ` ${join}` : ',');
str.push(tableToSQL(joinExpr));
str.push((0, _util.commonOptionConnector)('ON', _expr.exprToSQL, on));
if (using) str.push(`USING (${using.map(_util.identifierToSql).join(', ')})`);
clauses.push(str.filter(_util.hasVal).join(' '));
}
return clauses.filter(_util.hasVal).join('');
}
function tableOptionToSQL(tableOption) {
const {
keyword,
symbol,
value
} = tableOption;
const sql = [keyword.toUpperCase()];
if (symbol) sql.push(symbol);
sql.push(value);
return sql.join(' ');
}
});