Html HTML5 IndexedDB、Web SQL 数据库和浏览器大战
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3971813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 IndexedDB, Web SQL Database and browser wars
提问by ivo
I'm starting the development of a web app with offline database storage requirements. Long story short, the app should be able to run on:
我正在开始开发具有离线数据库存储要求的 Web 应用程序。长话短说,该应用程序应该能够运行:
- One of the major desktop browsers, Chrome preferred
- Safari on iOS
- Android's native browser (based on V8 and WebKit)
- 主流桌面浏览器之一,首选Chrome
- iOS 上的 Safari
- Android 原生浏览器(基于 V8 和 WebKit)
So the question is which technology to choose: IndexedDB or Web SQL Database?
所以问题是选择哪种技术:IndexedDB 还是 Web SQL 数据库?
Regarding Web SQL Database, on one hand, it is ready to be used in any of the above scenarios. On the other, Mozilla has stated Firefox will never implement it, and acording to the HTML5 working draftthe specification has reached an impasse:
关于 Web SQL 数据库,一方面,它已准备好用于上述任何场景。另一方面,Mozilla 已声明 Firefox 永远不会实施它,并且根据 HTML5工作草案,该规范已陷入僵局:
This specification has reached an impasse: all interested implementors have used the same SQL backend (Sqlite), but we need multiple independent implementations to proceed along a standardisation path. Until another implementor is interested in implementing this spec, the description of the SQL dialect has been left as simply a reference to Sqlite, which isn't acceptable for a standard. Should you be an implementor interested in implementing an independent SQL backend, please contact the editor so that he can write a specification for the dialect, thus allowing this specification to move forward.
该规范已陷入僵局:所有感兴趣的实现者都使用了相同的 SQL 后端 (Sqlite),但我们需要多个独立的实现来沿着标准化路径前进。在另一个实现者对实现这个规范感兴趣之前,SQL 方言的描述只是对 Sqlite 的引用,这对于标准来说是不可接受的。如果您是对实现独立 SQL 后端感兴趣的实现者,请联系编辑,以便他为方言编写规范,从而使该规范向前发展。
IndexedDB is the alternative advocated by Mozilla, but it will only come in Firefox 4. Microsoft is interested and Chrome will support it as well. I know nothing of Apple's plans regarding IndexedDB.
IndexedDB 是 Mozilla 提倡的替代方案,但它只会出现在 Firefox 4 中。微软对此很感兴趣,Chrome 也会支持它。我对 Apple 关于 IndexedDB 的计划一无所知。
I'm personally inclined to choose Web SQL Database, but just because I'm used to SQLite, I like the power and expressiveness of SQL, and I understand the relational model. IndexedDB, for me, is an uncertainty.
我个人倾向于选择 Web SQL 数据库,但仅仅因为我习惯了 SQLite,我喜欢 SQL 的强大和表达能力,并且我了解关系模型。IndexedDB,对我来说,是一种不确定性。
That said, I'm afraid of betting on the wrong horse. Is it safe to assume support for Web SQL Database will continue to exist, even if IndexedDB becomes the standard?
也就是说,我害怕押错马。假设对 Web SQL 数据库的支持将继续存在是否安全,即使 IndexedDB 成为标准?
(A note on CouchDB: do you also see it as an alternative?)
(关于 CouchDB 的说明:您是否也将其视为替代方案?)
采纳答案by codelark
Considering only WebSQL supports all three requirements you have listed, shouldn't your choice be simple? You have no insight into the development roadmap for Safari or Android, so use what you have available.
考虑到只有 WebSQL 支持您列出的所有三个要求,您的选择不应该很简单吗?您对 Safari 或 Android 的开发路线图一无所知,因此请使用现有的资源。
回答by Will Hartung
Well, as with all things computing, the game is "abstraction".
好吧,与所有计算一样,游戏是“抽象的”。
If you can come up with an adequate layer that works on both a SQL store and a key/value store, then, ideally you're isolated from the problem and can support the appropriate implementation on the particular browser. If your data model and access patterns don't fit with the lowest common denominator (i.e. a k/v store), then that pretty much solves your problem right there.
如果您可以提出一个适用于 SQL 存储和键/值存储的适当层,那么理想情况下,您可以与问题隔离,并且可以支持特定浏览器上的适当实现。如果您的数据模型和访问模式不符合最低公分母(即 ak/v 存储),那么这几乎可以解决您的问题。
If you can use either store, then work on a decent access layer and approach the problem from that direction.
如果您可以使用任一商店,那么请在合适的访问层上工作并从该方向解决问题。
Mind, just because you have a k/v store on the back end doesn't mean you have to model your data as only a k/v model. Essentially all a DB is on the backend is a k/v store. If you don't have an insane amount of data, you can do many things. With a large amount of data the hoops you might have to jump through may cost you in performance that you may well not see with a smaller amount of data. All depends.
请注意,仅仅因为您在后端有 ak/v 存储并不意味着您必须仅将数据建模为 ak/v 模型。本质上,后端的所有数据库都是 ak/v 存储。如果你没有大量的数据,你可以做很多事情。对于大量数据,您可能必须跳过的障碍可能会降低性能,而使用少量数据则可能看不到这些。一切都取决于。
回答by Tino
My recommendation is to go for IndexDB, because there is an IndexDB Polyfillavailable.
我的建议是使用 IndexDB,因为有一个IndexDB Polyfill可用。
All browsers supporting WebSQL can support the IndexDB APIthis way. The other way round would be very difficult to implement, so if you want to reach all browsers which know about some DB API, IndexDB is the best choice today.
所有支持 WebSQL 的浏览器都可以通过这种方式支持IndexDB API。反过来,实现起来非常困难,因此如果您想访问所有了解某些 DB API 的浏览器,IndexDB 是当今的最佳选择。
Note: Even that this question is old it still is relevant, so I think the answers to this question deserve an update. And sorry for the link-only solution, so I added only links to usually long lasting destinations: W3C and GitHub
注意:即使这个问题很老它仍然是相关的,所以我认为这个问题的答案值得更新。很抱歉只提供链接的解决方案,所以我只添加了指向通常持久的目的地的链接:W3C 和 GitHub
回答by Kevin
I'm replying to this in 2016 (5 years after you asked this question) and everything concerning the deprecation of WebSQL still stands. IndexedDB on the other hand, enjoys the support of all of the major browser vendors.
我在 2016 年(在您提出这个问题的 5 年后)对此进行了回复,关于弃用 WebSQL 的所有内容仍然有效。另一方面,IndexedDB享有所有主要浏览器供应商的支持。
So to anyone who may find themselves here faced with the same decision to make, go with IndexedDB.
因此,对于可能在这里面临同样决定的任何人,请选择 IndexedDB。
As implied by others here, however, such a decision isn't one that necessarily has to be made; one can simply choose (or make) a library which utilizes whichever database is available on a client machine.
然而,正如这里其他人所暗示的那样,这样的决定并不是必须做出的。人们可以简单地选择(或制作)一个库,该库利用客户端机器上可用的任何数据库。
BakedGoodsdiffers from such libraries already suggested here in several ways; most pertinently, it allows the storage type(s) that are to be utilized to be explicitly specified, in turn allowing the developer to introduce other factors (such as performance characteristics) in to the decision-making process.
BakedGoods与这里已经建议的此类库在几个方面不同;最相关的是,它允许明确指定要使用的存储类型,进而允许开发人员在决策过程中引入其他因素(例如性能特征)。
With it, conducting storage operations in whichever of the database types is supported is a matter of...
有了它,在支持的任何数据库类型中进行存储操作都是一个问题......
... specifying the appropriate operation options and equivalent configs for both database types:
...为两种数据库类型指定适当的操作选项和等效配置:
//If the operation is a set(), and the referenced structures
//don't exist, they will be created automatically.
var webSQLOptionsObj = {
databaseName: "Example_DB",
databaseDisplayName: "Example DB",
databaseVersion: "",
estimatedDatabaseSize: 1024 * 1024,
tableData: {
name: "Main",
keyColumnName: "lastName",
columnDefinitions: "(lastName TEXT PRIMARY KEY, firstName TEXT)"
},
tableIndexDataArray: [name: "First_Name_Index", columnNames: "(firstName)"]
};
var indexedDBOptionsObj = {
databaseName: "Example_DB",
databaseVersion: 1,
objectStoreData: {
name: "Main",
keyPath: lastName,
autoIncrement: false
},
objectStoreIndexDataArray: [
{name: "First_Name_Index", keyPath: "firstName", unique: false, multiEntry: false}
],
};
var optionsObj = {
conductDisjointly: false,
webSQL: webSQLOptionsObj,
indexedDB: indexedDBOptionsObj
};
... and conducting the operation:
...并进行操作:
bakedGoods.set({
data: [
{value: {lastName: "Obama", firstName: "Barack"}},
{value: {lastName: "Biden", firstName: "Joe"}}
],
storageTypes: ["indexedDB", "webSQL"],
options: optionsObj,
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
Its simple interface and unmatched storage facility support comes at the cost of lack of support for some storage facility-specific configurations. For instance, it does not support the conduction of storage operations in WebSQL tables with multi-column primary keys.
其简单的界面和无与伦比的存储设施支持是以缺乏对某些存储设施特定配置的支持为代价的。例如,它不支持在具有多列主键的WebSQL 表中进行存储操作。
So if you make heavy use of those types of features, you may want to look elsewhere.
因此,如果您大量使用这些类型的功能,您可能想看看其他地方。
Oh, and for the sake of complete transparency, BakedGoods is maintained by yours truly :) .
哦,为了完全透明,BakedGoods 由您真正维护:)。
回答by fish2000
Are your database needs significantly beyond key/value stores? If not, I've found a number of javascript packages for local browser-based database abstraction. One such package is jStore:
您的数据库需求是否远远超出键/值存储?如果没有,我已经找到了许多用于基于浏览器的本地数据库抽象的 javascript 包。jStore就是这样的一个包:
http://code.google.com/p/jquery-jstore/
http://code.google.com/p/jquery-jstore/
I recently used it to add local key/value storage. It's well-documented and the integration time was negligible -- it supports an array of storage backends, including flash local storage, through its API.
我最近用它来添加本地键/值存储。它有据可查,集成时间可以忽略不计——它通过其 API 支持一系列存储后端,包括闪存本地存储。
CouchDB is an excellent solution -- for a problem that is not quite congruent with yours. Check out couchone mobile. Not for strictly 'web apps' but it may provide a database foundation you could run with, if you have some flexibility with the specification.
CouchDB 是一个极好的解决方案——对于与您的问题不太一致的问题。检查沙发移动。不是严格意义上的“网络应用程序”,但如果您对规范有一定的灵活性,它可能会提供您可以运行的数据库基础。
回答by Kyaw Tun
With your given requirement of Safari on iOS, there is no alternative but WebSQL. WebSQL is supported in other mobile browser like Opera and Blackberry. I don't think they will remove WebSQL support even if they have IndexedDB. Somehow they are complementary.
根据您对 iOS 上的 Safari 的给定要求,除了 WebSQL 之外别无选择。Opera 和 Blackberry 等其他移动浏览器支持 WebSQL。我不认为他们会删除 WebSQL 支持,即使他们有 IndexedDB。不知何故,它们是互补的。
On the other hand, on browser storage war, IndexedDB win for good. IE and FF will only have IndexedDB. Ironic fact is that FF implements IndexedDB on top of Sqlite.
另一方面,在浏览器存储大战中,IndexedDB 赢了。IE 和 FF 将只有 IndexedDB。具有讽刺意味的是,FF 在 Sqlite 之上实现了 IndexedDB。
What I would like to say is IndexedDB is more than just key value store. It has index and transaction. These only two make almost all feature of SQL query including join, conditional and sorting. It is not obvious at first because of its asynchronous API.
我想说的是 IndexedDB 不仅仅是键值存储。它有索引和事务。只有这两个构成了 SQL 查询的几乎所有功能,包括连接、条件和排序。由于其异步API,一开始并不明显。
Performance of IndexedDB is better than WebSQL. It is more secure. It is more flexible for javascript use case. Lastly it is more easier to use.
IndexedDB 的性能优于 WebSQL。它更安全。它对于 javascript 用例更灵活。最后它更容易使用。
To illustrate the case, I will use sudo code from my library, but you can use IndexedDB API directly:
为了说明这种情况,我将使用我的库中的sudo 代码,但您可以直接使用 IndexedDB API:
The 'people' store has index field 'name' and list indexed field 'hobby'. In JSON,
'people' 商店有索引字段 'name' 和列表索引字段 'hobby'。在 JSON 中,
people = {
name: 'Foo Bar',
email: '[email protected]'
hobby: ['camping', 'swimming']};
To retrieve name from 'people' whose hobby is 'camping'.
从爱好是“露营”的“人”中检索姓名。
var req = db.keys('people', 'hobby', IDBKeyRange.only('camping'));
req.done(function(campers) {
db.keys('people', campers, 'name').done(function(names) {
console.log(names);
});
});
Interesting thing about this code is there is no serialisation involved. Hence it is very fast.
这段代码有趣的是不涉及序列化。因此它非常快。
The following example illustrate friendship graph query. friendship
object store has only one listed indexed field friend_list
. It uses people object store key as out-of-line primary key. people
object store has many attributes, among them is location
field. The query is to find list of friends who know me
and other_guy
and located in 'Singapore'.
以下示例说明了友谊图查询。friendship
对象存储只有一个列出的索引字段friend_list
。它使用人员对象存储键作为外联主键。people
对象存储有很多属性,其中包括location
字段。查询是找到谁知道的朋友列表me
,并other_guy
与设在“新加坡”。
var q1 = new ydn.db.Iterator('friendship', 'friend_list', IDBKeyRange.only(me));
var q2 = new dn.db.Iterator('friendship', 'friend_list', IDBKeyRange.only(other_guy));
// if location is not indexed, a filtered value query is used.
var q3 = new ydn.db.Iterator('people', new ydn.db.Expression(['"location"', "'Singapore'", '=']));
// if location is indexed, an index query is used.
// var q3 = new ydn.db.Iterator('people', 'location', IDBKeyRange.only('Singapore'));
var current_loop = 2; // start from inner loop
var join_algo = function(keys, index_keys) {
var advancement = [];
advancement[keys.length - 1] = null;
var has_adv = false;
for (var i = 0; i < keys.length; i++) {
if (!goog.isDef(keys[i])) {
// completed iterator
if (i != 0) {
advancement[i] = false; // request to restart the iteration
advancement[i - 1] = true; // advance outer iterator
current_loop = i - 1;
} // i == 0 means we are done.
has_adv = true;
break;
}
}
if (!has_adv) {
// continue looping current
advancement[current_loop] = true;
}
return advancement;
}
var result = db.scan([q3, q1, q2], join_algo);
result.done(function(keys, index_keys, values) {
console.log(values); // should get desire list of friends
});
Again this join query is just key scanning and hence very fast. By default scan
use sorted-merge algorithm to find matching keys, but here show naive nested-loop join algorithm. So table joining is possible, but you have to code join algorithm. But newer algorithms like zigzag merge are faster than possible with Sqlite because all inputs are sorted, cursors can advance at well and more importantly join process can exploit external knowledge that is not in the database. With SQL, join operation is opaque.
同样,这个连接查询只是键扫描,因此非常快。默认情况下scan
使用 sorted-merge 算法来查找匹配的键,但这里展示了朴素的嵌套循环连接算法。所以表连接是可能的,但你必须编写连接算法。但是较新的算法(如 zigzag 合并)比 Sqlite 更快,因为所有输入都已排序,游标可以很好地前进,更重要的是,连接过程可以利用数据库中没有的外部知识。使用 SQL,连接操作是不透明的。
Other than that IndexedDB can be used techniques like streaming and map/reduce processing.
除此之外,IndexedDB 还可以使用诸如流式处理和 map/reduce 处理之类的技术。