MCPcopy Create free account
hub / github.com/WiseLibs/better-sqlite3 / xBestIndex

Method xBestIndex

src/util/custom-table.cpp:289–338  ·  view source on GitHub ↗

This method tells SQLite how to *plan* queries on our virtual table. It gets invoked (typically multiple times) during db.prepare().

Source from the content-addressed store, hash-verified

287 // This method tells SQLite how to *plan* queries on our virtual table.
288 // It gets invoked (typically multiple times) during db.prepare().
289 static int xBestIndex(sqlite3_vtab* vtab, sqlite3_index_info* output) {
290 int parameter_count = VTab::Upcast(vtab)->parameter_count;
291 int argument_count = 0;
292 std::vector<std::pair<int, int>> forwarded;
293
294 for (int i = 0, len = output->nConstraint; i < len; ++i) {
295 auto item = output->aConstraint[i];
296
297 // The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET
298 // operators have no left-hand operand, and so for those operators the
299 // corresponding item.iColumn is meaningless.
300 // We don't care those constraints.
301 if (item.op == SQLITE_INDEX_CONSTRAINT_LIMIT || item.op == SQLITE_INDEX_CONSTRAINT_OFFSET) {
302 continue;
303 }
304 // We only care about constraints on parameters, not regular columns.
305 if (item.iColumn >= 0 && item.iColumn < parameter_count) {
306 if (item.op != SQLITE_INDEX_CONSTRAINT_EQ) {
307 sqlite3_free(vtab->zErrMsg);
308 vtab->zErrMsg = sqlite3_mprintf(
309 "virtual table parameter \"%s\" can only be constrained by the '=' operator",
310 VTab::Upcast(vtab)->parameter_names.at(item.iColumn).c_str());
311 return SQLITE_ERROR;
312 }
313 if (!item.usable) {
314 // Don't allow SQLite to make plans that ignore arguments.
315 // Otherwise, a user could pass arguments, but then they
316 // could appear undefined in the generator function.
317 return SQLITE_CONSTRAINT;
318 }
319 forwarded.emplace_back(item.iColumn, i);
320 }
321 }
322
323 // Tell SQLite to forward arguments to xFilter.
324 std::sort(forwarded.begin(), forwarded.end());
325 for (std::pair<int, int> pair : forwarded) {
326 int bit = 1 << pair.first;
327 if (!(output->idxNum & bit)) {
328 output->idxNum |= bit;
329 output->aConstraintUsage[pair.second].argvIndex = ++argument_count;
330 output->aConstraintUsage[pair.second].omit = 1;
331 }
332 }
333
334 // Use a very high estimated cost so SQLite is not tempted to invoke the
335 // generator function within a loop, if it can be avoided.
336 output->estimatedCost = output->estimatedRows = 1000000000 / (argument_count + 1);
337 return SQLITE_OK;
338 }
339
340 void PropagateJSError() {
341 assert(db->GetState()->was_js_error == false);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected