Skip to content

Commit bef7e0e

Browse files
feat: define db size
1 parent a161ff4 commit bef7e0e

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/api.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,30 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
735735
this.activeStatement = null;
736736
}
737737

738+
function expandFileStorage(node, newCapacity) {
739+
var prevCapacity = node.contents ? node.contents.length : 0;
740+
// No need to expand, the storage was already large enough.
741+
// Don't expand strictly to the given requested limit if it's
742+
// only a very small increase, but instead geometrically grow capacity.
743+
if (prevCapacity >= newCapacity) return;
744+
// For small filesizes (<1MB), perform size*2 geometric increase, but
745+
// for large sizes, do a much more conservative size*1.125 increase to
746+
// avoid overshooting the allocation cap by a very large margin.
747+
var CAPACITY_DOUBLING_MAX = 1024 * 1024;
748+
var capacityCoef = prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125;
749+
var newAutoCapacity = prevCapacity * capacityCoef;
750+
newCapacity = Math.max(newCapacity, newAutoCapacity | 0);
751+
// At minimum allocate 256b for each file when expanding.
752+
if (prevCapacity !== 0) newCapacity = Math.max(newCapacity, 256);
753+
var oldContents = node.contents;
754+
node.contents = new Uint8Array(newCapacity); // Allocate new storage.
755+
756+
if (node.usedBytes > 0) {
757+
// Copy old data over to the new storage.
758+
node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
759+
}
760+
}
761+
738762
/**
739763
* @typedef {{ done:true, value:undefined } |
740764
* { done:false, value:Statement}}
@@ -822,14 +846,22 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
822846
* @param {number[]} data An array of bytes representing
823847
* an SQLite database file
824848
*/
825-
function Database(data) {
849+
function Database(data, initialDbSize) {
826850
this.filename = "dbfile_" + (0xffffffff * Math.random() >>> 0);
827851
if (data != null) {
828852
FS.createDataFile("/", this.filename, data, true, true);
829853
}
830854
this.handleError(sqlite3_open(this.filename, apiTemp));
831855
this.db = getValue(apiTemp, "i32");
832856
registerExtensionFunctions(this.db);
857+
858+
if (initialDbSize) {
859+
this.run("VACUUM");
860+
var parentNode = FS.lookupPath("/").node;
861+
var dbNode = FS.lookupNode(parentNode, this.filename);
862+
expandFileStorage(dbNode, initialDbSize);
863+
}
864+
833865
// A list of all prepared statements of the database
834866
this.statements = {};
835867
// A list of all user function of the database

0 commit comments

Comments
 (0)