sql.js is a javascript SQL database. It allows you to create a relational database and query it entirely in the browser. You can try it in this online demo. It uses a virtual database file stored in memory, and thus doesn't persist the changes made to the database. However, it allows you to import any existing sqlite file, and to export the created database as a JavaScript typed array.
sql.js uses emscripten to compile SQLite to webassembly (or to javascript code for compatibility with older browsers). It includes contributed math and string extension functions.
sql.js can be used like any traditional JavaScript library. If you are building a native application in JavaScript (using Electron for instance), or are working in node.js, you will likely prefer to use a native binding of SQLite to JavaScript. A native binding will not only be faster because it will run native code, but it will also be able to work on database files directly instead of having to load the entire database in memory, avoiding out of memory errors and further improving performances.
SQLite is public domain, sql.js is MIT licensed.
A full API documentation for all the available classes and methods is available. It is generated from comments inside the source code, and is thus always up to date.
By default, sql.js uses wasm, and thus needs to load a .wasm
file in addition to the javascript library. You can find this file in ./node_modules/sql.js/dist/sql-wasm.wasm
after installing sql.js from npm, and instruct your bundler to add it to your static assets or load it from a CDN. Then use the locateFile
property of the configuration object passed to initSqlJs
to indicate where the file is. If you use an asset builder such as webpack, you can automate this. See this demo of how to integrate sql.js with webpack (and react).
const initSqlJs = require('sql.js'); // or if you are in a browser: // const initSqlJs = window.initSqlJs; const SQL = await initSqlJs({ // Required to load the wasm binary asynchronously. Of course, you can host it wherever you want // You can omit locateFile completely when running in node locateFile: file => `https://sql.js.org/dist/${file}` }); // Create a database const db = new SQL.Database(); // NOTE: You can also use new SQL.Database(data) where // data is an Uint8Array representing an SQLite database file // Execute a single SQL string that contains multiple statements let sqlstr = "CREATE TABLE hello (a int, b char); \ INSERT INTO hello VALUES (0, 'hello'); \ INSERT INTO hello VALUES (1, 'world');"; db.run(sqlstr); // Run the query without returning anything // Prepare an sql statement const stmt = db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval"); // Bind values to the parameters and fetch the results of the query const result = stmt.getAsObject({':aval' : 1, ':bval' : 'world'}); console.log(result); // Will print {a:1, b:'world'} // Bind other values stmt.bind([0, 'hello']); while (stmt.step()) console.log(stmt.get()); // Will print [0, 'hello'] // free the memory used by the statement stmt.free(); // You can not use your statement anymore once it has been freed. // But not freeing your statements causes memory leaks. You don't want that. const res = db.exec("SELECT * FROM hello"); /* [ {columns:['a','b'], values:[[0,'hello'],[1,'world']]} ] */ // You can also use JavaScript functions inside your SQL code // Create the js function you need function add(a, b) {return a+b;} // Specifies the SQL function's name, the number of it's arguments, and the js function to use db.create_function("add_js", add); // Run a query in which the function is used db.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));"); // Inserts 10 and 'Hello world' // You can create custom aggregation functions, by passing a name // and a set of functions to `db.create_aggregate`: // // - an `init` function. This function receives no argument and returns // the initial value for the state of the aggregate function. // - a `step` function. This function takes two arguments // - the current state of the aggregation // - a new value to aggregate to the state // It should return a new value for the state. // - a `finalize` function. This function receives a state object, and // returns the final value of the aggregate. It can be omitted, in which case // the final value of the state will be returned directly by the aggregate function. // // Here is an example aggregation function, `json_agg`, which will collect all // input values and return them as a JSON array: db.create_aggregate( "json_agg", { init: () => [], step: (state, val) => [...state, val], finalize: (state) => JSON.stringify(state), } ); db.exec("SELECT json_agg(column1) FROM (VALUES ('hello'), ('world'))"); // -> The result of the query is the string '["hello","world"]' // Export the database to an Uint8Array containing the SQLite database file const binaryArray = db.export();
There are a few examples available here. The most full-featured is the Sqlite Interpreter.
The test files provide up to date example of the use of the api.
<meta charset="utf8" /> <html> <script src='/dist/sql-wasm.js'></script> <script> config = { locateFile: filename => `/dist/${filename}` } // The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser. // We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder. initSqlJs(config).then(function(SQL){ //Create the database const db = new SQL.Database(); // Run a query without reading the results db.run("CREATE TABLE test (col1, col2);"); // Insert two rows: (1,111) and (2,222) db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]); // Prepare a statement const stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end"); stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111} // Bind new values stmt.bind({$start:1, $end:2}); while(stmt.step()) { // const row = stmt.getAsObject(); console.log('Here is a row: ' + JSON.stringify(row)); } }); </script> <body> Output is in Javascript console </body> </html>
SQL.Database
constructor takes an array of integer representing a database file as an optional parameter.
The following code uses an HTML input as the source for loading a database:
dbFileElm.onchange = () => { const f = dbFileElm.files[0]; const r = new FileReader(); r.onload = function() { const Uints = new Uint8Array(r.result); db = new SQL.Database(Uints); } r.readAsArrayBuffer(f); }
See : https://sql-js.github.io/sql.js/examples/GUI/gui.js
const sqlPromise = initSqlJs({ locateFile: file => `https://path/to/your/dist/folder/dist/${file}` }); const dataPromise = fetch("/path/to/database.sqlite").then(res => res.arrayBuffer()); const [SQL, buf] = await Promise.all([sqlPromise, dataPromise]) const db = new SQL.Database(new Uint8Array(buf));
const xhr = new XMLHttpRequest(); // For example: https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite xhr.open('GET', '/path/to/database.sqlite', true); xhr.responseType = 'arraybuffer'; xhr.onload = e => { const uInt8Array = new Uint8Array(xhr.response); const db = new SQL.Database(uInt8Array); const contents = db.exec("SELECT * FROM my_table"); // contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}] }; xhr.send();
See: https://github.com/sql-js/sql.js/wiki/Load-a-database-from-the-server
sql.js
is hosted on npm. To install it, you can simply run npm install sql.js
.
Alternatively, you can simply download sql-wasm.js
and sql-wasm.wasm
, from the download link below.
const fs = require('fs'); const initSqlJs = require('sql-wasm.js'); const filebuffer = fs.readFileSync('test.sqlite'); initSqlJs().then(function(SQL){ // Load the db const db = new SQL.Database(filebuffer); });
You need to convert the result of db.export
to a buffer
const fs = require("fs"); // [...] (create the database) const data = db.export(); const buffer = Buffer.from(data); fs.writeFileSync("filename.sqlite", buffer);
See : https://github.com/sql-js/sql.js/blob/master/test/test_node_file.js
If you don't want to run CPU-intensive SQL queries in your main application thread, you can use the more limited WebWorker API.
You will need to download worker.sql-wasm.js
and worker.sql-wasm.wasm
from the release page.
Example:
<script> const worker = new Worker("/dist/worker.sql-wasm.js"); worker.onmessage = () => { console.log("Database opened"); worker.onmessage = event => { console.log(event.data); // The result of the query }; worker.postMessage({ id: 2, action: "exec", sql: "SELECT age,name FROM test WHERE id=$id", params: { "$id": 1 } }); }; worker.onerror = e => console.log("Worker error: ", e); worker.postMessage({ id:1, action:"open", buffer:buf, /*Optional. An ArrayBuffer representing an SQLite Database file*/ }); </script>
If you need BigInt
support, it is partially supported since most browsers now supports it including Safari.Binding BigInt
is still not supported, only getting BigInt
from the database is supported for now.
<script> const stmt = db.prepare("SELECT * FROM test"); const config = {useBigInt: true}; /*Pass optional config param to the get function*/ while (stmt.step()) console.log(stmt.get(null, config)); /*OR*/ const results = db.exec("SELECT * FROM test", config); console.log(results[0].values) </script>
On WebWorker, you can just add config
param before posting a message. With this, you wont have to pass config param on get
function.
<script> worker.postMessage({ id:1, action:"exec", sql: "SELECT * FROM test", config: {useBigInt: true}, /*Optional param*/ }); </script>
See examples/GUI/gui.js for a full working example.
This library includes both WebAssembly and asm.js versions of Sqlite. (WebAssembly is the newer, preferred way to compile to JavaScript, and has superceded asm.js. It produces smaller, faster code.) Asm.js versions are included for compatibility.
Version 1.0 of sql.js must be loaded asynchronously, whereas asm.js was able to be loaded synchronously.
So in the past, you would:
<script src='js/sql.js'></script> <script> const db = new SQL.Database(); //... </script>
or:
const SQL = require('sql.js'); const db = new SQL.Database(); //...
Version 1.x:
<script src='dist/sql-wasm.js'></script> <script> initSqlJs({ locateFile: filename => `/dist/${filename}` }).then(function(SQL){ const db = new SQL.Database(); //... }); </script>
or:
const initSqlJs = require('sql-wasm.js'); initSqlJs().then(function(SQL){ const db = new SQL.Database(); //... });
NOTHING
is now a reserved word in SQLite, whereas previously it was not. This could cause errors like Error: near "nothing": syntax error
Although asm.js files were distributed as a single Javascript file, WebAssembly libraries are most efficiently distributed as a pair of files, the .js
loader and the .wasm
file, like sql-wasm.js
and sql-wasm.wasm
. The .js
file is responsible for loading the .wasm
file. You can find these files on our release page
You can always find the latest published artifacts on https://github.com/sql-js/sql.js/releases/latest.
For each release, you will find a file called sqljs.zip
in the release assets. It will contain:
sql-wasm.js
: The Web Assembly version of Sql.js. Minified and suitable for production. Use this. If you use this, you will need to include/ship sql-wasm.wasm
as well.sql-wasm-debug.js
: The Web Assembly, Debug version of Sql.js. Larger, with assertions turned on. Useful for local development. You will need to include/ship sql-wasm-debug.wasm
if you use this.sql-asm.js
: The older asm.js version of Sql.js. Slower and larger. Provided for compatibility reasons.sql-asm-memory-growth.js
: Asm.js doesn't allow for memory to grow by default, because it is slower and de-optimizes. If you are using sql-asm.js and you see this error (Cannot enlarge memory arrays
), use this file.sql-asm-debug.js
: The Debug asm.js version of Sql.js. Use this for local development.worker.*
- Web Worker versions of the above libraries. More limited API. See examples/GUI/gui.js for a good example of this.General consumers of this library don't need to read any further. (The compiled files are available via the release page.)
If you want to compile your own version of SQLite for WebAssembly, or want to contribute to this project, see
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号