Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions src/EntglDb.Persistence.Sqlite/SqlitePeerStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -946,18 +946,47 @@ public async Task<int> CountDocumentsAsync(string collection, QueryNode? queryEx
return documents.Count();
}

public Task EnsureIndexAsync(string collection, string propertyPath, CancellationToken cancellationToken = default)
public async Task EnsureIndexAsync(string collection, string propertyPath, CancellationToken cancellationToken = default)
{
// Not implemented (Placeholder)
return Task.CompletedTask;
using var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);

await EnsureCollectionTablesAsync(connection, collection);

var tableName = GetDocumentTableName(collection);
var usePerCollection = _options?.UsePerCollectionTables == true;

// Sanitize names to prevent injection
var safeColl = new string(collection.Where(char.IsLetterOrDigit).ToArray());
var safeProp = new string(propertyPath.Where(c => char.IsLetterOrDigit(c) || c == '_' || c == '.').ToArray());
var indexName = $"IDX_{safeColl}_{safeProp.Replace(".", "_")}";

string sql;
if (usePerCollection)
{
// Per-collection mode: simple index without collection filter
sql = $@"CREATE INDEX IF NOT EXISTS {indexName}
ON {tableName}(json_extract(JsonData, '$.{safeProp}'))";
}
else
{
// Legacy mode: index with collection filter
sql = $@"CREATE INDEX IF NOT EXISTS {indexName}
ON Documents(json_extract(JsonData, '$.{safeProp}'))
WHERE Collection = '{safeColl}'";
}

await connection.ExecuteAsync(sql);

_logger.LogInformation("Ensured index {IndexName} on {Collection}.{Property}", indexName, collection, propertyPath);
}

public async Task<IEnumerable<string>> GetCollectionsAsync(CancellationToken cancellationToken = default)
{
using var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);

if (UsePerCollectionTables)
if (_options?.UsePerCollectionTables == true)
{
// In per-collection mode, rely on known collection tables.
return GetKnownCollections(connection);
Expand Down