(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName)
| 8013 | } |
| 8014 | |
| 8015 | async function createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName) { |
| 8016 | const viewSignature = createViewSignature(mapFun, reduceFun); |
| 8017 | |
| 8018 | let cachedViews; |
| 8019 | if (!temporary) { |
| 8020 | // cache this to ensure we don't try to update the same view twice |
| 8021 | cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {}; |
| 8022 | if (cachedViews[viewSignature]) { |
| 8023 | return cachedViews[viewSignature]; |
| 8024 | } |
| 8025 | } |
| 8026 | |
| 8027 | const promiseForView = sourceDB.info().then(async function (info) { |
| 8028 | const depDbName = info.db_name + '-mrview-' + |
| 8029 | (temporary ? 'temp' : stringMd5(viewSignature)); |
| 8030 | |
| 8031 | // save the view name in the source db so it can be cleaned up if necessary |
| 8032 | // (e.g. when the _design doc is deleted, remove all associated view data) |
| 8033 | function diffFunction(doc) { |
| 8034 | doc.views = doc.views || {}; |
| 8035 | let fullViewName = viewName; |
| 8036 | if (fullViewName.indexOf('/') === -1) { |
| 8037 | fullViewName = viewName + '/' + viewName; |
| 8038 | } |
| 8039 | const depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {}; |
| 8040 | /* istanbul ignore if */ |
| 8041 | if (depDbs[depDbName]) { |
| 8042 | return; // no update necessary |
| 8043 | } |
| 8044 | depDbs[depDbName] = true; |
| 8045 | return doc; |
| 8046 | } |
| 8047 | await upsert(sourceDB, '_local/' + localDocName, diffFunction); |
| 8048 | const res = await sourceDB.registerDependentDatabase(depDbName); |
| 8049 | const db = res.db; |
| 8050 | db.auto_compaction = true; |
| 8051 | const view = { |
| 8052 | name: depDbName, |
| 8053 | db, |
| 8054 | sourceDB, |
| 8055 | adapter: sourceDB.adapter, |
| 8056 | mapFun, |
| 8057 | reduceFun |
| 8058 | }; |
| 8059 | |
| 8060 | let lastSeqDoc; |
| 8061 | try { |
| 8062 | lastSeqDoc = await view.db.get('_local/lastSeq'); |
| 8063 | } catch (err) { |
| 8064 | /* istanbul ignore if */ |
| 8065 | if (err.status !== 404) { |
| 8066 | throw err; |
| 8067 | } |
| 8068 | } |
| 8069 | |
| 8070 | view.seq = lastSeqDoc ? lastSeqDoc.seq : 0; |
| 8071 | if (cachedViews) { |
| 8072 | view.db.once('destroyed', function () { |
no test coverage detected
searching dependent graphs…