using Chronos.Core.Model; namespace Chronos.Data.Repositories; /// /// Projects of sequences and their versions (owner review 2, R8; projects, project_versions). The sidecars /// in .chronos/projects/ are the truth and are written first (Projects.ProjectService); these rows are /// derived, rebuilt from the sidecars, and go with the sequence's row. /// public sealed class ProjectRepository { private const string Columns = "id, sequence_id, name, is_main, head_version_id, head_number, mirrored_settings_version, mirrored_version_id, created_by, created_at, " + "updated_at, deleted_at"; private const string VersionColumns = "id, project_id, parent_id, number, kind, author, client_name, note, settings_json, content_hash, settings_format, frames_version, " + "restored_from, created_at, stored_at"; private readonly DbAccess _db; internal ProjectRepository(DbAccess db) => _db = db; /// The projects of a sequence: Main first, then the others oldest first; deleted ones only when asked. public Task> ListBySequenceAsync(Guid sequenceId, bool includeDeleted = false, CancellationToken cancellationToken = default) => _db.ListAsync($"SELECT {Columns} FROM projects WHERE sequence_id = $1{(includeDeleted ? string.Empty : " AND deleted_at IS NULL")} " + "ORDER BY is_main DESC, created_at, id", [sequenceId], Map, cancellationToken); public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => _db.SingleAsync($"SELECT {Columns} FROM projects WHERE id = $1", [id], Map, cancellationToken); /// The Main project of a sequence; null until it is made. public Task GetMainAsync(Guid sequenceId, CancellationToken cancellationToken = default) => _db.SingleAsync($"SELECT {Columns} FROM projects WHERE sequence_id = $1 AND is_main = $2 AND deleted_at IS NULL", [sequenceId, true], Map, cancellationToken); /// Adds a project; a name or a Main another live project of the sequence has already fails (unique). public Task InsertAsync(SequenceProject project, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(project); return _db.ExecuteAsync($"INSERT INTO projects ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)", [ project.Id, project.SequenceId, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.MirroredSettingsVersion, project.MirroredVersionId, project.CreatedBy, project.CreatedAt, project.UpdatedAt, project.DeletedAt, ], cancellationToken); } /// Stores every field of but its id, sequence and creation; false when it is gone. public async Task UpdateAsync(SequenceProject project, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(project); return await _db.ExecuteAsync( "UPDATE projects SET name = $2, is_main = $3, head_version_id = $4, head_number = $5, mirrored_settings_version = $6, mirrored_version_id = $7, " + "updated_at = $8, deleted_at = $9 WHERE id = $1", [ project.Id, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.MirroredSettingsVersion, project.MirroredVersionId, project.UpdatedAt, project.DeletedAt, ], cancellationToken).ConfigureAwait(false) > 0; } /// /// Moves the head to (number ) only while it is still at /// : two writers never both advance it from the same head. False when it moved. /// public async Task AdvanceHeadAsync(Guid projectId, int expectedNumber, Guid headId, int headNumber, DateTimeOffset at, CancellationToken cancellationToken = default) => await _db.ExecuteAsync("UPDATE projects SET head_version_id = $2, head_number = $3, updated_at = $4 WHERE id = $1 AND head_number = $5", [projectId, headId, headNumber, at, expectedNumber], cancellationToken).ConfigureAwait(false) > 0; /// Records the version and the sequence's settings version a Main project's head was last mirrored with. public async Task SetMirroredAsync(Guid projectId, Guid? versionId, int settingsVersion, CancellationToken cancellationToken = default) => await _db.ExecuteAsync("UPDATE projects SET mirrored_version_id = $2, mirrored_settings_version = $3 WHERE id = $1", [projectId, versionId, settingsVersion], cancellationToken).ConfigureAwait(false) > 0; /// Adds a version; a number or id the project has already fails (unique). public Task InsertVersionAsync(ProjectVersion version, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(version); return _db.ExecuteAsync($"INSERT INTO project_versions ({VersionColumns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)", [ version.Id, version.ProjectId, version.ParentId, version.Number, ProjectVersionKinds.Name(version.Kind), version.Author, version.ClientName, version.Note, DbParam.Text(version.SettingsJson), version.ContentHash, version.SettingsFormat, version.FramesVersion, version.RestoredFrom, version.CreatedAt, version.StoredAt ?? version.CreatedAt, ], cancellationToken); } public Task GetVersionAsync(Guid id, CancellationToken cancellationToken = default) => _db.SingleAsync($"SELECT {VersionColumns} FROM project_versions WHERE id = $1", [id], MapVersion, cancellationToken); public Task GetVersionByNumberAsync(Guid projectId, int number, CancellationToken cancellationToken = default) => _db.SingleAsync($"SELECT {VersionColumns} FROM project_versions WHERE project_id = $1 AND number = $2", [projectId, number], MapVersion, cancellationToken); /// /// One page of a project's history, newest first: the versions numbered below (all /// when null), at most (1–1000). /// public Task> ListVersionsAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken = default) => _db.ListAsync($"SELECT {VersionColumns} FROM project_versions WHERE project_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3", [projectId, beforeNumber ?? int.MaxValue, Cursor.ClampLimit(limit)], MapVersion, cancellationToken); /// The versions numbered above , oldest first, at most (1–1000): what a pull takes. public Task> ListVersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken = default) => _db.ListAsync($"SELECT {VersionColumns} FROM project_versions WHERE project_id = $1 AND number > $2 ORDER BY number LIMIT $3", [projectId, afterNumber, Cursor.ClampLimit(limit)], MapVersion, cancellationToken); /// The id of each version of a project by number (the index's side of a comparison with the sidecars). public async Task> ListVersionIdsAsync(Guid projectId, CancellationToken cancellationToken = default) { var rows = await _db.ListAsync("SELECT number, id FROM project_versions WHERE project_id = $1", [projectId], r => (r.GetInt32(0), r.GetGuid(1)), cancellationToken).ConfigureAwait(false); return rows.ToDictionary(r => r.Item1, r => r.Item2); } private static SequenceProject Map(DbRow r) => new() { Id = r.GetGuid(0), SequenceId = r.GetGuid(1), Name = r.GetString(2), IsMain = r.GetBool(3), HeadVersionId = r.GetGuidOrNull(4), HeadNumber = r.GetInt32(5), MirroredSettingsVersion = r.GetInt32OrNull(6), MirroredVersionId = r.GetGuidOrNull(7), CreatedBy = r.GetStringOrNull(8), CreatedAt = r.GetDateTimeOffset(9), UpdatedAt = r.GetDateTimeOffset(10), DeletedAt = r.GetDateTimeOffsetOrNull(11), }; private static ProjectVersion MapVersion(DbRow r) => new() { Id = r.GetGuid(0), ProjectId = r.GetGuid(1), ParentId = r.GetGuidOrNull(2), Number = r.GetInt32(3), Kind = ProjectVersionKinds.Parse(r.GetStringOrNull(4)), Author = r.GetStringOrNull(5), ClientName = r.GetStringOrNull(6), Note = r.GetStringOrNull(7), SettingsJson = r.GetString(8), ContentHash = r.GetString(9), SettingsFormat = r.GetInt32(10), FramesVersion = r.GetInt32(11), RestoredFrom = r.GetGuidOrNull(12), CreatedAt = r.GetDateTimeOffset(13), StoredAt = r.GetDateTimeOffset(14), }; }