forked from sql-js/sql.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.coffee
51 lines (48 loc) · 2.15 KB
/
worker.coffee
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
# Since this is only included in web worker builds, I'm not sure if we need to detect this.
# In fact, it seems like we might want to throw an error if importScripts isn't available.
if typeof importScripts is 'function' # Detect webworker context
db = null
createDb = (data) ->
if db? then db.close()
db = new SQL.Database data
sqlModuleReady = initSqlJs();
self.onmessage = (event) ->
sqlModuleReady.then ->
data = event['data']
switch data?['action']
when 'open'
buff = data['buffer']
createDb (if buff then new Uint8Array(buff) else undefined)
postMessage
'id': data['id']
'ready': true
when 'exec'
if db is null then createDb()
if not data['sql'] then throw 'exec: Missing query string'
postMessage
'id' : data['id']
'results': db.exec data['sql']
when 'each'
if db is null then createDb()
callback = (row) -> postMessage
'id': data['id']
'row': row
'finished': false
done = -> postMessage
'id' : data['id']
'finished': true
db.each data['sql'], data['params'], callback, done
when 'export'
buff = db.export()
result = {
'id' : data['id']
'buffer' : buff
}
try
postMessage result, [result]
catch err # Some browsers fail when trying to use transferable objects
postMessage result
when 'close'
db?.close()
else
throw new 'Invalid action : ' + data?['action']