我的主要目标是将以下结构保留在 android/IOS 的 sqlite 中的数据库中。相应的表将由 pragma 处理的外键组成。
var tempData = [{
name : "foo",
values : [{
child : "foofoo",
value : [1, 2, 3]
}, {
child : "foofaa",
value : [5, 6, 7]
}
]
}, {
name : "bar",
values : [{
child : "barbar",
values : [11, 22, 33]
}, {
child : "barbala",
values : [44, 55, 66]
}
]
}, {
name : "baz",
values : [{
child : "bazbaz",
values : [444, 333, 222]
}, {
child : "bazbaazar",
values : [999, 888, 777]
}
]
}];
我写了下面的代码片段来保持上述结构。这是克服嵌套事务的传统方法吗?还是我必须遵循一些标准?
下面的代码工作正常,只是不能保证执行顺序。我在输出中看到了一些随机行为。我如何保证嵌套事务的同步行为。我已经抓取了许多网站,但找不到坦诚的解决方案。请帮忙
db.transaction(setupTable, dbErrorHandler, getEntries);
function setupTable(tx) {
doLog("before execute sql...");
tx.executeSql('CREATE TABLE IF NOT EXISTS mainTest(mainKey INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)');
tx.executeSql('CREATE TABLE IF NOT EXISTS child(PKEY INTEGER PRIMARY KEY AUTOINCREMENT,parentKey INTEGER,children TEXT NOT NULL,FOREIGN KEY(parentKey) REFERENCES mainTest(mainKey))');
tx.executeSql('CREATE TABLE IF NOT EXISTS secondChild(SCKEY INTEGER PRIMARY KEY AUTOINCREMENT,spkey INTEGER,sales INTEGER,FOREIGN KEY(spkey) REFERENCES child(PKEY))');
doLog("after execute sql...");}
function getEntries(tx) {
//doLog("get entries");
/*dbShell.transaction(function(tx) {
tx.executeSql("select id, title, body, updated from notes order by updated desc",[],renderEntries,dbErrorHandler);
}, dbErrorHandler);*/
doLog("get entries");
db.transaction(function (tx) {
_.each(tempData, function (item) {
name = item.name;
tx.executeSql('INSERT INTO mainTest (name) VALUES("' + name + '")', [], function (tx, result) {
doLog("in child insert" + item.values);
doLog("in child insert" + JSON.stringify(tempData));
_.each(item.values, function (item) {
doLog("in " + item.child);
tx.executeSql('INSERT INTO child (parentKey,children) VALUES((select mainKey from mainTest where name = "' + name + '"),"' + item.child + '")', [], function (tx, result) {
_.each(item.values, function (itemNew) {
tx.executeSql('INSERT INTO secondChild (spkey,sales) VALUES((select PKEY from child where children = "' + item.child + '"),"' + itemNew + '")', [], function (tx, result) {}, dbErrorHandler);
});
}, dbErrorHandler);
doLog("after secondChild Insertion");
});
doLog("after child insertion");
}, dbErrorHandler);
doLog("after main insertion");
});
}, dbErrorHandler);}