Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mechanism for maintaining cache of table counts using triggers #212

Closed
simonw opened this issue Jan 2, 2021 · 1 comment
Closed

Mechanism for maintaining cache of table counts using triggers #212

simonw opened this issue Jan 2, 2021 · 1 comment
Labels

Comments

@simonw
Copy link
Owner

simonw commented Jan 2, 2021

Counting all of the rows in a large table is expensive - this is one of the main causes of performance problems in Datasette when running against large databases.

Carefully constructed SQL triggers could be used to maintain accurate cached counts for a table, by incrementing and decrementing a counter every time a row is inserted or deleted.

sqlite-utils already has a mechanism for creating triggers for FTS - the table.enable_fts(..., create_triggers=True) method. How about a similar mechanism for setting up triggers to maintain a count of table rows?

@simonw
Copy link
Owner Author

simonw commented Jan 2, 2021

Here's a prototype:

with db.conn:
    db.conn.executescript("""
CREATE TABLE IF NOT EXISTS [_counts] ([table] TEXT PRIMARY KEY, [count] INTEGER DEFAULT 0);
CREATE TRIGGER IF NOT EXISTS [Street_Tree_List_counts_ai] AFTER INSERT ON [Street_Tree_List] BEGIN
    INSERT OR REPLACE INTO _counts
        VALUES ('Street_Tree_List', COALESCE(
            (SELECT count FROM _counts
                WHERE [table]='Street_Tree_List'),
            0) + 1);
END;
CREATE TRIGGER IF NOT EXISTS [Street_Tree_List_counts_ad] AFTER DELETE ON [Street_Tree_List] BEGIN
    INSERT OR REPLACE INTO _counts
        VALUES ('Street_Tree_List', COALESCE(
            (SELECT count FROM _counts
                WHERE [table]='Street_Tree_List'),
            0) - 1);
END;
INSERT OR REPLACE INTO _counts VALUES ('Street_Tree_List', (select count(*) from [Street_Tree_List]));
""")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant