Skip to content

Commit a0b2473

Browse files
authored
fix: expand object params after ON DUPLICATE KEY UPDATE preceded by SET (#19)
1 parent f9859b2 commit a0b2473

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

src/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,10 +144,10 @@ const findNextPlaceholder = (sql: string, start: number): number => {
144144
return -1;
145145
};
146146

147-
const findSetKeyword = (sql: string): number => {
147+
const findSetKeyword = (sql: string, startFrom = 0): number => {
148148
const length = sql.length;
149149

150-
for (let position = 0; position < length; position++) {
150+
for (let position = startFrom; position < length; position++) {
151151
const code = sql.charCodeAt(position);
152152
const lower = code | 32;
153153

@@ -463,7 +463,7 @@ export const format = (
463463
isRecord(currentValue)
464464
) {
465465
escapedValue = objectToValues(currentValue, timezone);
466-
setIndex = -1;
466+
setIndex = findSetKeyword(sql, placeholderEnd);
467467
} else escapedValue = escape(currentValue, true, timezone);
468468
} else escapedValue = escape(currentValue, stringifyObjects, timezone);
469469

test/everyday-queries.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,27 @@ describe('Critical: ON DUPLICATE KEY UPDATE with raw() values', () => {
148148
"INSERT INTO t (id, name) VALUES (1, 'test') ON DUPLICATE KEY UPDATE `name` = 'updated', `modified` = CURRENT_TIMESTAMP"
149149
);
150150
});
151+
152+
test('INSERT ... SET ? ON DUPLICATE KEY UPDATE ? with two objects', () => {
153+
const dataInsert = {
154+
aula: 'Math101',
155+
fecha: '2024-01-15',
156+
texto: 'Lesson content',
157+
tipo: 'lecture',
158+
imagen: 'image.png',
159+
file: 'notes.pdf',
160+
};
161+
const { aula, fecha, tipo, ...dataUpdate } = dataInsert;
162+
const sql = format(
163+
'INSERT INTO column SET ? ON DUPLICATE KEY UPDATE ?',
164+
[dataInsert, dataUpdate],
165+
false
166+
);
167+
assert.equal(
168+
sql,
169+
"INSERT INTO column SET `aula` = 'Math101', `fecha` = '2024-01-15', `texto` = 'Lesson content', `tipo` = 'lecture', `imagen` = 'image.png', `file` = 'notes.pdf' ON DUPLICATE KEY UPDATE `texto` = 'Lesson content', `imagen` = 'image.png', `file` = 'notes.pdf'"
170+
);
171+
});
151172
});
152173

153174
describe('Critical: stringifyObjects=undefined (mysqljs/mysql legacy mode)', () => {

0 commit comments

Comments
 (0)