diff --git a/lib/method.js b/lib/method.js index 031c5d0..f059bcb 100644 --- a/lib/method.js +++ b/lib/method.js @@ -75,7 +75,7 @@ class Method { } let sql = parser.select(select) - sql += `FROM \`${table}\` ` + sql += `FROM ${table} ` if (leftJoin) { sql += parser.leftJoin(leftJoin) } @@ -130,7 +130,7 @@ class Method { return Promise.reject('Insert Error: empty table') } - let sql = `INSERT INTO \`${table}\` ` + let sql = `INSERT INTO ${table} ` let keys = [] let vals = [] diff --git a/lib/parser.js b/lib/parser.js index 9fbe7da..0d0eac9 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -6,38 +6,6 @@ */ const { escape } = require('mysql') -/** - * [parseWhere 格式化where条件] - * @param [array] arr [条件数组] - */ - -/*function parseWhere(arr) { - if (typeof arr === 'string' && !!arr) { - return ' WHERE ' + arr - } else if (Array.isArray(arr) && arr.length > 0) { - let where = '' - for (let it of arr) { - it.join = it.join || 'AND' - it.op = it.op || '=' - - let fixVal = it.val - if ( - !/(^\(SELECT\s+.*\)$)|^`/.test(it.val) && - !['IN', 'BETWEEN'].includes(it.op) - ) { - fixVal = escape(it.val) - } - - where += `${it.join.toUpperCase()} ${it.key} ${it.op} ${fixVal} ` - } - - where = ' WHERE ' + where.trim().replace(/^(AND|OR)/, ' ') + ' ' - return where - } else { - return ' ' - } -}*/ - function getType(val) { if (val === null) { return String(val) @@ -87,7 +55,7 @@ function parse$opt(opt) { break } if (tmp.$sql) { - sql += ` ${k} IN ${tmp.$sql} ` + sql += ` ${k} ${tmp.$sql} ` break } @@ -98,6 +66,33 @@ function parse$opt(opt) { sql += ` ${k} IN (${list.join(',')}) ` break } + if (tmp.$between) { + if (tmp.$between.length < 2) { + throw new Error(`Array $between's length must be 2.`) + } + let list = tmp.$between.map(it => { + return escape(it) + }) + sql += ` ${k} BETWEEN ${list[0]} AND ${list[1]} ` + break + } + // 比较 + if (tmp.$lt || tmp.$lte) { + sql += ` ${k} <${tmp.$lte ? '=' : ''} ${tmp.$lt || tmp.$lte} ` + if (tmp.$gt || tmp.$gte) { + sql += ` AND ${k} >${tmp.$gte ? '=' : ''} ${tmp.$gt || tmp.$gte} ` + } + break + } + if (tmp.$gt || tmp.$gte) { + sql += ` ${k} >${tmp.$gte ? '=' : ''} ${tmp.$gt || tmp.$gte} ` + break + } + + if (tmp.$eq) { + sql += ` ${k} = ${tmp.$eq} ` + break + } default: sql += ` ${k} = ${escape(tmp)}` } @@ -145,7 +140,7 @@ const Parser = { } else if (opt.$or) { return parse$or(opt.$or) } - return parse$opt(opt) + return ` WHERE ${parse$opt(opt)}` } return ' '