完成条件的解析

master
宇天 2018-03-03 20:10:31 +08:00
parent b5330c859c
commit 041e633849
2 changed files with 31 additions and 36 deletions

View File

@ -75,7 +75,7 @@ class Method {
} }
let sql = parser.select(select) let sql = parser.select(select)
sql += `FROM \`${table}\` ` sql += `FROM ${table} `
if (leftJoin) { if (leftJoin) {
sql += parser.leftJoin(leftJoin) sql += parser.leftJoin(leftJoin)
} }
@ -130,7 +130,7 @@ class Method {
return Promise.reject('Insert Error: empty table') return Promise.reject('Insert Error: empty table')
} }
let sql = `INSERT INTO \`${table}\` ` let sql = `INSERT INTO ${table} `
let keys = [] let keys = []
let vals = [] let vals = []

View File

@ -6,38 +6,6 @@
*/ */
const { escape } = require('mysql') 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) { function getType(val) {
if (val === null) { if (val === null) {
return String(val) return String(val)
@ -87,7 +55,7 @@ function parse$opt(opt) {
break break
} }
if (tmp.$sql) { if (tmp.$sql) {
sql += ` ${k} IN ${tmp.$sql} ` sql += ` ${k} ${tmp.$sql} `
break break
} }
@ -98,6 +66,33 @@ function parse$opt(opt) {
sql += ` ${k} IN (${list.join(',')}) ` sql += ` ${k} IN (${list.join(',')}) `
break 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: default:
sql += ` ${k} = ${escape(tmp)}` sql += ` ${k} = ${escape(tmp)}`
} }
@ -145,7 +140,7 @@ const Parser = {
} else if (opt.$or) { } else if (opt.$or) {
return parse$or(opt.$or) return parse$or(opt.$or)
} }
return parse$opt(opt) return ` WHERE ${parse$opt(opt)}`
} }
return ' ' return ' '