Skip to content

Commit

Permalink
Add support for the JSON MySQL type
Browse files Browse the repository at this point in the history
MySQL supports the JSON type since 5.7.8 which is a nice way to store and work with nested documents.
  • Loading branch information
dangoodman committed Sep 4, 2018
1 parent 91e5a94 commit 0bf30ab
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ const NATIVE_TYPES = {
val = val.replace(controlRegex, '')
return val
}
},
'JSON': {
type: 'JSON',
convert: val => {
if (val === null || val === undefined) {
return null
}
return sqlstring.escape(JSON.stringify(val))
}
}
}

Expand Down
13 changes: 13 additions & 0 deletions test/specs/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,17 @@ describe('Momy Types', () => {
assert.equal(convert(undefined), "''")
assert.equal(convert('\x07'), "''") // skip a control char
})

it('JSON', () => {
const convert = NATIVE_TYPES.JSON.convert
assert.equal(convert(null), null)
assert.equal(convert(undefined), null)
assert.equal(convert({a: null, b: undefined}), '\'{\\"a\\":null}\'')
assert.equal(convert(true), '\'true\'')
assert.equal(convert(false), '\'false\'')
assert.equal(convert('string'), '\'\\"string\\"\'')
assert.equal(convert([1, 2, '3']), '\'[1,2,\\"3\\"]\'')
assert.equal(convert({age: 1, name: 'John', ids: [5, 10, 15]}), '\'{\\"age\\":1,\\"name\\":\\"John\\",\\"ids\\":[5,10,15]}\'')
assert.equal(convert('\x07\r\n\t'), '\'\\"\\\\u0007\\\\r\\\\n\\\\t\\"\'') // escape control chars
})
})

0 comments on commit 0bf30ab

Please sign in to comment.