From 0441103d6f77cc524674bfa755d70098882cad0d Mon Sep 17 00:00:00 2001 From: Erik Man Date: Sat, 8 Jul 2017 20:31:31 +0200 Subject: [PATCH] Make it possible to have '' as default value --- lib/sqlutil.js | 13 ++++++++++++- test/sqlutil.js | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/lib/sqlutil.js b/lib/sqlutil.js index ca092c0..91b0886 100644 --- a/lib/sqlutil.js +++ b/lib/sqlutil.js @@ -928,7 +928,18 @@ export class Table { let primaryKey = column.primaryKey ? ' PRIMARY KEY' : ''; let unique = column.unique && !column.primaryKey ? ' UNIQUE' : ''; let notNull = column.notNull && !column.primaryKey ? ' NOT NULL' : ''; - let defaultValue = !_.isUndefined(column.defaultValue) && !_.isNull(column.defaultValue) ? ` DEFAULT ${column.defaultValue}` : ''; + let defaultValue = ''; + if (!_.isUndefined(column.defaultValue) && !_.isNull(column.defaultValue)) { + if (_.isNumber(column.defaultValue)) { + defaultValue = ` DEFAULT ${column.defaultValue}`; + } + else if (_.isString(column.defaultValue)) { + defaultValue = ` DEFAULT "${column.defaultValue}"`; + } + else { + throw new Error(`Invalid type for default value for column ${columnName}`); + } + } columnDescriptions.push(`${columnName} ${column.type}${primaryKey}${unique}${notNull}${defaultValue}`); diff --git a/test/sqlutil.js b/test/sqlutil.js index da37a1d..f89bf0a 100644 --- a/test/sqlutil.js +++ b/test/sqlutil.js @@ -113,6 +113,29 @@ describe('sqlutil', () => { }); }); + it('should be possible to have default value \'\' for columns', () => { + let defaultValueTable = new sqlutil.Table(db, { + name: 'defaultValueTableEmptyString', + columns: { + id: {type: sqlutil.DataType.INTEGER, primaryKey: true}, + name: {type: sqlutil.DataType.TEXT, unique: true}, + value: {type: sqlutil.DataType.TEXT, notNull: true, defaultValue: ''} + } + }); + + return defaultValueTable.createTable() + .then(() => defaultValueTable.insert({name: 'keyWithValue', value: '1'})) + .then(() => defaultValueTable.insert({name: 'keyWithoutValue'})) + .then(() => { + return expect(defaultValueTable.find({name: 'keyWithValue'}).get()) + .to.eventually.deep.equal({id: 1, name: 'keyWithValue', value: '1'}); + }) + .then(() => { + return expect(defaultValueTable.find({name: 'keyWithoutValue'}).get()) + .to.eventually.deep.equal({id: 2, name: 'keyWithoutValue', value: ''}); + }); + }); + it('should be possible to have non-unique indices', () => { let indexTable = new sqlutil.Table(db, { name: 'indexTable',