diff --git a/.travis.yml b/.travis.yml index 17eb39f..4f19520 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - '6' + - '8' sudo: false script: - "npm test" diff --git a/lib/parser.js b/lib/parser.js index f7383cf..0cb43a3 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -1,5 +1,5 @@ const helper = require('think-helper'); -const {Parser} = require('think-model-abstract'); +const { Parser } = require('think-model-abstract'); module.exports = class MysqlParser extends Parser { /** @@ -23,6 +23,8 @@ module.exports = class MysqlParser extends Parser { */ escapeString(str) { if (!str) return ''; + + // eslint-disable-next-line no-control-regex return str.replace(/[\0\n\r\b\t\\'"\x1a]/g, s => { switch (s) { case '\0': @@ -42,4 +44,39 @@ module.exports = class MysqlParser extends Parser { } }); } + + /** + * get insert sql + * @param {Object} options + */ + buildInsertSql(options, replace) { + const isUpdate = helper.isObject(options.update) || helper.isArray(options.update); + if (replace || !isUpdate) { + return super.buildInsertSql(options, replace); + } + + const table = this.parseTable(options.table); + const values = options.values[0] !== '(' ? `(${options.values})` : options.values; + + let sets = []; + if (helper.isArray(options.update)) { + sets = options.update.map(field => { + field = this.parseKey(field); + return field + '=' + `VALUES(${field})`; + }); + } else { + for (const key in options.update) { + const value = this.parseValue(options.update[key]); + if (helper.isString(value) || helper.isNumber(value) || helper.isBoolean(value)) { + sets.push(this.parseKey(key) + '=' + value); + } + } + } + + const duplicateUpdate = sets.length ? ' ON DUPLICATE KEY UPDATE ' + sets.join(',') : ''; + const lock = this.parseLock(options.lock); + const comment = this.parseComment(options.comment); + + return `INSERT INTO ${table} (${options.fields}) VALUES ${values}${duplicateUpdate}${lock}${comment}`; + } }; diff --git a/package.json b/package.json index 30847f2..a05ae06 100644 --- a/package.json +++ b/package.json @@ -26,27 +26,16 @@ }, "homepage": "https://github.com/thinkjs/think-model-mysql#readme", "dependencies": { - "think-debounce": "^1.0.3", - "think-helper": "^1.0.5", - "think-model-abstract": "^1.0.5", - "think-mysql": "^1.0.2" + "think-debounce": "^1.0.4", + "think-helper": "^1.1.2", + "think-model-abstract": "^1.2.2", + "think-mysql": "^1.2.4" }, "devDependencies": { "ava": "^0.19.1", - "eslint": "^4.2.0", + "eslint": "^4.19.1", "eslint-config-think": "^1.0.1", "muk": "^0.5.3", "nyc": "^10.3.0" - }, - "ava": { - "require": [ - "babel-register" - ], - "babel": "inherit" - }, - "babel": { - "presets": [ - "think-node" - ] } -} +} \ No newline at end of file