Unbatched queries hit 'OperationalError: too many SQL variables' in _collect_and_delete_violating_records and bulk user import
❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.
Observed behavior
Using a large database with some broken data, on startup the _collect_and_delete_violating_records utility can raise sqlite3.OperationalError: too many SQL variables when there are too many broken things.
On develop at 5a9f408bfd with SQLite, bulkimportusers hits the same error: three queries in bulk_import.py take one variable per row (limit 999 before SQLite 3.32.0, 32,766 from it: https://www.sqlite.org/limits.html#max_variable_number). No user is imported and no per-line report is written.
L601-L605: one per row with aUUID. This is the query that raises.L724-L726: with--delete, one per matched user and facility admin.L730-L732: with--delete, one per class the CSV names that already exists.
Errors and logs
Error: Traceback (most recent call last):
File "/home/bjester/Projects/learningequality/kolibri/streaming-serialize/kolibri/utils/cli.py", line 201, in invoke
initialize(**get_initialize_params())
File "/home/bjester/Projects/learningequality/kolibri/streaming-serialize/kolibri/utils/main.py", line 289, in initialize
_upgrades_before_django_setup(updated, version)
File "/home/bjester/Projects/learningequality/kolibri/streaming-serialize/kolibri/utils/main.py", line 209, in _upgrades_before_django_setup
sqlite_check_foreign_keys(DATABASE_NAMES)
File "/home/bjester/Projects/learningequality/kolibri/streaming-serialize/kolibri/utils/database.py", line 98, in sqlite_check_foreign_keys
records_to_backup = _collect_and_delete_violating_records(
File "/home/bjester/Projects/learningequality/kolibri/streaming-serialize/kolibri/utils/database.py", line 37, in _collect_and_delete_violating_records
cursor.execute(
sqlite3.OperationalError: too many SQL variables
kolibri/core/auth/utils/bulk_import.py:618: in build_users_objects
django.db.utils.OperationalError: too many SQL variables
Expected behavior
I believe there's a utility within Kolibri that can be used to iteratively batch the parameters to avoid this issue.
- [ ] On SQLite,
bulkimportusersimports a CSV in which more rows carry aUUIDthanSQLITE_LIMIT_VARIABLE_NUMBER. - [ ] The same import with
--deletecompletes, and deletes only users the CSV does not name. - [ ] With
--delete, a CSV naming more existing classes than the limit completes, and clears only classes the CSV does not name. - [ ] A test covers each of the three, with the variable limit lowered rather than tens of thousands of rows.
User-facing consequences
Large implementations with historical broken data may hit this.
An admin of a facility with more users than the limit (1000 on SQLite before 3.32.0) cannot re-import the CSV bulk export wrote, since export fills UUID on every row.
Importing the file in parts under the limit works without --delete. With --delete, each part deletes the users named only in the other parts.
Steps to reproduce
Create 1000 broken FK constrains, perhaps in content_contentnode_tags
bulkimportusers <file> --facility <id> with 1000 rows on SQLite before 3.32.0, or 32,767 rows from it, each with a UUID, unique USERNAME, PASSWORD and USER_TYPE=LEARNER. A test reproduces it with 401 rows after connection.connection.setlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, 400) (Python 3.11+).
Context
Branch: release-v0.19.x
bulkimportusers hits the same error. On develop at 5a9f408bfd with SQLite, a CSV with more UUID rows than the variable limit (32,766 on SQLite 3.53) raises OperationalError; no user is imported and no per-line report is written. Three queries in bulk_import.py take one variable per row:
L601-L605: one per row with aUUID. This is the query that raises.L724-L726: with--delete, one per matched user and facility admin.L730-L732: with--delete, one per class the CSV names that already exists.
kolibri/core/auth/utils/bulk_import.py:618: in build_users_objects
django.db.utils.OperationalError: too many SQL variables
An admin of a facility with more than 32,766 users cannot re-import the CSV bulk export wrote, since export fills UUID on every row.
Reproduce: bulkimportusers <file> --facility <id> with 32,767 rows, each with a UUID, unique USERNAME, PASSWORD and USER_TYPE=LEARNER. A test reproduces it with 401 rows after connection.connection.setlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, 400) (Python 3.11+).
Acceptance criteria for this site:
- [ ] On SQLite,
bulkimportusersimports a CSV in which more rows carry aUUIDthanSQLITE_LIMIT_VARIABLE_NUMBER. - [ ] The same import with
--deletecompletes, and deletes only users the CSV does not name. - [ ] With
--delete, a CSV naming more existing classes than the limit completes, and clears only classes the CSV does not name. - [ ] A test covers each of the three, with the variable limit lowered rather than tens of thousands of rows.
🤖 Found by Claude Code while reviewing the branch for #15867; the first query's failure was reproduced with the lowered limit. No human has reviewed it.
Written by rtibblesbot, an LLM-based coding agent.
The bulk import failure starts at 1000 rows, not 32,767, on SQLite builds older than 3.32.0. Those builds allow 999 variables per query: https://www.sqlite.org/limits.html#max_variable_number
- An admin of a facility with 1000 or more users on such a build cannot export the users, edit the file and import it again.
- Without
--delete, importing the file in parts of under 999 rows works. With--delete, each part deletes the users named only in the other parts.
Reproduce in a Django TestCase on Python 3.11+:
- Create a facility with 1000 users.
call_command("bulkexportusers", output_file=path, overwrite=True, facility=facility.id)connection.connection.setlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, 999)call_command("bulkimportusers", path, facility=facility.id)raisesOperationalError: too many SQL variables. With 900 users it imports.
🤖 Found by Claude Code while reviewing #15926 and reproduced on develop at 5a9f408bfd. No human has reviewed it.
Written by rtibblesbot, an LLM-based coding agent.
These tests reproduce the first two bulk import criteria. Both fail on develop at 5a9f408bfd and need Python 3.11+ for Connection.setlimit:
import csv
import sqlite3
import tempfile
from django.core.management import call_command
from django.db import connection
from django.test import TestCase
from kolibri.core.auth.models import Facility
from kolibri.core.auth.models import FacilityUser
from kolibri.core.auth.utils.bulk_export import labels
from kolibri.core.utils.csv import open_csv_for_writing
class VariableLimitTestCase(TestCase):
databases = "__all__"
def _import_existing_users(self, *args):
facility = Facility.objects.create(name="F")
limit = 400
users = [
FacilityUser.objects.create(username=f"u{i}", facility=facility)
for i in range(limit + 1)
]
_, filename = tempfile.mkstemp(suffix=".csv")
with open_csv_for_writing(local_filepath=filename) as f:
writer = csv.writer(f)
writer.writerow(labels.values())
for user in users:
writer.writerow([user.id, user.username, "*", "", "LEARNER"] + [""] * 5)
connection.ensure_connection()
default = connection.connection.setlimit(
sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, limit
)
self.addCleanup(
connection.connection.setlimit, sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, default
)
call_command("bulkimportusers", filename, *args, facility=facility.id)
self.assertEqual(
FacilityUser.objects.filter(facility=facility).count(), len(users)
)
def test_imports_more_existing_users_than_sqlite_allows_query_variables(self):
self._import_existing_users()
def test_delete_keeps_more_users_than_sqlite_allows_query_variables(self):
self._import_existing_users("--delete")
🤖 Found by Claude Code while reviewing #15926. No human has reviewed it.
Written by rtibblesbot, an LLM-based coding agent.