diff --git a/src/background/mysql.js b/src/background/mysql.js index 750174b..d45694e 100644 --- a/src/background/mysql.js +++ b/src/background/mysql.js @@ -118,6 +118,60 @@ const expand = (sphinx) => { }) }) + sphinx.replaceValues = (table, values, particial = true, key = 'id', callback = () => {}) => new Promise((resolve) => { + values = Object.assign({}, values) // copy + + let names = ''; + let data = ''; + const parseValues = (values) => { + let valuesData = '' + names = '' + for(const val in values) + { + if(values[val] === null) + continue; + + if(typeof values[val] == 'object') + values[val] = JSON.stringify(values[val]) + + names += '`' + val + '`,'; + valuesData += sphinx.escape(values[val]) + ','; + } + names = names.slice(0, -1) + valuesData = valuesData.slice(0, -1) + return valuesData + } + const finalQuery = () => { + let query = `REPLACE INTO ${table}(${names}) VALUES ${data}`; + queryCall(query, (...responce) => { + if(callback) + callback(...responce) + resolve(...responce) + }) + } + + if(particial) + { + queryCall(`SELECT * from ${table} WHERE \`${key}\` = ${sphinx.escape(values[key])}`, (err, row) => { + if(err || row.length == 0) + { + logTE('sql', 'error on sql replace request', row) + resolve(undefined) + callback(undefined) + return + } + + data = `(${parseValues(Object.assign(row[0], values))})` + finalQuery() + }) + } + else + { + data = `(${parseValues(values)})` + finalQuery() + } + }) + return sphinx } diff --git a/tests/sphinx.api.test.js b/tests/sphinx.api.test.js new file mode 100644 index 0000000..5af6c7d --- /dev/null +++ b/tests/sphinx.api.test.js @@ -0,0 +1,31 @@ +import { assert } from "chai"; +const {pool} = require('../src/background/mysql') + +describe("big table for check", () => { + let sphinx; + + it("init", async function() { + sphinx = await pool() + assert(sphinx) + await sphinx.query(`delete from feed where id >= 1`) + }) + + it("replace with add", async function() { + await sphinx.query(`insert into feed(id, data) values(1, '{a: 1}')`) + assert.equal((await sphinx.query(`select data from feed where id = 1`))[0].data, '{"a":1}') + await sphinx.replaceValues('feed', {id: 1, data: {a: 1, b: 2}}, true) + assert.equal((await sphinx.query(`select data from feed`))[0].data, '{"a":1,"b":2}') + }) + + it("replace without add", async function() { + await sphinx.query(`insert into feed(id, data) values(2, '{a: 1}')`) + + await sphinx.replaceValues('feed', {id: 1, data: {a: 1, b: 2, c: 3}}, false) + assert.equal((await sphinx.query(`select data from feed where id = 1`))[0].data, '{"a":1,"b":2,"c":3}') + assert.equal((await sphinx.query(`select count(*) as c from feed`))[0].c, 2) + }) + + it("close", async function() { + await sphinx.end() + }) +});