Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion lib/sqlutil.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);

Expand Down
23 changes: 23 additions & 0 deletions test/sqlutil.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down