Skip to content

Commit 02d0e73

Browse files
committed
Add export to Uint8array
1 parent 00c288e commit 02d0e73

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ var sql = require('./js/sql-api.js');
1515

1616
// Create a database
1717
var db = new sql.Database();
18+
// NOTE: You can also use new sql.Database(data) where
19+
// data is an Uint8Array representing an SQLite database file
1820

1921
// Execute some sql
2022
sqlstr = "CREATE TABLE hello (a int, b char);";
@@ -41,6 +43,9 @@ while (stmt.step()) console.log(stmt.get()); // Will print [0, 'hello']
4143
stmt.free();
4244
// You can not use your statement anymore once it has been freed.
4345
// But not freeing your statements causes memory leaks. You don't want that.
46+
47+
// Export the database to an Uint8Array containing the SQLite database file
48+
var binaryArray = db.export();
4449
```
4550

4651
## Differences from the original sql.js

js/api.coffee

+3
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,9 @@ class Database
9999
if pStmt is NULL then throw 'Nothing to prepare'
100100
return new Statement(pStmt)
101101

102+
# Exports the contents of the database to a binary array
103+
export: -> new Uint8Array FS.root.contents[@filename].contents
104+
102105
handleErrors = (ret, errPtrPtr) ->
103106
if not errPtrPtr
104107
return if ret is SQLite.OK then null else SQLite.errorMessages[ret]

test/test_api.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
var sql = require('../js/sql-api.js');
2+
3+
// Create a database
4+
var db = new sql.Database();
5+
6+
// Execute some sql
7+
sqlstr = "CREATE TABLE hello (a int, b char);";
8+
sqlstr += "INSERT INTO hello VALUES (0, 'hello');"
9+
sqlstr += "INSERT INTO hello VALUES (1, 'world');"
10+
db.exec(sqlstr);
11+
12+
// Prepare an sql statement
13+
var stmt = db.prepare("SELECT * FROM hello WHERE a=? AND b=?");
14+
15+
// Bind values to the parameters
16+
stmt.bind([1, 'world']);
17+
18+
// Fetch the results of the query
19+
while (stmt.step()) console.log(stmt.get()); // Will print [1, 'world']
20+
21+
22+
// Resets the statement, so it can be used again with other values
23+
stmt.reset()
24+
// Bind other values
25+
stmt.bind([0, 'hello']);
26+
while (stmt.step()) console.log(stmt.get()); // Will print [0, 'hello']
27+
28+
29+
// free the memory used by the statement
30+
stmt.free();
31+
// You can not use your statement anymore once it has been freed.
32+
// But not freeing your statements causes memory leaks. You don't want that.
33+
34+
// Export the database to an Uint8Array containing the SQLite database file
35+
var binaryArray = db.export();
36+
console.log(String.fromCharCode.apply(null,binaryArray.slice(0,6))); // The first 6 bytes form the word 'SQLite'

0 commit comments

Comments
 (0)