lamindb: OperationalError: too many SQL variables

Report

reinstalling my package scdataloader (using uv instead of pip) but with the same lamindb versions: lamindb==0.76.3 bionty==0.49.0

I get an error when doing:

(scDataLoader) ml4ig1@ml4ig1-Precision-7820-Tower:~/Documents code/scDataLoader$ ipython
Python 3.10.15 (main, Oct  2 2024, 16:37:14) [Clang 18.1.8 ]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.27.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import bionty as bt

In [2]: organism = "mouse"

In [3]: names = bt.Gene.public(organism=organism).df()["ensembl_gene_id"]
→ connected lamindb: anonymous/test

In [4]: records = bt.Gene.from_values(
   ...:             names.tolist(),
   ...:             field="ensembl_gene_id",
   ...:             organism=organism,
   ...:         )
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:105, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
    104 else:
--> 105     return self.cursor.execute(sql, params)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py:329, in SQLiteCursorWrapper.execute(self, query, params)
    328 query = self.convert_query(query, param_names=param_names)
--> 329 return super().execute(query, params)

OperationalError: too many SQL variables

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
Cell In[4], line 1
----> 1 records = bt.Gene.from_values(
      2             names.tolist(),
      3             field="ensembl_gene_id",
      4             organism=organism,
      5         )

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_record.py:181, in from_values(cls, values, field, create, organism, source, mute)
    178 from_source = True if cls.__module__.startswith("bionty.") else False
    180 field_str = get_name_field(cls, field=field)
--> 181 return get_or_create_records(
    182     iterable=values,
    183     field=getattr(cls, field_str),
    184     create=create,
    185     from_source=from_source,
    186     organism=organism,
    187     source=source,
    188     mute=mute,
    189 )

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_from_values.py:44, in get_or_create_records(iterable, field, create, from_source, organism, source, mute)
     41 iterable_idx = index_iterable(iterable)
     43 # returns existing records & non-existing values
---> 44 records, nonexist_values, msg = get_existing_records(
     45     iterable_idx=iterable_idx, field=field, mute=mute, **kwargs
     46 )
     48 # new records to be created based on new values
     49 if len(nonexist_values) > 0:

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_from_values.py:167, in get_existing_records(iterable_idx, field, mute, **kwargs)
    164 condition.update({f"{field.field.name}__in": iterable_idx.values})
    166 query_set = model.filter(**condition)
--> 167 records = query_set.list()
    169 # now we have to sort the list of queried records
    170 # preserved = Case(
    171 #     *[
   (...)
    178 
    179 # log validated terms
    180 validated = result.validated

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_query_set.py:261, in QuerySet.list(self, field)
    254 """Populate a list with the results.
    255 
    256 Examples:
    257     >>> queryset.list()  # list of records
    258     >>> queryset.list("name")  # list of values
    259 """
    260 if field is None:
--> 261     return list(self)
    262 else:
    263     return list(self.values_list(field, flat=True))

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/query.py:400, in QuerySet.__iter__(self)
    385 def __iter__(self):
    386     """
    387     The queryset iterator protocol uses three nested iterators in the
    388     default case:
   (...)
    398            - Responsible for turning the rows into model objects.
    399     """
--> 400     self._fetch_all()
    401     return iter(self._result_cache)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/query.py:1928, in QuerySet._fetch_all(self)
   1926 def _fetch_all(self):
   1927     if self._result_cache is None:
-> 1928         self._result_cache = list(self._iterable_class(self))
   1929     if self._prefetch_related_lookups and not self._prefetch_done:
   1930         self._prefetch_related_objects()

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/query.py:91, in ModelIterable.__iter__(self)
     88 compiler = queryset.query.get_compiler(using=db)
     89 # Execute the query. This will also fill compiler.select, klass_info,
     90 # and annotations.
---> 91 results = compiler.execute_sql(
     92     chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
     93 )
     94 select, klass_info, annotation_col_map = (
     95     compiler.select,
     96     compiler.klass_info,
     97     compiler.annotation_col_map,
     98 )
     99 model_cls = klass_info["model"]

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py:1562, in SQLCompiler.execute_sql(self, result_type, chunked_fetch, chunk_size)
   1560     cursor = self.connection.cursor()
   1561 try:
-> 1562     cursor.execute(sql, params)
   1563 except Exception:
   1564     # Might fail for server-side cursors (e.g. connection closed)
   1565     cursor.close()

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:79, in CursorWrapper.execute(self, sql, params)
     78 def execute(self, sql, params=None):
---> 79     return self._execute_with_wrappers(
     80         sql, params, many=False, executor=self._execute
     81     )

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:92, in CursorWrapper._execute_with_wrappers(self, sql, params, many, executor)
     90 for wrapper in reversed(self.db.execute_wrappers):
     91     executor = functools.partial(wrapper, executor)
---> 92 return executor(sql, params, many, context)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:100, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
     98     warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning)
     99 self.db.validate_no_broken_transaction()
--> 100 with self.db.wrap_database_errors:
    101     if params is None:
    102         # params default might be backend specific.
    103         return self.cursor.execute(sql)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/utils.py:91, in DatabaseErrorWrapper.__exit__(self, exc_type, exc_value, traceback)
     89 if dj_exc_type not in (DataError, IntegrityError):
     90     self.wrapper.errors_occurred = True
---> 91 raise dj_exc_value.with_traceback(traceback) from exc_value

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:105, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
    103     return self.cursor.execute(sql)
    104 else:
--> 105     return self.cursor.execute(sql, params)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py:329, in SQLiteCursorWrapper.execute(self, query, params)
    327 param_names = list(params) if isinstance(params, Mapping) else None
    328 query = self.convert_query(query, param_names=param_names)
