Skip to content

Commit

Permalink
AlaSQL#2027 sqlCache retains data (and other properties), possible me…
Browse files Browse the repository at this point in the history
…mory leak AlaSQL#2027

- Remove the `data` property from the sql cache after executing the query
  • Loading branch information
paulrutter committed Jan 8, 2025
1 parent 0dd3a6f commit 8bbc1d8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/17alasql.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,23 @@ alasql.exec = function (sql, params, cb, scope) {
}
};

/**
* Clears any unneeded properties from a given AST statement closure used for caching
* @param {Object} statement the statement to cleanup
*/
function cleanupCache(statement) {
if (!statement) {
return;
}
if (!alasql.options.cache) {
return;
}
// cleanup the table data to prevent storing this information in the SQL cache
if (statement && statement.query && statement.query.data) {
statement.query.data = [];
}
}

/**
Run SQL statement on specific database
*/
Expand All @@ -259,7 +276,9 @@ alasql.dexec = function (databaseid, sql, params, cb, scope) {
let statement = db.sqlCache[hh];
// If database structure was not changed since last time return cache
if (statement && db.dbversion === statement.dbversion) {
return statement(params, cb);
var res = statement(params, cb);
cleanupCache(statement);
return res;
}
}

Expand Down Expand Up @@ -302,6 +321,7 @@ alasql.dexec = function (databaseid, sql, params, cb, scope) {
db.sqlCache[hh] = statement;
}
var res = (alasql.res = statement(params, cb, scope));
cleanupCache(statement);
return res;
}
alasql.precompile(ast.statements[0], alasql.useid, params);
Expand Down
30 changes: 30 additions & 0 deletions test/test2027.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const alasql = require('../dist/alasql.js');

if (typeof exports === 'object') {
var assert = require('assert');
}

describe('Test 2007 - SQL cache', function () {
before(function () {
alasql('create database test');
alasql('use test');
});

after(function () {
alasql('drop database test');
});

it('A) Execute query and assert cache for `data` afterwards', () => {
alasql('CREATE TABLE osoby (id INT, meno STRING)');
alasql('INSERT INTO osoby VALUES (1, "John"), (2, "Jane"), (3, "Jake")');
alasql('SELECT * FROM osoby');

assert.deepEqual(alasql.databases["test"].sqlCache["-169125189"].query.data, []);

// Execute same query from cache again, the cache is hit now
alasql('SELECT * FROM osoby');

// Cache should still be empty for "data"
assert.deepEqual(alasql.databases["test"].sqlCache["-169125189"].query.data, []);
});
});

0 comments on commit 8bbc1d8

Please sign in to comment.