litedb-org/LiteDB · error · LiteException

0

0

Error message

Collection $query(sql) requires `sql` string parameter

What it means

Thrown by SysQuery.Input when the $query system collection is used without a SQL string argument. options?.AsString returns null when options is null or not a string, so the entire $query(...) call must be a single SQL string literal.

Source

Thrown at LiteDB/Engine/SystemCollections/SysQuery.cs:24

using static LiteDB.Constants;

namespace LiteDB.Engine
{
    /// <summary>
    /// This class implement $query experimental system function to run sub-queries. It's experimental only - possible not be present in final release
    /// </summary>
    internal class SysQuery : SystemCollection
    {
        private readonly ILiteEngine _engine;

        public SysQuery(ILiteEngine engine) : base("$query")
        {
            _engine = engine; 
        }

        public override IEnumerable<BsonDocument> Input(BsonValue options)
        {
            var query = options?.AsString ?? throw new LiteException(0, $"Collection $query(sql) requires `sql` string parameter");

            var sql = new SqlParser(_engine, new Tokenizer(query), null);

            using (var reader = sql.Execute())
            {
                while(reader.Read())
                {
                    var value = reader.Current;

                    yield return value.IsDocument ? value.AsDocument : new BsonDocument { ["expr"] = value };
                }
            }
        }
    }
}

View on GitHub (pinned to f906a5f850)

Solutions

  1. Pass a SQL string: SELECT * FROM $query('SELECT * FROM items WHERE price > 10').
  2. When building dynamically, ensure the interpolated argument is a quoted string literal.
  3. Use parameterized application-side SqlParser execution instead of $query for dynamic SQL.

Example fix

// before
db.Execute("SELECT * FROM $query()"); // throws

// after
db.Execute("SELECT * FROM $query('SELECT * FROM items WHERE active = true')");
Defensive patterns

Strategy: validation

Validate before calling

if (string.IsNullOrWhiteSpace(sql)) throw new ArgumentException("$query requires a SQL string");
db.Execute($"SELECT * FROM $query('{sql.Replace("'", "''")}')");

Try / catch

try { db.Execute("SELECT * FROM $query(...)"); }
catch (LiteException ex) when (ex.Message.Contains("requires `sql` string parameter")) {
    // supply a non-empty SQL string
}

Prevention

When it happens

Trigger: SELECT * FROM $query() with no SQL; $query({ sql:'SELECT...' }) as a document (wrong shape); $query(null); passing a non-string BsonValue.

Common situations: Trying to parameterize $query with a document instead of a plain string; building the call dynamically and passing an empty/null expression; confusing $query with a function that takes options.

Related errors


AI-assisted analysis of litedb-org/LiteDB@f906a5f850 (2026-08-13). Data as JSON: /api/errors/28aef8762580b4b1. Report an issue: GitHub.