sequelize.test.js
29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
var chai = require('chai')
, expect = chai.expect
, assert = chai.assert
, Support = require(__dirname + '/support')
, DataTypes = require(__dirname + "/../lib/data-types")
, dialect = Support.getTestDialect()
, _ = require('lodash')
, Sequelize = require(__dirname + '/../index')
, config = require(__dirname + "/config/config")
, moment = require('moment')
, Transaction = require(__dirname + '/../lib/transaction')
, path = require('path')
, sinon = require('sinon')
chai.Assertion.includeStack = true
var qq = function(str) {
if (dialect == 'postgres' || dialect == 'sqlite') {
return '"' + str + '"'
} else if (Support.dialectIsMySQL()) {
return '`' + str + '`'
} else {
return str
}
}
describe(Support.getTestDialectTeaser("Sequelize"), function () {
describe('constructor', function() {
it('should pass the global options correctly', function(done) {
var sequelize = Support.createSequelizeInstance({ logging: false, define: { underscored:true } })
, DAO = sequelize.define('dao', {name: DataTypes.STRING})
expect(DAO.options.underscored).to.be.ok
done()
})
it('should correctly set the host and the port', function(done) {
var sequelize = Support.createSequelizeInstance({ host: '127.0.0.1', port: 1234 })
expect(sequelize.config.port).to.equal(1234)
expect(sequelize.config.host).to.equal('127.0.0.1')
done()
})
if (dialect === 'sqlite') {
it('should work with connection strings (1)', function () {
var sequelize = new Sequelize('sqlite://test.sqlite')
})
it('should work with connection strings (2)', function () {
var sequelize = new Sequelize('sqlite://test.sqlite/')
})
it('should work with connection strings (3)', function () {
var sequelize = new Sequelize('sqlite://test.sqlite/lol?reconnect=true')
})
}
})
if (dialect !== 'sqlite') {
describe('authenticate', function() {
describe('with valid credentials', function() {
it('triggers the success event', function(done) {
this.sequelize.authenticate().success(done)
})
})
describe('with an invalid connection', function() {
beforeEach(function() {
var options = _.extend({}, this.sequelize.options, { port: "99999" })
this.sequelizeWithInvalidConnection = new Sequelize("wat", "trololo", "wow", options)
})
it('triggers the error event', function(done) {
this
.sequelizeWithInvalidConnection
.authenticate()
.complete(function(err, result) {
expect(err).to.not.be.null
done()
})
})
it('triggers the actual adapter error', function(done) {
this
.sequelizeWithInvalidConnection
.authenticate()
.complete(function(err, result) {
if (dialect === 'mariadb') {
expect(err.message).to.match(/Access denied for user/)
} else if (dialect === 'postgres') {
expect(err.message).to.match(/invalid port number/)
} else {
expect(err.message).to.match(/Failed to authenticate/)
}
done()
})
})
})
describe('with invalid credentials', function() {
beforeEach(function() {
this.sequelizeWithInvalidCredentials = new Sequelize("localhost", "wtf", "lol", this.sequelize.options)
})
it('triggers the error event', function(done) {
this
.sequelizeWithInvalidCredentials
.authenticate()
.complete(function(err, result) {
expect(err).to.not.be.null
done()
})
})
it('triggers the error event when using replication', function (done) {
new Sequelize('sequelize', null, null, {
replication: {
read: {
host: 'localhost',
username: 'omg',
password: 'lol'
}
}
}).authenticate()
.complete(function(err, result) {
expect(err).to.not.be.null
done()
})
})
})
})
describe('validate', function() {
it('is an alias for .authenticate()', function() {
expect(this.sequelize.validate).to.equal(this.sequelize.authenticate)
})
})
}
describe('getDialect', function() {
it('returns the defined dialect', function() {
expect(this.sequelize.getDialect()).to.equal(dialect)
})
})
describe('isDefined', function() {
it("returns false if the dao wasn't defined before", function() {
expect(this.sequelize.isDefined('Project')).to.be.false
})
it("returns true if the dao was defined before", function() {
this.sequelize.define('Project', {
name: DataTypes.STRING
})
expect(this.sequelize.isDefined('Project')).to.be.true
})
})
describe('model', function() {
it('throws an error if the dao being accessed is undefined', function() {
var self = this
expect(function() {
self.sequelize.model('Project')
}).to.throw(/project has not been defined/i)
})
it('returns the dao factory defined by daoName', function() {
var project = this.sequelize.define('Project', {
name: DataTypes.STRING
})
expect(this.sequelize.model('Project')).to.equal(project)
})
})
describe('query', function() {
afterEach(function(done) {
this.sequelize.options.quoteIdentifiers = true
done()
})
beforeEach(function(done) {
this.User = this.sequelize.define('User', {
username: DataTypes.STRING
})
this.insertQuery = "INSERT INTO " + qq(this.User.tableName) + " (username, " + qq("createdAt") + ", " + qq("updatedAt") + ") VALUES ('john', '2012-01-01 10:10:10', '2012-01-01 10:10:10')"
this.User.sync({ force: true }).success(function() {
done()
})
})
it('executes a query the internal way', function(done) {
this.sequelize.query(this.insertQuery, null, { raw: true })
.complete(function(err, result) {
expect(err).to.be.null
expect(result).to.be.null
done()
})
})
it('executes a query if only the sql is passed', function(done) {
this.sequelize.query(this.insertQuery)
.complete(function(err, result) {
expect(err).to.be.null
expect(result).to.not.exist
done()
})
})
it('executes select queries correctly', function(done) {
var self = this
self.sequelize.query(this.insertQuery).success(function() {
self.sequelize
.query("select * from " + qq(self.User.tableName) + "")
.complete(function(err, users) {
expect(err).to.be.null
expect(users.map(function(u){ return u.username })).to.include('john')
done()
})
})
})
it('executes select queries correctly when quoteIdentifiers is false', function(done) {
var self = this
, seq = Object.create(self.sequelize)
seq.options.quoteIdentifiers = false
seq.query(this.insertQuery).success(function() {
seq.query("select * from " + qq(self.User.tableName) + "")
.complete(function(err, users) {
expect(err).to.be.null
expect(users.map(function(u){ return u.username })).to.include('john')
done()
})
})
})
it('executes select query and parses dot notation results', function(done) {
var self = this
self.sequelize.query('DELETE FROM ' + qq(self.User.tableName)).complete(function() {
self.sequelize.query(self.insertQuery).success(function() {
self.sequelize
.query("select username as " + qq("user.username") + " from " + qq(self.User.tableName) + "")
.complete(function(err, users) {
expect(err).to.be.null
expect(users.map(function(u){ return u.user })).to.deep.equal([{'username':'john'}])
done()
})
})
})
})
if (Support.dialectIsMySQL()) {
it('executes stored procedures', function(done) {
var self = this
self.sequelize.query(this.insertQuery).success(function() {
self.sequelize.query('DROP PROCEDURE IF EXISTS foo').success(function() {
self.sequelize.query(
"CREATE PROCEDURE foo()\nSELECT * FROM " + self.User.tableName + ";"
).success(function() {
self.sequelize.query('CALL foo()').success(function(users) {
expect(users.map(function(u){ return u.username })).to.include('john')
done()
})
})
})
})
})
} else {
console.log('FIXME: I want to be supported in this dialect as well :-(')
}
it('uses the passed DAOFactory', function(done) {
var self = this
self.sequelize.query(this.insertQuery).success(function() {
self.sequelize.query("SELECT * FROM " + qq(self.User.tableName) + ";", self.User).success(function(users) {
expect(users[0].__factory).to.equal(self.User)
done()
})
})
})
it('destructs dot separated attributes when doing a raw query', function(done) {
var tickChar = (dialect === 'postgres') ? '"' : '`'
, sql = "select 1 as " + Sequelize.Utils.addTicks('foo.bar.baz', tickChar)
this.sequelize.query(sql, null, { raw: true }).success(function(result) {
expect(result).to.deep.equal([ { foo: { bar: { baz: 1 } } } ])
done()
})
})
it('replaces token with the passed array', function(done) {
this.sequelize.query('select ? as foo, ? as bar', null, { raw: true }, [ 1, 2 ]).success(function(result) {
expect(result).to.deep.equal([{ foo: 1, bar: 2 }])
done()
})
})
it('replaces named parameters with the passed object', function(done) {
this.sequelize.query('select :one as foo, :two as bar', null, { raw: true }, { one: 1, two: 2 }).success(function(result) {
expect(result).to.deep.equal([{ foo: 1, bar: 2 }])
done()
})
})
it('replaces named parameters with the passed object and ignore those which does not qualify', function(done) {
this.sequelize.query('select :one as foo, :two as bar, \'00:00\' as baz', null, { raw: true }, { one: 1, two: 2 }).success(function(result) {
expect(result).to.deep.equal([{ foo: 1, bar: 2, baz: '00:00' }])
done()
})
})
it('replaces named parameters with the passed object using the same key twice', function(done) {
this.sequelize.query('select :one as foo, :two as bar, :one as baz', null, { raw: true }, { one: 1, two: 2 }).success(function(result) {
expect(result).to.deep.equal([{ foo: 1, bar: 2, baz: 1 }])
done()
})
})
it('replaces named parameters with the passed object having a null property', function(done) {
this.sequelize.query('select :one as foo, :two as bar', null, { raw: true }, { one: 1, two: null }).success(function(result) {
expect(result).to.deep.equal([{ foo: 1, bar: null }])
done()
})
})
it('throw an exception when key is missing in the passed object', function(done) {
var self = this
expect(function() {
self.sequelize.query('select :one as foo, :two as bar, :three as baz', null, { raw: true }, { one: 1, two: 2 })
}).to.throw(Error, /Named parameter ":\w+" has no value in the given object\./g)
done()
})
it('throw an exception with the passed number', function(done) {
var self = this
expect(function() {
self.sequelize.query('select :one as foo, :two as bar', null, { raw: true }, 2)
}).to.throw(Error, /Named parameter ":\w+" has no value in the given object\./g)
done()
})
it('throw an exception with the passed empty object', function(done) {
var self = this
expect(function() {
self.sequelize.query('select :one as foo, :two as bar', null, { raw: true }, {})
}).to.throw(Error, /Named parameter ":\w+" has no value in the given object\./g)
done()
})
it('throw an exception with the passed string', function(done) {
var self = this
expect(function() {
self.sequelize.query('select :one as foo, :two as bar', null, { raw: true }, 'foobar')
}).to.throw(Error, /Named parameter ":\w+" has no value in the given object\./g)
done()
})
it('throw an exception with the passed date', function(done) {
var self = this
expect(function() {
self.sequelize.query('select :one as foo, :two as bar', null, { raw: true }, new Date())
}).to.throw(Error, /Named parameter ":\w+" has no value in the given object\./g)
done()
})
it('handles AS in conjunction with functions just fine', function(done) {
this.sequelize.query('SELECT ' + (dialect === "sqlite" ? 'date(\'now\')' : 'NOW()') + ' AS t').success(function(result) {
expect(moment(result[0].t).isValid()).to.be.true
done()
})
})
if (Support.getTestDialect() === 'postgres') {
it('supports WITH queries', function(done) {
this
.sequelize
.query("WITH RECURSIVE t(n) AS ( VALUES (1) UNION ALL SELECT n+1 FROM t WHERE n < 100) SELECT sum(n) FROM t")
.success(function(results) {
expect(results).to.deep.equal([ { "sum": "5050" } ])
done()
})
})
}
})
describe('define', function() {
it("adds a new dao to the dao manager", function(done) {
expect(this.sequelize.daoFactoryManager.all.length).to.equal(0)
this.sequelize.define('foo', { title: DataTypes.STRING })
expect(this.sequelize.daoFactoryManager.all.length).to.equal(1)
done()
})
it("overwrites global options", function(done) {
var sequelize = Support.createSequelizeInstance({ define: { collate: 'utf8_general_ci' } })
var DAO = sequelize.define('foo', {bar: DataTypes.STRING}, {collate: 'utf8_bin'})
expect(DAO.options.collate).to.equal('utf8_bin')
done()
})
it("inherits global collate option", function(done) {
var sequelize = Support.createSequelizeInstance({ define: { collate: 'utf8_general_ci' } })
var DAO = sequelize.define('foo', {bar: DataTypes.STRING})
expect(DAO.options.collate).to.equal('utf8_general_ci')
done()
})
it("inherits global classMethods and instanceMethods", function(done) {
var sequelize = Support.createSequelizeInstance({
define: {
classMethods : { globalClassMethod : function() {} },
instanceMethods : { globalInstanceMethod : function() {} }
}
})
var DAO = sequelize.define('foo', {bar: DataTypes.STRING}, {
classMethods : { localClassMethod : function() {} }
})
expect(typeof DAO.options.classMethods.globalClassMethod).to.equal('function')
expect(typeof DAO.options.classMethods.localClassMethod).to.equal('function')
expect(typeof DAO.options.instanceMethods.globalInstanceMethod).to.equal('function')
done()
})
it("uses the passed tableName", function(done) {
var self = this
, Photo = this.sequelize.define('Foto', { name: DataTypes.STRING }, { tableName: 'photos' })
Photo.sync({ force: true }).success(function() {
self.sequelize.getQueryInterface().showAllTables().success(function(tableNames) {
expect(tableNames).to.include('photos')
done()
})
})
})
})
describe('sync', function() {
it("synchronizes all daos", function(done) {
var Project = this.sequelize.define('project' + config.rand(), { title: DataTypes.STRING })
var Task = this.sequelize.define('task' + config.rand(), { title: DataTypes.STRING })
Project.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
Project.create({title: 'bla'}).success(function() {
Task.create({title: 'bla'}).success(function(task){
expect(task).to.exist
expect(task.title).to.equal('bla')
done()
})
})
})
})
})
it('works with correct database credentials', function(done) {
var User = this.sequelize.define('User', { username: DataTypes.STRING })
User.sync().success(function() {
expect(true).to.be.true
done()
})
})
if (dialect !== "sqlite") {
it("fails with incorrect database credentials (1)", function(done) {
this.sequelizeWithInvalidCredentials = new Sequelize("omg", "bar", null, _.omit(this.sequelize.options, ['host']))
var User2 = this.sequelizeWithInvalidCredentials.define('User', { name: DataTypes.STRING, bio: DataTypes.TEXT })
User2.sync().error(function(err) {
if (dialect === "postgres" || dialect === "postgres-native") {
assert([
'fe_sendauth: no password supplied',
'role "bar" does not exist',
'FATAL: role "bar" does not exist',
'password authentication failed for user "bar"'
].indexOf(err.message.trim()) !== -1)
} else {
expect(err.message.toString()).to.match(/.*Access\ denied.*/)
}
done()
})
})
it('fails with incorrect database credentials (2)', function (done) {
var sequelize = new Sequelize('db', 'user', 'pass', {
dialect: this.sequelize.options.dialect
});
var Project = sequelize.define('Project', {title: Sequelize.STRING})
var Task = sequelize.define('Task', {title: Sequelize.STRING})
sequelize.sync({force: true}).done(function (err) {
expect(err).to.be.ok
done()
})
})
it('fails with incorrect database credentials (3)', function (done) {
var sequelize = new Sequelize('db', 'user', 'pass', {
dialect: this.sequelize.options.dialect,
port: 99999
});
var Project = sequelize.define('Project', {title: Sequelize.STRING})
var Task = sequelize.define('Task', {title: Sequelize.STRING})
sequelize.sync({force: true}).done(function (err) {
expect(err).to.be.ok
done()
})
})
it('fails with incorrect database credentials (4)', function (done) {
var sequelize = new Sequelize('db', 'user', 'pass', {
dialect: this.sequelize.options.dialect,
port: 99999,
pool: {}
});
var Project = sequelize.define('Project', {title: Sequelize.STRING})
var Task = sequelize.define('Task', {title: Sequelize.STRING})
sequelize.sync({force: true}).done(function (err) {
expect(err).to.be.ok
done()
})
})
it('returns an error correctly if unable to sync a foreign key referenced model', function (done) {
var Application = this.sequelize.define('Application', {
authorID: { type: Sequelize.BIGINT, allowNull: false, references: 'User', referencesKey: 'id' },
})
this.sequelize.sync().error(function (error) {
assert.ok(error);
done()
})
})
it('handles self dependant foreign key constraints', function (done) {
var block = this.sequelize.define("block", {
id: { type: DataTypes.INTEGER, primaryKey: true },
name: DataTypes.STRING
}, {
tableName: "block",
timestamps: false,
paranoid: false
});
block.hasMany(block, {
as: 'childBlocks',
foreignKey: 'parent',
joinTableName: 'link_block_block',
useJunctionTable: true,
foreignKeyConstraint: true
});
block.belongsTo(block, {
as: 'parentBlocks',
foreignKey: 'child',
joinTableName: 'link_block_block',
useJunctionTable: true,
foreignKeyConstraint: true
});
this.sequelize.sync().done(done)
})
}
describe("doesn't emit logging when explicitly saying not to", function() {
afterEach(function(done) {
this.sequelize.options.logging = false
done()
})
beforeEach(function(done) {
this.spy = sinon.spy()
var self = this
this.sequelize.options.logging = function() { self.spy() }
this.User = this.sequelize.define('UserTest', { username: DataTypes.STRING })
done()
})
it('through Sequelize.sync()', function(done) {
var self = this
this.sequelize.sync({ force: true, logging: false }).success(function() {
expect(self.spy.notCalled).to.be.true
done()
})
})
it('through DAOFactory.sync()', function(done) {
var self = this
this.User.sync({ force: true, logging: false }).success(function() {
expect(self.spy.notCalled).to.be.true
done()
})
})
})
})
describe('drop should work', function() {
it('correctly succeeds', function(done) {
var User = this.sequelize.define('Users', {username: DataTypes.STRING })
User.sync({ force: true }).success(function() {
User.drop().success(function() {
expect(true).to.be.true
done()
})
})
})
})
describe('import', function() {
it("imports a dao definition from a file absolute path", function(done) {
var Project = this.sequelize.import(__dirname + "/assets/project")
expect(Project).to.exist
done()
})
it("imports a dao definition from a function", function(done) {
var Project = this.sequelize.import('Project', function(sequelize, DataTypes) {
return sequelize.define('Project' + parseInt(Math.random() * 9999999999999999), {
name: DataTypes.STRING
})
})
expect(Project).to.exist
done()
})
})
describe('define', function() {
[
{ type: DataTypes.ENUM, values: ['scheduled', 'active', 'finished']},
DataTypes.ENUM('scheduled', 'active', 'finished')
].forEach(function(status) {
describe('enum', function() {
beforeEach(function(done) {
this.Review = this.sequelize.define('review', { status: status })
this.Review.sync({ force: true }).success(function() {
done()
})
})
it('raises an error if no values are defined', function(done) {
var self = this
expect(function() {
self.sequelize.define('omnomnom', {
bla: { type: DataTypes.ENUM }
})
}).to.throw(Error, 'Values for ENUM haven\'t been defined.')
done()
})
it('correctly stores values', function(done) {
this.Review.create({ status: 'active' }).success(function(review) {
expect(review.status).to.equal('active')
done()
})
})
it('correctly loads values', function(done) {
var self = this
this.Review.create({ status: 'active' }).success(function() {
self.Review.findAll().success(function(reviews) {
expect(reviews[0].status).to.equal('active')
done()
})
})
})
it("doesn't save an instance if value is not in the range of enums", function(done) {
this.Review.create({status: 'fnord'}).error(function(err) {
expect(err).to.deep.equal({ status: [ 'Value "fnord" for ENUM status is out of allowed scope. Allowed values: scheduled, active, finished' ] })
done()
})
})
})
})
describe('table', function() {
[
{ id: { type: DataTypes.BIGINT } },
{ id: { type: DataTypes.STRING, allowNull: true } },
{ id: { type: DataTypes.BIGINT, allowNull: false, primaryKey: true, autoIncrement: true } }
].forEach(function(customAttributes) {
it('should be able to override options on the default attributes', function(done) {
var Picture = this.sequelize.define('picture', _.cloneDeep(customAttributes))
Picture.sync({ force: true }).success(function() {
Object.keys(customAttributes).forEach(function(attribute) {
Object.keys(customAttributes[attribute]).forEach(function(option) {
var optionValue = customAttributes[attribute][option];
expect(Picture.rawAttributes[attribute][option]).to.be.equal(optionValue)
})
})
done()
})
})
})
})
describe('transaction', function() {
beforeEach(function(done) {
var self = this
Support.prepareTransactionTest(this.sequelize, function(sequelize) {
self.sequelizeWithTransaction = sequelize
done()
})
})
it('is a transaction method available', function() {
expect(Support.Sequelize).to.respondTo('transaction')
})
it('passes a transaction object to the callback', function(done) {
this.sequelizeWithTransaction.transaction(function(t) {
expect(t).to.be.instanceOf(Transaction)
done()
})
})
it('returns a transaction object', function() {
expect(this.sequelizeWithTransaction.transaction(function(){})).to.be.instanceOf(Transaction)
})
it('allows me to define a callback on the result', function(done) {
this
.sequelizeWithTransaction
.transaction(function(t) { t.commit() })
.done(done)
})
it('allows me to define a callback on the transaction object', function(done) {
this.sequelizeWithTransaction.transaction(function(t) {
t.done(done)
t.commit()
})
})
if (dialect === 'sqlite') {
it("correctly scopes transaction from other connections", function(done) {
var TransactionTest = this.sequelizeWithTransaction.define('TransactionTest', { name: DataTypes.STRING }, { timestamps: false })
, self = this
var count = function(transaction, callback) {
var sql = self.sequelizeWithTransaction.getQueryInterface().QueryGenerator.selectQuery('TransactionTests', { attributes: [['count(*)', 'cnt']] })
self
.sequelizeWithTransaction
.query(sql, null, { plain: true, raw: true, transaction: transaction })
.success(function(result) { callback(result.cnt) })
}
TransactionTest.sync({ force: true }).success(function() {
self.sequelizeWithTransaction.transaction(function(t1) {
self.sequelizeWithTransaction.query('INSERT INTO ' + qq('TransactionTests') + ' (' + qq('name') + ') VALUES (\'foo\');', null, { plain: true, raw: true, transaction: t1 }).success(function() {
count(null, function(cnt) {
expect(cnt).to.equal(0)
count(t1, function(cnt) {
expect(cnt).to.equal(1)
t1.commit().success(function() {
count(null, function(cnt) {
expect(cnt).to.equal(1)
done()
})
})
})
})
})
})
})
})
} else {
it("correctly handles multiple transactions", function(done) {
var TransactionTest = this.sequelizeWithTransaction.define('TransactionTest', { name: DataTypes.STRING }, { timestamps: false })
, self = this
var count = function(transaction, callback) {
var sql = self.sequelizeWithTransaction.getQueryInterface().QueryGenerator.selectQuery('TransactionTests', { attributes: [['count(*)', 'cnt']] })
self
.sequelizeWithTransaction
.query(sql, null, { plain: true, raw: true, transaction: transaction })
.success(function(result) { callback(parseInt(result.cnt, 10)) })
}
TransactionTest.sync({ force: true }).success(function() {
self.sequelizeWithTransaction.transaction(function(t1) {
self.sequelizeWithTransaction.query('INSERT INTO ' + qq('TransactionTests') + ' (' + qq('name') + ') VALUES (\'foo\');', null, { plain: true, raw: true, transaction: t1 }).success(function() {
self.sequelizeWithTransaction.transaction(function(t2) {
self.sequelizeWithTransaction.query('INSERT INTO ' + qq('TransactionTests') + ' (' + qq('name') + ') VALUES (\'bar\');', null, { plain: true, raw: true, transaction: t2 }).success(function() {
count(null, function(cnt) {
expect(cnt).to.equal(0)
count(t1, function(cnt) {
expect(cnt).to.equal(1)
count(t2, function(cnt) {
expect(cnt).to.equal(1)
t2.rollback().success(function() {
count(t2, function(cnt) {
expect(cnt).to.equal(0)
t1.commit().success(function() {
count(null, function(cnt) {
expect(cnt).to.equal(1)
})
})
})
})
})
})
})
})
})
})
}).done(function() {
done()
})
})
})
}
})
})
})