From 041e633849543c58291f9f3b48d01e2118ff41cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=87=E5=A4=A9?= Date: Sat, 3 Mar 2018 20:10:31 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E6=9D=A1=E4=BB=B6=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/method.js | 4 ++-- lib/parser.js | 63 ++++++++++++++++++++++++--------------------------- 2 files changed, 31 insertions(+), 36 deletions(-) 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 ' '