SQLite 编译为 JavaScript
sql.js (英语) 是一个 Javascript SQL 数据库。 它允许您创建关系数据库,并完全在浏览器中查询. 你可以试试看 此在线演示它使用 存储在内存中的虚拟数据库文件,因此 不坚持的改变 输入数据库 然而,它允许你 导入 任何已存在的 sqlite 文件,并改为 导出 作为创建的数据库 JavaScript 键入数组。 。 。 .
sql.js (英语) 用途 标记 要编译 SQL 点 至web组装(或与旧浏览器兼容的javascript代码)。 它包括 贡献的数学和字符串扩展函数。 。 。 .
sql.js可以像任何传统的JavaScript库一样被使用. 如果您正在 JavaScript( 例如使用 Electron) 构建本地应用程序, 或者在节点工作, 您可能更喜欢使用 本地绑定 SQLite 到 JavaScript. 原生装订不仅会因为会运行原生代码而更快,而且还能直接在数据库文件上工作,而不必将整个数据库装入内存,避免内存出错并进一步改善性能.
SQLite为公有领域, sql.js为麻省理工学院许可.
API 文档
A 类 aPI 完整文档 所有现有课程和方法都有. 是源代码内部的评论产生的,因此总是最新的.
使用量
默认, sql.js (英语) 用途 原声,因此需要装入 .wasm 除javascript 库外还有文件。 您可以在 ./node_modules/sql.js/dist/sql-wasm.wasm 从 npm 安装 sql.js 后,并指示您的捆绑者将其添加到您的静态资产中或从中加载 a CDN (中文(简体) )。然后使用 locateFile 配置对象的属性 initSqlJs 以显示文件的位置。 如果您使用 Webpack 等资产构建器,您可以自动化此功能. 见 此演示如何将 sql。 。 。 .
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'
// Export the database to an Uint8Array containing the SQLite database file
const binaryArray = db.export();
演示
有几个例子 此处可用。最全面性是 Sqlite 口译员。 。 。 .
实例
测试文件提供了使用 api 的最新实例 .
浏览器内部
示例 HTML 语言 文件 :
<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 构造器将代表数据库文件的整数组作为可选参数.
以下代码使用 HTML 输入作为输入数据库的来源 :
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);
}
见: https://sql-js.github.io/sql.js/examples/GUI/gui.js 互联网档案馆的存檔,存档日期2013-12-12
从服务器上装入数据库
使用获取
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));
使用 XMLHttp 请求
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();
见: https://github.com/sql-js/sql.js/wiki/Load-a-database- from-the-server 互联网档案馆的存檔,存档日期2013-12-22
从节点.js 使用
sql.js 实值 npm 时主机。要安装它,你可以简单地运行 npm install sql.js。 。 。 .
或者,你可以简单地下载 sql-wasm.js 财务报告和审定财务报表 sql-wasm.wasm,从下面的下载链接.
从磁盘上读取数据库 :
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);
});
将数据库写入磁盘
您需要转换结果 db.export 到缓冲器
const fs = require("fs");
// [...] (create the database)
const data = db.export();
const buffer = new Buffer(data);
fs.writeFileSync("filename.sqlite", buffer);
见: https://github.com/sql-js/sql.js/blob/master/test/test node file.js (中文(简体) )
用作网络工人
如果您不想在主应用程序线索中运行 CPU 密集 SQL 查询, 您可以使用 比较有限 网工API.
您需要下载 worker.sql-wasm.js 财务报告和审定财务报表 worker.sql-wasm.wasm 从 页面。 。 。 .
示例
<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>
启用 BigInt 支持
如果你需要的话 BigInt 支持,它得到部分支持,因为大多数浏览器现在都支持它包括了Safari. 装订 BigInt 仍然不支持,仅获取 BigInt 从数据库中获取支持.
<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 result = db.exec("SELECT * FROM test", config);
console.log(results[0].values)
</script>
在WebWorker上,你可以只添加 config 发布消息前的参数 。 有了这个,你不必通过配置参数 get 函数.
<script>
worker.postMessage({
id:1,
action:"exec",
sql: "SELECT * FROM test",
config: {useBigInt: true}, /*Optional param*/
});
</script>
见 实例/GUI/gui.js 对于一个完整的例子.
目标/下载数
这个图书馆包括了Sqlite的WebAssembly和asm.js版本. (WebAssembly是更新的,首选的编译方式为JavaScript,并已经超越了asm.js. 它产生较小,更快的代码. ) 包含Asm.js版本的相容性.
从0.x升级到1.x
Sql.js的1.0版本必须同步装入,而asm.js则能够同步装入.
所以在过去 你会:
<script src='js/sql.js'></script>
<script>
const db = new SQL.Database();
//...
</script>
或:
const SQL = require('sql.js');
const db = new SQL.Database();
//...
1.x版本:
<script src='dist/sql-wasm.js'></script>
<script>
initSqlJs({ locateFile: filename => `/dist/${filename}` }).then(function(SQL){
const db = new SQL.Database();
//...
});
</script>
或:
const initSqlJs = require('sql-wasm.js');
initSqlJs().then(function(SQL){
const db = new SQL.Database();
//...
});
NOTHING 现在在SQLite中是一个保留词,而以前它不是。 这可能造成错误,如 Error: near "nothing": syntax error
下载/使用:
虽然asm.js文件作为单一Javascript文件分发,但WebAssembly作为一对文件分发效率最高 .js 加载器和 .wasm 文档,比如 sql-wasm.js 财务报告和审定财务报表 sql-wasm.wasm编辑 .js 文件负责装入 .wasm 文档。 你可以从我们身上找到这些文件 页面
分布式文物中的 sql.js版本
你总能找到最新出版的文物 https://github.com/sql-js/sql.js/releases/latest (中文(简体) )。 。 。 .
每笔 释放,你会找到一个名为 sqljs.zip 输入 释放资产它将包括:
sql-wasm.js: Sql.js的Web大会版. 已消化并适合生产。 用这个 如果您使用此选项, 您需要包含/ shipsql-wasm.wasm还有.sql-wasm-debug.js: Web Assembly, Sql.js 调试版本. 更大的, 与断言打开。 有利于地方发展. 您需要包含/舰艇sql-wasm-debug.wasm如果你用这个.sql-asm.js: Sql.js更古老的Asm.js版本. 较慢而更大. 出于兼容性原因提供.sql-asm-memory-growth.js: Asm.js不允许内存在默认情况下增长,因为其速度较慢并非优化. 如果您正在使用 sql-asm.js 并看到这个错误(Cannot enlarge memory arrays,使用此文件.sql-asm-debug.js编号: 调试 asm.js版本的Sql.j. 利用这个进行地方发展.worker.*- 上述图书馆的网络工作者版本。 比较有限度的API. 见 实例/GUI/gui.js 对于一个很好的例子.
汇编/撰稿
这个图书馆的一般消费者不需要再读了. (汇编的文件可通过 页面. ) (中文(简体) )
如果您想为 Web Assembly 编译自己的 SQLite 版本, 或者想要为此工程贡献, 请参见 捐款额。 。 。 .