--> 329 return super().execute(query, params)

OperationalError: too many SQL variables

In [5]: records = bt.Gene.from_values(
   ...:             names,
   ...:             field="ensembl_gene_id",
   ...:             organism=organism,
   ...:         )
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:105, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
    104 else:
--> 105     return self.cursor.execute(sql, params)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py:329, in SQLiteCursorWrapper.execute(self, query, params)
    328 query = self.convert_query(query, param_names=param_names)
--> 329 return super().execute(query, params)

OperationalError: too many SQL variables

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
Cell In[5], line 1
----> 1 records = bt.Gene.from_values(
      2             names,
      3             field="ensembl_gene_id",
      4             organism=organism,
      5         )

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_record.py:181, in from_values(cls, values, field, create, organism, source, mute)
    178 from_source = True if cls.__module__.startswith("bionty.") else False
    180 field_str = get_name_field(cls, field=field)
--> 181 return get_or_create_records(
    182     iterable=values,
    183     field=getattr(cls, field_str),
    184     create=create,
    185     from_source=from_source,
    186     organism=organism,
    187     source=source,
    188     mute=mute,
    189 )

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_from_values.py:44, in get_or_create_records(iterable, field, create, from_source, organism, source, mute)
     41 iterable_idx = index_iterable(iterable)
     43 # returns existing records & non-existing values
---> 44 records, nonexist_values, msg = get_existing_records(
     45     iterable_idx=iterable_idx, field=field, mute=mute, **kwargs
     46 )
     48 # new records to be created based on new values
     49 if len(nonexist_values) > 0:

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_from_values.py:167, in get_existing_records(iterable_idx, field, mute, **kwargs)
    164 condition.update({f"{field.field.name}__in": iterable_idx.values})
    166 query_set = model.filter(**condition)
--> 167 records = query_set.list()
    169 # now we have to sort the list of queried records
    170 # preserved = Case(
    171 #     *[
   (...)
    178 
    179 # log validated terms
    180 validated = result.validated

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/lamindb/_query_set.py:261, in QuerySet.list(self, field)
    254 """Populate a list with the results.
    255 
    256 Examples:
    257     >>> queryset.list()  # list of records
    258     >>> queryset.list("name")  # list of values
    259 """
    260 if field is None:
--> 261     return list(self)
    262 else:
    263     return list(self.values_list(field, flat=True))

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/query.py:400, in QuerySet.__iter__(self)
    385 def __iter__(self):
    386     """
    387     The queryset iterator protocol uses three nested iterators in the
    388     default case:
   (...)
    398            - Responsible for turning the rows into model objects.
    399     """
--> 400     self._fetch_all()
    401     return iter(self._result_cache)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/query.py:1928, in QuerySet._fetch_all(self)
   1926 def _fetch_all(self):
   1927     if self._result_cache is None:
-> 1928         self._result_cache = list(self._iterable_class(self))
   1929     if self._prefetch_related_lookups and not self._prefetch_done:
   1930         self._prefetch_related_objects()

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/query.py:91, in ModelIterable.__iter__(self)
     88 compiler = queryset.query.get_compiler(using=db)
     89 # Execute the query. This will also fill compiler.select, klass_info,
     90 # and annotations.
---> 91 results = compiler.execute_sql(
     92     chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
     93 )
     94 select, klass_info, annotation_col_map = (
     95     compiler.select,
     96     compiler.klass_info,
     97     compiler.annotation_col_map,
     98 )
     99 model_cls = klass_info["model"]

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py:1562, in SQLCompiler.execute_sql(self, result_type, chunked_fetch, chunk_size)
   1560     cursor = self.connection.cursor()
   1561 try:
-> 1562     cursor.execute(sql, params)
   1563 except Exception:
   1564     # Might fail for server-side cursors (e.g. connection closed)
   1565     cursor.close()

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:79, in CursorWrapper.execute(self, sql, params)
     78 def execute(self, sql, params=None):
---> 79     return self._execute_with_wrappers(
     80         sql, params, many=False, executor=self._execute
     81     )

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:92, in CursorWrapper._execute_with_wrappers(self, sql, params, many, executor)
     90 for wrapper in reversed(self.db.execute_wrappers):
     91     executor = functools.partial(wrapper, executor)
---> 92 return executor(sql, params, many, context)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:100, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
     98     warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning)
     99 self.db.validate_no_broken_transaction()
--> 100 with self.db.wrap_database_errors:
    101     if params is None:
    102         # params default might be backend specific.
    103         return self.cursor.execute(sql)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/utils.py:91, in DatabaseErrorWrapper.__exit__(self, exc_type, exc_value, traceback)
     89 if dj_exc_type not in (DataError, IntegrityError):
     90     self.wrapper.errors_occurred = True
---> 91 raise dj_exc_value.with_traceback(traceback) from exc_value

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/utils.py:105, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
    103     return self.cursor.execute(sql)
    104 else:
--> 105     return self.cursor.execute(sql, params)

File ~/Documents code/scDataLoader/.venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py:329, in SQLiteCursorWrapper.execute(self, query, params)
    327 param_names = list(params) if isinstance(params, Mapping) else None
    328 query = self.convert_query(query, param_names=param_names)
--> 329 return super().execute(query, params)

OperationalError: too many SQL variables

No clear idea why but this wasn’t the case before and in my other installation it does work well…

Version information

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 17 (8 by maintainers)

Most upvoted comments

for now my quick fix is to load elements by block of 10k. But this bug is so weird… Let me know if you have any ideas otherwise I will leave it here.