-
Notifications
You must be signed in to change notification settings - Fork 6
/
SQLitePlugin.coffee.md
1212 lines (937 loc) · 41.6 KB
/
SQLitePlugin.coffee.md
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SQLite plugin in Markdown (litcoffee)
###
License for this version: GPL v3 (http://www.gnu.org/licenses/gpl.txt) or commercial license.
Contact for commercial license: [email protected]
###
#### Use coffee compiler to compile this directly into Javascript
# Top-level SQLite plugin objects
## root window object:
root = @
## constant(s):
READ_ONLY_REGEX = /^(\s|;)*(?:alter|create|delete|drop|insert|reindex|replace|update)/i
# per-db state
DB_STATE_INIT = "INIT"
DB_STATE_OPEN = "OPEN"
## global(s):
# per-db map of locking and queueing
# XXX NOTE: This is NOT cleaned up when a db is closed and/or deleted.
# If the record is simply removed when a db is closed or deleted,
# it will cause some test failures and may break large-scale
# applications that repeatedly open and close the database.
# [BUG #210] TODO: better to abort and clean up the pending transaction state.
# XXX TBD this will be renamed and include some more per-db state.
# NOTE: In case txLocks is renamed or replaced the selfTest has to be adapted as well.
txLocks = {}
## utility functions:
# Errors returned to callbacks must conform to `SqlError` with a code and message.
# Some errors are of type `Error` or `string` and must be converted.
newSQLError = (error, code) ->
sqlError = error
code = 0 if !code # unknown by default
if !sqlError
sqlError = new Error "a plugin had an error but provided no response"
sqlError.code = code
if typeof sqlError is "string"
sqlError = new Error error
sqlError.code = code
if !sqlError.code && sqlError.message
sqlError.code = code
if !sqlError.code && !sqlError.message
sqlError = new Error "an unknown error was returned: " + JSON.stringify(sqlError)
sqlError.code = code
return sqlError
nextTick = window.setImmediate || (fun) ->
window.setTimeout(fun, 0)
return
###
Utility that avoids leaking the arguments object. See
https://www.npmjs.org/package/argsarray
###
argsArray = (fun) ->
return ->
len = arguments.length
if len
args = []
i = -1
while ++i < len
args[i] = arguments[i]
return fun.call this, args
else
return fun.call this, []
## SQLite plugin db-connection handle
#### NOTE: there can be multipe SQLitePlugin db-connection handles per open db.
#### SQLite plugin db connection handle object is defined by a constructor function and prototype member functions:
SQLitePlugin = (openargs, openSuccess, openError) ->
# console.log "SQLitePlugin openargs: #{JSON.stringify openargs}"
# SHOULD already be checked by openDatabase:
if !(openargs and openargs['name'])
throw newSQLError "Cannot create a SQLitePlugin db instance without a db name"
dbname = openargs.name
if typeof dbname != 'string'
throw newSQLError 'sqlite plugin database name must be a string'
@openargs = openargs
@dbname = dbname
@openSuccess = openSuccess
@openError = openError
@openSuccess or
@openSuccess = ->
console.log "DB opened: " + dbname
return
@openError or
@openError = (e) ->
console.log e.message
return
@open @openSuccess, @openError
return
SQLitePlugin::databaseFeatures = isSQLitePluginDatabase: true
# Keep track of state of open db connections
# XXX FUTURE TBD this *may* be moved and renamed,
# or even combined with txLocks if possible.
# NOTE: In case txLocks is renamed or replaced the selfTest has to be adapted as well.
SQLitePlugin::openDBs = {}
SQLitePlugin::dbidmap = {}
SQLitePlugin::fjmap = {}
SQLitePlugin::addTransaction = (t) ->
if !txLocks[@dbname]
txLocks[@dbname] = {
queue: []
inProgress: false
}
txLocks[@dbname].queue.push t
if @dbname of @openDBs && @openDBs[@dbname] isnt DB_STATE_INIT
# FUTURE TBD: rename startNextTransaction to something like
# triggerTransactionQueue
# ALT TBD: only when queue has length of 1 (and test)??
@startNextTransaction()
else
if @dbname of @openDBs
console.log 'new transaction is queued, waiting for open operation to finish'
else
# XXX SHOULD NOT GET HERE.
# FUTURE TBD TODO: in this exceptional case abort and discard the transaction.
console.log 'database is closed, new transaction is [stuck] waiting until db is opened again!'
return
SQLitePlugin::transaction = (fn, error, success) ->
# FUTURE TBD check for valid fn here
if !@openDBs[@dbname]
error newSQLError 'database not open'
return
@addTransaction new SQLitePluginTransaction(this, fn, error, success, true, false)
return
SQLitePlugin::readTransaction = (fn, error, success) ->
# FUTURE TBD check for valid fn here (and add test for this)
if !@openDBs[@dbname]
error newSQLError 'database not open'
return
@addTransaction new SQLitePluginTransaction(this, fn, error, success, false, true)
return
SQLitePlugin::startNextTransaction = ->
self = @
nextTick =>
if !(@dbname of @openDBs) || @openDBs[@dbname] isnt DB_STATE_OPEN
console.log 'cannot start next transaction: database not open'
return
txLock = txLocks[self.dbname]
if !txLock
console.log 'cannot start next transaction: database connection is lost'
# XXX TBD TODO (BUG #210/??): abort all pending transactions with error cb [and test!!]
# @abortAllPendingTransactions()
return
else if txLock.queue.length > 0 && !txLock.inProgress
# start next transaction in q
txLock.inProgress = true
txLock.queue.shift().start()
return
return
SQLitePlugin::abortAllPendingTransactions = ->
# extra debug info:
# if txLocks[@dbname] then console.log 'abortAllPendingTransactions with transaction queue length: ' + txLocks[@dbname].queue.length
# else console.log 'abortAllPendingTransactions with no transaction lock state'
txLock = txLocks[@dbname]
if !!txLock && txLock.queue.length > 0
# XXX TODO: what to do in case there is a (stray) transaction in progress?
#console.log 'abortAllPendingTransactions - cleanup old transaction(s)'
for tx in txLock.queue
tx.abortFromQ newSQLError 'Invalid database handle'
# XXX TODO: consider cleaning up (delete) txLocks[@dbname] resource,
# in case it is known there are no more pending transactions
txLock.queue = []
txLock.inProgress = false
return
SQLitePlugin::open = (success, error) ->
if @dbname of @openDBs
console.log 'database already open: ' + @dbname
@dbid = @dbidmap[@dbname]
# for a re-open run the success cb async so that the openDatabase return value
# can be used in the success handler as an alternative to the handler's
# db argument
nextTick =>
success @
return
# (done)
else
# openDatabase step 1:
console.log 'OPEN database: ' + @dbname
opensuccesscb = (fjinfo) =>
# NOTE: the db state is NOT stored (in @openDBs) if the db was closed or deleted.
console.log 'OPEN database: ' + @dbname + ' - OK'
# distinguish use of flat JSON batch sql interface
if !!fjinfo and !!fjinfo.dbid
console.log 'Detected Android/iOS/macOS platform version with flat JSON interface'
@dbidmap[@dbname] = @dbid = fjinfo.dbid
@fjmap[@dbname] = true
#if !@openDBs[@dbname] then call open error cb, and abort pending tx if any
if !@openDBs[@dbname]
console.log 'database was closed during open operation'
# XXX TODO (WITH TEST) ref BUG litehelpers/Cordova-sqlite-storage#210:
# if !!error then error newSQLError 'database closed during open operation'
# @abortAllPendingTransactions()
if @dbname of @openDBs
@openDBs[@dbname] = DB_STATE_OPEN
if !!success then success @
txLock = txLocks[@dbname]
if !!txLock && txLock.queue.length > 0 && !txLock.inProgress
@startNextTransaction()
return
openerrorcb = =>
console.log 'OPEN database: ' + @dbname + ' FAILED, aborting any pending transactions'
# XXX TODO: newSQLError missing the message part!
if !!error then error newSQLError 'Could not open database'
delete @openDBs[@dbname]
delete @dbidmap[@dbname]
delete @fjmap[@dbname]
@abortAllPendingTransactions()
return
# store initial DB state:
@openDBs[@dbname] = DB_STATE_INIT
@dbidmap[@dbname] = @dbid = null
@fjmap[@dbname] = false
# UPDATED WORKAROUND SOLUTION to cordova-sqlite-storage BUG 666:
# Request to native side to close existing database
# connection in case it is already open.
# Wait for callback before opening the database
# (ignore close error).
step2 = =>
cordova.exec opensuccesscb, openerrorcb, "SQLitePlugin", "open", [ @openargs ]
return
cordova.exec step2, step2, 'SQLitePlugin', 'close', [ { path: @dbname } ]
return
SQLitePlugin::close = (success, error) ->
if @dbname of @openDBs
if txLocks[@dbname] && txLocks[@dbname].inProgress
# FUTURE TBD TODO ref BUG litehelpers/Cordova-sqlite-storage#210:
# Wait for current tx to finish then close,
# then abort any other pending transactions
# (and cleanup any other internal resources).
# (This would need testing!!)
console.log 'cannot close: transaction is in progress'
error newSQLError 'database cannot be closed while a transaction is in progress'
return
console.log 'CLOSE database: ' + @dbname
# NOTE: closing one db handle disables other handles to same db
# FUTURE TBD TODO ref litehelpers/Cordova-sqlite-storage#210:
# Add a dispose method to simply invalidate the
# current database object ("this")
delete @openDBs[@dbname]
if txLocks[@dbname] then console.log 'closing db with transaction queue length: ' + txLocks[@dbname].queue.length
else console.log 'closing db with no transaction lock state'
# XXX TODO BUG litehelpers/Cordova-sqlite-storage#210:
# abort all pending transactions (with error callback)
# when closing a database (needs testing!!)
# (and cleanup any other internal resources)
cordova.exec success, error, "SQLitePlugin", "close", [ { path: @dbname } ]
else
console.log 'cannot close: database is not open'
if error then nextTick -> error()
return
SQLitePlugin::executeSql = (statement, params, success, error) ->
# XXX TODO: better to capture the result, and report it once
# the transaction has completely finished.
# This would fix BUG #204 (cannot close db in db.executeSql() callback).
mysuccess = (t, r) -> if !!success then success r
myerror = (t, e) -> if !!error then error e
myfn = (tx) ->
tx.addStatement(statement, params, mysuccess, myerror)
return
@addTransaction new SQLitePluginTransaction(this, myfn, null, null, false, false)
return
SQLitePlugin::sqlBatch = (sqlStatements, success, error) ->
if !sqlStatements || sqlStatements.constructor isnt Array
throw newSQLError 'sqlBatch expects an array'
ss = sqlStatements.slice(0)
f = (tx) ->
for s in ss
if s.constructor is Array
if s.length is 0
throw newSQLError 'sqlBatch array element of zero (0) length'
tx.addStatement s[0],
(if s.length is 0 then [] else s[1]), null, null
else
tx.addStatement s, [], null, null
@addTransaction new SQLitePluginTransaction(this, f, error, success, true, false)
return
## SQLite plugin transaction object for batching:
SQLitePluginTransaction = (db, fn, error, success, txlock, readOnly) ->
# FUTURE TBD check this earlier:
if typeof(fn) != "function"
###
This is consistent with the implementation in Chrome -- it
throws if you pass anything other than a function. This also
prevents us from stalling our txQueue if somebody passes a
false value for fn.
###
throw newSQLError "transaction expected a function"
@db = db
@fn = fn
@error = error
@success = success
@txlock = txlock
@readOnly = readOnly
@executesLength = 0
@flatExecutesList = []
@executeCallbacks = []
if txlock
@addStatement "BEGIN", [], null, (tx, err) ->
throw newSQLError "unable to begin transaction: " + err.message, err.code
# Workaround for litehelpers/Cordova-sqlite-storage#409
# extra statement in case user function does not add any SQL statements
# TBD This also adds an extra statement to db.executeSql()
else
@addStatement "SELECT 1", [], null, null
return
SQLitePluginTransaction::start = ->
try
@fn this
@run()
catch err
# If "fn" throws, we must report the whole transaction as failed.
txLocks[@db.dbname].inProgress = false
@db.startNextTransaction()
if @error
@error newSQLError err
return
SQLitePluginTransaction::executeSql = (sql, values, success, error) ->
if @finalized
throw {message: 'InvalidStateError: DOM Exception 11: This transaction is already finalized. Transactions are committed after its success or failure handlers are called. If you are using a Promise to handle callbacks, be aware that implementations following the A+ standard adhere to run-to-completion semantics and so Promise resolution occurs on a subsequent tick and therefore after the transaction commits.', code: 11}
return
if @readOnly && READ_ONLY_REGEX.test(sql)
@handleStatementFailure(error, {message: 'invalid sql for a read-only transaction'})
return
@addStatement(sql, values, success, error)
return
# This method adds the SQL statement to the transaction queue but does not check for
# finalization since it is used to execute COMMIT and ROLLBACK.
SQLitePluginTransaction::addStatement = (sql, values, success, error) ->
sqlStatement = if typeof sql is 'string'
sql
else
sql.toString()
@executesLength++
flatlist = @flatExecutesList
flatlist.push sqlStatement
if !!values && values.constructor == Array
flatlist.push values.length
for v in values
t = typeof v
flatlist.push(
if v == null || v == undefined then null
else if t == 'number' || t == 'string' then v
else v.toString()
)
else
flatlist.push 0
@executeCallbacks.push
success: success
error: error
return
SQLitePluginTransaction::handleStatementSuccess = (handler, response) ->
if !handler
return
rows = response.rows || []
payload =
rows:
item: (i) ->
rows[i]
length: rows.length
rowsAffected: response.rowsAffected or 0
insertId: response.insertId or undefined
handler this, payload
return
SQLitePluginTransaction::handleStatementFailure = (handler, response) ->
if !handler
throw newSQLError "a statement with no error handler failed: " + response.message, response.code
if handler(this, response) isnt false
throw newSQLError "a statement error callback did not return false: " + response.message, response.code
return
SQLitePluginTransaction::run = ->
# persist for handlerFor callbacks:
txFailure = null
# sql statements from queue:
batchExecutesLength = @executesLength
flatBatchExecutes = @flatExecutesList
batchExecuteCallbacks = @executeCallbacks
# XXX NOTE: If this length is zero it will not work.
# Workaround is applied in the constructor.
# FUTURE TBD: It would be better to fix the problem here.
waiting = batchExecutesLength
@executesLength = 0
@flatExecutesList = []
@executeCallbacks = []
# my tx object (this)
tx = @
# FUTURE TBD factor this out in favor of a more elegant solution?
handlerFor = (index, didSucceed) ->
(response) ->
if !txFailure
try
if didSucceed
tx.handleStatementSuccess batchExecuteCallbacks[index].success, response
else
tx.handleStatementFailure batchExecuteCallbacks[index].error, newSQLError(response)
catch err
# NOTE: txFailure is expected to be null at this point.
txFailure = newSQLError(err)
if --waiting == 0
if txFailure
tx.executesLength = 0
tx.flatExecutesList = []
tx.executeCallbacks = []
tx.$abort txFailure
else if tx.executesLength > 0
# new requests have been issued by the callback
# handlers, so run another batch.
tx.run()
else
tx.$finish()
return
if @db.fjmap[@db.dbname]
@run_batch_flatjson batchExecutesLength, flatBatchExecutes, handlerFor
else
@run_batch1 batchExecutesLength, flatBatchExecutes, handlerFor
return
# version with flat JSON interface
SQLitePluginTransaction::run_batch_flatjson = (batchExecutesLength, flatBatchExecutes, handlerFor) ->
# XXX TBD evidently not always set in SQLitePlugin::open
# FUTURE TBD more elegant solution that may possibly be more efficient
@db.dbid = @db.dbidmap[@db.dbname]
flatlist = [@db.dbid, batchExecutesLength]
# Use Array.prototype.concat since Array.prototype.push should not be applied on
# applied on large number of elements ref:
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push#Merging_two_arrays
flatlist = flatlist.concat(flatBatchExecutes)
flatlist.push 'extra'
check1 = false
rrr = []
mycb = (result) ->
i = 0
ri = 0
rl = result.length
if rl > 0 and result[0] is 'batcherror'
while i < batchExecutesLength
# XXX TODO use correct error code values
handlerFor(i, false)
result:
code: -1
sqliteCode: -1
message: 'internal batch error'
++i
return
while ri < rl
r = result[ri++]
if r == 'ok'
handlerFor(i, true)({ rows: [] })
else if r is "ch2"
changes = result[ri++]
insert_id = result[ri++]
handlerFor(i, true)({
rowsAffected: changes
insertId: insert_id
})
else if r == 'okrows'
rows = []
changes = 0
insert_id = undefined
if result[ri] == 'changes'
++ri
changes = result[ri++]
if result[ri] == 'insert_id'
++ri
insert_id = result[ri++]
while result[ri] != 'endrows'
c = result[ri++]
j = 0
row = {}
while j < c
k = result[ri++]
v = result[ri++]
row[k] = v
++j
rows.push row
handlerFor(i, true)({
rows: rows
rowsAffected: changes
insertId: insert_id
})
++ri
else if r == 'error'
code = result[ri++]
++ri # [ignored]
errormessage = result[ri++]
handlerFor(i, false)({
code: code
message: errormessage
})
++i
return
mycb2 = (result) ->
if result.length is 0
# TBD just in case:
return mycb(rrr)
else if result[0] is "multi"
check1 = true
else if result[0] is null
if check1
return mycb(rrr)
else
if check1
# TBD ISSUE with result.slice(-1) on Android 4.4
# rrr = rrr.concat(result.slice(-1))
rrr = rrr.concat(result.slice(0, result.length-1))
else
return mycb(result)
# NOTE: flatlist.length is needed internally for the JSON decoding.
if @db.dbid isnt -1
cordova.exec mycb2, null, "SQLitePlugin", "fj:#{flatlist.length};extra", flatlist
else
cordova.exec mycb, null, "SQLitePlugin", "fj",
[{dbargs: {dbname: @db.dbname}, flen: batchExecutesLength, flatlist: flatlist}]
return
# version for platforms with no flat JSON interface:
SQLitePluginTransaction::run_batch1 = (batchExecutesLength, flatBatchExecutes, handlerFor) ->
tropts = []
mycbmap = {}
fi = 0
i = 0
while i < batchExecutesLength
sql = flatBatchExecutes[fi++]
paramsCount = flatBatchExecutes[fi++]
fi2 = fi+paramsCount
params = flatBatchExecutes.slice(fi, fi2)
fi = fi2
mycbmap[i] =
success: handlerFor(i, true)
error: handlerFor(i, false)
tropts.push
sql: sql
params: params
i++
mycb = (result) ->
#console.log "mycb result #{JSON.stringify result}"
for resultIndex in [0 .. result.length-1]
r = result[resultIndex]
type = r.type
res = r.result
q = mycbmap[resultIndex]
if q
if q[type]
q[type] res
++i
return
cordova.exec mycb, null, "SQLitePlugin", "backgroundExecuteSqlBatch", [{dbargs: {dbname: @db.dbname}, executes: tropts}]
return
SQLitePluginTransaction::$abort = (txFailure) ->
if @finalized then return
tx = @
succeeded = (tx) ->
txLocks[tx.db.dbname].inProgress = false
tx.db.startNextTransaction()
if tx.error and typeof tx.error is 'function'
tx.error txFailure
return
failed = (tx, err) ->
txLocks[tx.db.dbname].inProgress = false
tx.db.startNextTransaction()
if tx.error and typeof tx.error is 'function'
tx.error newSQLError 'error while trying to roll back: ' + err.message, err.code
return
@finalized = true
if @txlock
@addStatement "ROLLBACK", [], succeeded, failed
@run()
else
succeeded(tx)
return
SQLitePluginTransaction::$finish = ->
if @finalized then return
tx = @
succeeded = (tx) ->
txLocks[tx.db.dbname].inProgress = false
tx.db.startNextTransaction()
if tx.success and typeof tx.success is 'function'
tx.success()
return
failed = (tx, err) ->
txLocks[tx.db.dbname].inProgress = false
tx.db.startNextTransaction()
if tx.error and typeof tx.error is 'function'
tx.error newSQLError 'error while trying to commit: ' + err.message, err.code
return
@finalized = true
if @txlock
@addStatement "COMMIT", [], succeeded, failed
@run()
else
succeeded(tx)
return
SQLitePluginTransaction::abortFromQ = (sqlerror) ->
# NOTE: since the transaction is waiting in the queue,
# the transaction function containing the SQL statements
# would not be run yet. Simply report the transaction error.
if @error
@error sqlerror
return
## SQLite plugin object factory:
# OLD:
dblocations = [ "docs", "libs", "nosync" ]
iosLocationMap =
'default' : 'nosync'
'Documents' : 'docs'
'Library' : 'libs'
SQLiteFactory =
###
NOTE: this function should NOT be translated from Javascript
back to CoffeeScript by js2coffee.
If this function is edited in Javascript then someone will
have to translate it back to CoffeeScript by hand.
###
openDatabase: argsArray (args) ->
if args.length < 1 || !args[0]
throw newSQLError 'Sorry missing mandatory open arguments object in openDatabase call'
#first = args[0]
#openargs = null
#okcb = null
#errorcb = null
#if first.constructor == String
# openargs = {name: first}
# if args.length >= 5
# okcb = args[4]
# if args.length > 5 then errorcb = args[5]
#else
# openargs = first
# if args.length >= 2
# okcb = args[1]
# if args.length > 2 then errorcb = args[2]
if args[0].constructor == String
throw newSQLError 'Sorry first openDatabase argument must be an object'
openargs = args[0]
# check here
if !openargs.name
throw newSQLError 'Database name value is missing in openDatabase call'
if !openargs.iosDatabaseLocation and !openargs.location and openargs.location isnt 0
throw newSQLError 'Database location or iosDatabaseLocation setting is now mandatory in openDatabase call.'
if !!openargs.location and !!openargs.iosDatabaseLocation
throw newSQLError 'AMBIGUOUS: both location and iosDatabaseLocation settings are present in openDatabase call. Please use either setting, not both.'
dblocation =
if !!openargs.location and openargs.location is 'default'
iosLocationMap['default']
else if !!openargs.iosDatabaseLocation
iosLocationMap[openargs.iosDatabaseLocation]
else
dblocations[openargs.location]
if !dblocation
throw newSQLError 'Valid iOS database location could not be determined in openDatabase call'
openargs.dblocation = dblocation
if !!openargs.createFromLocation and openargs.createFromLocation == 1
openargs.createFromResource = "1"
if !!openargs.androidDatabaseProvider and !!openargs.androidDatabaseImplementation
throw newSQLError 'AMBIGUOUS: both androidDatabaseProvider and deprecated androidDatabaseImplementation settings are present in openDatabase call. Please drop androidDatabaseImplementation in favor of androidDatabaseProvider.'
if openargs.androidDatabaseProvider isnt undefined and
openargs.androidDatabaseProvider isnt 'default' and
openargs.androidDatabaseProvider isnt 'system'
throw newSQLError "Incorrect androidDatabaseProvider value. Valid values are: 'default', 'system'"
if !!openargs.androidDatabaseProvider and openargs.androidDatabaseProvider is 'system'
openargs.androidOldDatabaseImplementation = 1
# DEPRECATED:
if !!openargs.androidDatabaseImplementation and openargs.androidDatabaseImplementation == 2
openargs.androidOldDatabaseImplementation = 1
if !!openargs.androidLockWorkaround and openargs.androidLockWorkaround == 1
openargs.androidBugWorkaround = 1
okcb = null
errorcb = null
if args.length >= 2
okcb = args[1]
if args.length > 2 then errorcb = args[2]
new SQLitePlugin openargs, okcb, errorcb
deleteDatabase: (first, success, error) ->
# XXX TODO BUG litehelpers/Cordova-sqlite-storage#367:
# abort all pending transactions (with error callback)
# when deleting a database
# (and cleanup any other internal resources)
# NOTE: This should properly close the database
# (at least on the JavaScript side) before deleting.
args = {}
if first.constructor == String
#console.log "delete db name: #{first}"
#args.path = first
#args.dblocation = dblocations[0]
#args.dblocation = dblocations[2]
throw newSQLError 'Sorry first deleteDatabase argument must be an object'
else
#console.log "delete db args: #{JSON.stringify first}"
if !(first and first['name']) then throw new Error "Please specify db name"
dbname = first.name
if typeof dbname != 'string'
throw newSQLError 'delete database name must be a string'
args.path = dbname
#dblocation = if !!first.location then dblocations[first.location] else null
#args.dblocation = dblocation || dblocations[0]
#args.dblocation = dblocation || dblocations[2]
if !first.iosDatabaseLocation and !first.location and first.location isnt 0
throw newSQLError 'Database location or iosDatabaseLocation setting is now mandatory in deleteDatabase call.'
if !!first.location and !!first.iosDatabaseLocation
throw newSQLError 'AMBIGUOUS: both location and iosDatabaseLocation settings are present in deleteDatabase call. Please use either setting value, not both.'
dblocation =
if !!first.location and first.location is 'default'
iosLocationMap['default']
else if !!first.iosDatabaseLocation
iosLocationMap[first.iosDatabaseLocation]
else
dblocations[first.location]
if !dblocation
throw newSQLError 'Valid iOS database location could not be determined in deleteDatabase call'
args.dblocation = dblocation
# XXX TODO BUG litehelpers/Cordova-sqlite-storage#367 (repeated here):
# abort all pending transactions (with error callback)
# when deleting a database
# (and cleanup any other internal resources)
delete SQLitePlugin::openDBs[args.path]
delete SQLitePlugin::dbidmap[args.path]
delete SQLitePlugin::fjmap[args.path]
cordova.exec success, error, "SQLitePlugin", "delete", [ args ]
## Self test:
SelfTest =
DBNAME: '___$$$___litehelpers___$$$___test___$$$___.db'
start: (successcb, errorcb) ->
SQLiteFactory.deleteDatabase {name: SelfTest.DBNAME, location: 'default'},
(-> SelfTest.step1(successcb, errorcb)),
(-> SelfTest.step1(successcb, errorcb))
return
step1: (successcb, errorcb) ->
SQLiteFactory.openDatabase {name: SelfTest.DBNAME, location: 'default'}, (db) ->
check1 = false
db.transaction (tx) ->
tx.executeSql 'SELECT UPPER("Test") AS upperText', [], (ignored, resutSet) ->
if !resutSet.rows
return SelfTest.finishWithError errorcb, 'Missing resutSet.rows'
if !resutSet.rows.length
return SelfTest.finishWithError errorcb, 'Missing resutSet.rows.length'
if resutSet.rows.length isnt 1
return SelfTest.finishWithError errorcb,
"Incorrect resutSet.rows.length value: #{resutSet.rows.length} (expected: 1)"
if !resutSet.rows.item(0).upperText
return SelfTest.finishWithError errorcb,
'Missing resutSet.rows.item(0).upperText'
if resutSet.rows.item(0).upperText isnt 'TEST'
return SelfTest.finishWithError errorcb,
"Incorrect resutSet.rows.item(0).upperText value: #{resutSet.rows.item(0).upperText} (expected: 'TEST')"
check1 = true
return
, (ignored, tx_sql_err) ->
return SelfTest.finishWithError errorcb, "TX SQL error: #{tx_sql_err}"
return
, (tx_err) ->
return SelfTest.finishWithError errorcb, "TRANSACTION error: #{tx_err}"
, () ->
# tx success:
if !check1
return SelfTest.finishWithError errorcb,
'Did not get expected upperText result data'
# SIMULATE SCENARIO IN BUG litehelpers/Cordova-sqlite-storage#666:
db.executeSql 'BEGIN', null, (ignored) -> nextTick -> # (nextTick needed for Windows)
# DELETE INTERNAL STATE to simulate the effects of location refresh or change:
delete db.openDBs[SelfTest.DBNAME]
delete txLocks[SelfTest.DBNAME]
nextTick ->
# VERIFY INTERNAL STATE IS DELETED:
db.transaction (tx2) ->
tx2.executeSql 'SELECT 1'
return
, (tx_err) ->
# EXPECTED RESULT:
if !tx_err
return SelfTest.finishWithError errorcb, 'Missing error object'
SelfTest.step2 successcb, errorcb
return
, () ->
# NOT EXPECTED:
return SelfTest.finishWithError errorcb, 'Missing error object'
return
return
return