Trending

World technology news

→
From SQLite 3.8.3 to expression indexes: why a stock-code function needs stable results
Software Engineering · 2014
Software Engineering2014

From SQLite 3.8.3 to expression indexes: why a stock-code function needs stable results

A stock-code lookup illustrates SQLite’s 2014 deterministic function flag and compares a rejected index definition with a working expression index in a current runtime.

Archive retrospective · Topic year 2014

Developer's JournalPublished: Dec 5, 20266 min read
Reading progress0%
In this article
  1. What the 2014 flag let applications express
  2. Give normalization a narrow, explicit meaning
  3. Observe rejection and successful lookup locally
  4. Keep the search expression aligned with the index
  5. A change to the rule can require rebuilding stored keys
  6. Register the function for each relevant connection
  7. Check the runtime that will open the database

What the 2014 flag let applications express

SQLite 3.8.3 was released on February 3, 2014. Its release notes introduced the SQLITE_DETERMINISTIC flag for application-defined SQL functions. The flag tells SQLite that the same inputs produce the same result. In some plans, that information can let SQLite move a call outside an inner loop. The illustrative expression index in this article arrived later, in SQLite 3.9.0 in 2015. Distinguishing those dates places the flag and the index feature in their actual releases. I use an inventory key to show why stable function output matters today. The table retains the original code, while a function produces the value used by searches.

Give normalization a narrow, explicit meaning

The sample function uppercases a code and removes ASCII spaces and hyphens. Both PA-042 and PA 042 therefore produce PA042. This is a limited example. A real catalog might use the hyphen to encode a product family or region, in which case removing it could create unwanted collisions. The sample uses a non-unique index and returns both matching rows. Define how punctuation, case and empty input work before choosing a normalization rule. Avoid reading mutable configuration, the current time or a local file from a function used as a stable index key. A code that reads those inputs might yield different results when the input stock identifier remains the same.

Database access flowConceptual sketch · summary of the article's technical flow

Observe rejection and successful lookup locally

I ran the example with Python 3.12.10 and SQLite 3.49.1 in memory. A three-row table contains two spellings of PA042 and one other code. The first registration leaves the deterministic flag unset. SQLite rejects the expression index because unmarked application functions are treated as non-deterministic. The second registration passes deterministic=True and the index is created. A lookup for PA042 returns IDs 1 and 2. The query plan refers to stock_normalized, the index built by the example. The test checks the index name and actual rows instead of matching an entire diagnostic string. This is a current-runtime demonstration. It does not run the historical SQLite 3.8.3 binary.

import sqlite3

def normalized_code(value):
    if value is None:
        return None
    return value.upper().replace("-", "").replace(" ", "")

with sqlite3.connect(":memory:") as db:
    db.execute("CREATE TABLE stock(id INTEGER PRIMARY KEY, code TEXT NOT NULL)")
    db.executemany("INSERT INTO stock(code) VALUES (?)",
        [("pa-042",), ("PA 042",), ("PB-103",)])
    db.create_function("normalize_code", 1, normalized_code)
    try:
        db.execute("CREATE INDEX stock_normalized ON stock(normalize_code(code))")
    except sqlite3.OperationalError as error:
        assert "non-deterministic" in str(error)
        print("default registration:", error)
    else:
        raise AssertionError("An unmarked function was accepted")
    db.create_function("normalize_code", 1, normalized_code, deterministic=True)
    db.execute("CREATE INDEX stock_normalized ON stock(normalize_code(code))")
    query="SELECT id FROM stock WHERE normalize_code(code) = ?"
    plan=db.execute("EXPLAIN QUERY PLAN " + query, ("PA042",)).fetchall()
    items=db.execute(query, ("PA042",)).fetchall()
    assert any("stock_normalized" in row[-1] for row in plan)
    assert sorted(items) == [(1,), (2,)]
    print("query plan:", plan[0][-1])
    print("matches:", sorted(items), "| SQLite", sqlite3.sqlite_version)

Keep the search expression aligned with the index

An expression index stores keys derived from the values in the table. SQLite’s documentation explains that the planner looks for a matching expression and does not generally rewrite algebraically equivalent expressions to find an index. Calling normalize_code in both the index and the lookup establishes a stable relationship. When changing filters or sorting, revisit the plan on representative data. A full scan can be satisfactory on three rows, while a large catalog has different costs. Keep the actual row assertions as well as the plan assertion. Index access can make a query faster while still returning the wrong records if the normalization rule fails to match the catalog’s semantics.

A change to the rule can require rebuilding stored keys

If a new release registers different behavior under the same function name, its future results can diverge from the keys already in the index. Suppose a hyphen becomes significant for one category of stock code. A previously indexed PA-042 row may still be found under PA042 until the index reflects the new rule. SQLite documents the risk of using a function falsely marked deterministic in an expression or partial index. A migration can test a versioned replacement function, compare results, and rebuild the index under a controlled rollout. REINDEX can rebuild an affected index according to the function currently available to the connection. Coordinate that operation with the application's writers and verify both the query results and the plan afterward.

Register the function for each relevant connection

The Python API registers a function on a connection. A second process that opens the same database may also need that function, especially if it writes to a table and updates the index as part of the write. An import task, an application server and a maintenance tool can all load the same database while using different connection setup code. A rollout should check how each process loads the function and which implementation it uses. A missing function and a legitimate search with no results require different handling. Exercise a fresh connection in the test so that a previously initialized session cannot hide a dependency on startup configuration.

Check the runtime that will open the database

The deterministic parameter in today’s Python sqlite3 library is a later way to pass the flag added to the C API in 2014. Inspect the SQLite library version used by the application rather than assuming that a separate command-line executable has the same version. An application targeting SQLite releases before 3.9.0 cannot rely on reading a database containing expression indexes. Record the runtime, sample inputs, expected rows and observed query plan with the migration. If the inventory system later adds another separator to its codes, those same examples can be rerun under the proposed rule. The release record can then show whether a match reflects the intended catalog policy or an unintended collision.

570 reads ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.