Skip to main content

ic_db_cli/
lib.rs

1//! Transport types shared by the local DB console and its fixture canister.
2#![forbid(unsafe_code)]
3
4pub mod browse;
5#[cfg(feature = "fixture-codec")]
6pub mod fixture_codec;
7
8#[cfg(feature = "host")]
9pub mod host;
10
11/// A local query result, in the fixture's positional field order.
12#[derive(Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
13pub struct ConsolePage {
14    /// Displayed rows and their continuation.
15    pub page: DisplayPage,
16    /// Examined query candidates.
17    pub examined: u32,
18    /// Fetched source rows.
19    pub fetched: u32,
20    /// Encoded result bytes before transport framing.
21    pub output_bytes: u32,
22}
23
24/// Byte predicates on the fixture payload column.
25#[derive(Clone, Default, Debug, serde::Deserialize, serde::Serialize)]
26pub struct PayloadFilters {
27    /// Inclusive lower bound.
28    pub minimum: Option<Vec<u8>>,
29    /// Inclusive upper bound.
30    pub maximum: Option<Vec<u8>>,
31    /// Required prefix.
32    pub prefix: Option<Vec<u8>>,
33    /// Required suffix.
34    pub suffix: Option<Vec<u8>>,
35    /// Required contiguous bytes.
36    pub contains: Option<Vec<u8>>,
37}
38
39/// Entity restrictions shared by ordinary and retained fixture queries.
40#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
41#[cfg_attr(feature = "console", derive(clap::Args))]
42pub struct EntityFilters {
43    /// Entry.amount >= VALUE.
44    #[cfg_attr(feature = "console", arg(long = "min"))]
45    pub minimum: Option<u64>,
46    /// Entry.category == VALUE.
47    #[cfg_attr(feature = "console", arg(long))]
48    pub category: Option<u64>,
49    /// Document.entry_id == VALUE.
50    #[cfg_attr(feature = "console", arg(long))]
51    pub entry_id: Option<u64>,
52}
53
54/// Local query command in fixture fixture field order.
55#[derive(Debug, serde::Deserialize, serde::Serialize)]
56pub struct QueryRequest {
57    /// Selected entity.
58    pub entity: String,
59    /// Encoded continuation.
60    pub cursor: Option<Vec<u8>>,
61    /// Maximum rows per page.
62    pub limit: u32,
63    /// Restrictions on fixture entity fields.
64    pub entity_filters: EntityFilters,
65    /// Ordered field specifications.
66    pub order: Vec<String>,
67    /// Reverse traversal.
68    pub descending: bool,
69    /// Candidate budget.
70    pub work: u32,
71    /// Output byte budget.
72    pub bytes: u32,
73    /// Selected output.
74    pub select: String,
75    /// Grouping and predicates.
76    pub options: QueryOptions,
77}
78
79/// Inclusive group result bounds in positional fixture order.
80#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
81#[cfg_attr(feature = "console", derive(clap::Args))]
82pub struct GroupBounds {
83    /// For grouped summaries, prefix each bound with count:, sum: or avg:.
84    /// Keep completed aggregate values >= VALUE, parsed as the exact result type.
85    /// Signed sums accept negatives; Decimal results accept fractions at their scale.
86    /// Note min/max bounds are literal text in UTF-8 byte order, without normalization.
87    /// Integer results reject fractions; threshold text is bounded to 64 bytes.
88    #[cfg_attr(feature = "console", arg(long, allow_hyphen_values = true))]
89    pub group_min: Option<String>,
90    /// Keep completed aggregate values <= VALUE; same exact types as --group-min.
91    /// Both bounds are inclusive and apply before ordering or output limits.
92    #[cfg_attr(feature = "console", arg(long, allow_hyphen_values = true))]
93    pub group_max: Option<String>,
94}
95
96/// Actions in the fixed local migration demonstration.
97#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
98#[serde(from = "u8")]
99pub enum MigrationAction {
100    /// Seed the source database.
101    Seed,
102    /// Freeze ordinary source access.
103    Freeze,
104    /// Copy a bounded batch.
105    Copy,
106    /// Validate the target.
107    Validate,
108    /// Publish the validated target.
109    Publish,
110    /// Clean up the retired source.
111    Cleanup,
112    /// Read the published target.
113    ReadTarget,
114    /// Read the source.
115    ReadSource,
116    /// Refuse an unknown fixture action without touching backing.
117    Unknown,
118}
119
120// The fixture takes one raw byte, including invalid actions above the Postcard
121// single-byte varint range. Preserve its ordinary error reply for those callers.
122impl From<u8> for MigrationAction {
123    fn from(value: u8) -> Self {
124        [
125            Self::Seed,
126            Self::Freeze,
127            Self::Copy,
128            Self::Validate,
129            Self::Publish,
130            Self::Cleanup,
131            Self::ReadTarget,
132            Self::ReadSource,
133        ]
134        .get(usize::from(value))
135        .copied()
136        .unwrap_or(Self::Unknown)
137    }
138}
139
140/// Ordering accepted by the local fixture for completed groups.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
142#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
143pub enum FixtureGroupOrder {
144    /// The `key` ordering.
145    Key,
146    /// The `key-desc` ordering.
147    KeyDesc,
148    /// The `first` ordering.
149    First,
150    /// The `asc` ordering.
151    Asc,
152    /// The `desc` ordering.
153    Desc,
154    /// The `count:asc` ordering.
155    #[cfg_attr(feature = "console", value(name = "count:asc"))]
156    CountAsc,
157    /// The `count:desc` ordering.
158    #[cfg_attr(feature = "console", value(name = "count:desc"))]
159    CountDesc,
160    /// The `sum:asc` ordering.
161    #[cfg_attr(feature = "console", value(name = "sum:asc"))]
162    SumAsc,
163    /// The `sum:desc` ordering.
164    #[cfg_attr(feature = "console", value(name = "sum:desc"))]
165    SumDesc,
166    /// The `avg:asc` ordering.
167    #[cfg_attr(feature = "console", value(name = "avg:asc"))]
168    AvgAsc,
169    /// The `avg:desc` ordering.
170    #[cfg_attr(feature = "console", value(name = "avg:desc"))]
171    AvgDesc,
172}
173
174/// Options carried together by the query endpoint.
175#[derive(Debug, serde::Deserialize, serde::Serialize)]
176pub struct QueryOptions {
177    /// Request distinct output.
178    pub distinct: bool,
179    /// Lower and upper group bounds.
180    pub group_bounds: GroupBounds,
181    /// Group ordering.
182    pub group_order: Option<FixtureGroupOrder>,
183    /// Row predicates.
184    pub filters: RowFilters,
185}
186
187/// Local fixture status.
188#[derive(Debug, serde::Deserialize, serde::Serialize)]
189pub struct Status {
190    /// Schema fingerprint.
191    pub schema: [u8; 32],
192    /// Store incarnation.
193    pub incarnation: [u8; 16],
194    /// Entry revision.
195    pub revision: u64,
196    /// Wasm linear memory pages.
197    pub pages: u64,
198}
199
200/// Local schema inspection reply.
201#[derive(Debug, serde::Deserialize, serde::Serialize)]
202pub struct SchemaResponse {
203    /// Fixture status.
204    pub status: Status,
205    /// Matching entities.
206    pub entities: Vec<EntityView>,
207    /// Named value types.
208    pub types: Vec<TypeView>,
209}
210
211/// Inspected entity.
212#[derive(Debug, serde::Deserialize, serde::Serialize)]
213pub struct EntityView {
214    /// Entity name.
215    pub name: String,
216    /// Primary key field.
217    #[serde(rename = "primary_key")]
218    pub primary: Vec<String>,
219    /// Stored fields.
220    pub fields: Vec<FieldView>,
221    /// Declared indexes.
222    pub indexes: Vec<IndexView>,
223}
224
225/// Inspected entity field.
226#[derive(Debug, serde::Deserialize, serde::Serialize)]
227pub struct FieldView {
228    /// Field name.
229    pub name: String,
230    /// Field type.
231    #[serde(rename = "type")]
232    pub kind: String,
233    /// Optionality.
234    pub optional: bool,
235    /// Constraints and metadata.
236    pub info: String,
237    /// Reference target and index.
238    pub reference: Option<ReferenceView>,
239}
240
241/// Target and supporting index of an inspected reference.
242#[derive(Debug, serde::Deserialize, serde::Serialize)]
243pub struct ReferenceView {
244    /// Store-local name of the referenced entity.
245    pub target_entity: String,
246    /// Scalar primary-key field on that entity.
247    pub target_field: String,
248    /// Reverse lookup used by strong references.
249    pub index: Option<String>,
250    /// Stable target store key for a weak reference within this canister.
251    pub weak_store: Option<String>,
252    /// Referencing scalar member for a directly embedded record.
253    pub member: Option<String>,
254}
255
256///
257/// IndexView
258/// An index in the inspected schema.
259///
260#[derive(Debug, serde::Deserialize, serde::Serialize)]
261pub struct IndexView {
262    /// Target of a strong reference over all index components.
263    pub reference: Option<String>,
264    /// Index name.
265    pub name: String,
266    /// Component fields in index order.
267    pub fields: Vec<String>,
268    /// Whether the key must be unique.
269    pub unique: bool,
270    /// Whether rows with absent components are excluded.
271    pub present_only: bool,
272    /// Required Boolean membership condition, when declared.
273    pub filter: Option<(String, bool)>,
274}
275
276///
277/// TypeView
278/// A named type in the inspected schema.
279///
280#[derive(Debug, serde::Deserialize, serde::Serialize)]
281pub struct TypeView {
282    /// Schema name.
283    pub name: String,
284    /// Type category.
285    pub kind: String,
286    /// Declared fields, variants or collection roles.
287    pub members: Vec<TypeMemberView>,
288}
289
290///
291/// TypeMemberView
292/// One member of a named schema type.
293///
294#[derive(Debug, serde::Deserialize, serde::Serialize)]
295pub struct TypeMemberView {
296    /// Member name.
297    pub name: String,
298    /// Member type.
299    #[serde(rename = "type")]
300    pub kind: String,
301    /// Whether the member permits absence.
302    pub optional: bool,
303    /// Constraints and metadata.
304    pub info: String,
305}
306
307///
308/// FilterComparison
309/// Comparison carried by a fixture filter.
310///
311#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, Copy)]
312#[cfg_attr(feature = "console", derive(clap::ValueEnum))]
313pub enum FilterComparison {
314    /// Equal.
315    Eq,
316    /// Unequal.
317    Ne,
318    /// Less than.
319    Lt,
320    /// At most.
321    Le,
322    /// Greater than.
323    Gt,
324    /// At least.
325    Ge,
326    /// Prefix match.
327    StartsWith,
328    /// Suffix match.
329    EndsWith,
330    /// Substring match.
331    Contains,
332}
333
334///
335/// ComparisonFilter
336/// A field compared with a typed right operand.
337///
338#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
339pub struct ComparisonFilter<T> {
340    /// Left field.
341    pub field: String,
342    /// Comparison to apply.
343    pub op: FilterComparison,
344    /// Right operand.
345    pub operand: T,
346}
347
348///
349/// FieldRange
350/// Three field names in a range predicate.
351///
352#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
353pub struct FieldRange {
354    /// Tested field.
355    pub field: String,
356    /// Lower end.
357    pub lower: String,
358    /// Upper end.
359    pub upper: String,
360}
361
362/// Row predicates carried by the local query and retained-aggregate commands.
363#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
364pub struct RowFilters {
365    /// Lower bound, upper bound, prefix, suffix and substring on BinaryObject.payload.
366    pub payload: PayloadFilters,
367    /// Left field, comparison, right field.
368    pub compare: Option<ComparisonFilter<String>>,
369    /// Field, comparison and length threshold.
370    pub length: Option<ComparisonFilter<u32>>,
371    /// Require a value in this optional field.
372    pub present: Option<String>,
373    /// Require absence in this optional field.
374    pub absent: Option<String>,
375    /// Field, comparison and exact UTF-8 literal.
376    pub text: Option<ComparisonFilter<String>>,
377    /// Field and Boolean equality operand.
378    pub boolean: Option<(String, bool)>,
379    /// Field, inclusive lower field and inclusive upper field.
380    pub between_fields: Option<FieldRange>,
381    /// Field, lower field and upper field for the strict outside-range comparison.
382    pub not_between_fields: Option<FieldRange>,
383}
384
385/// Selection shared by the private retained fixture when starting and resuming a job.
386#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
387pub struct RetainedSelection {
388    /// Entity name.
389    pub entity: String,
390    /// Aggregate selection.
391    pub select: String,
392    /// Minimum, category and entry ID restrictions.
393    pub entity_filters: EntityFilters,
394    /// Maximum output groups.
395    pub limit: u32,
396    /// Inclusive lower and upper group bounds.
397    pub group_bounds: GroupBounds,
398    /// Completed-group order.
399    pub group_order: Option<FixtureGroupOrder>,
400    /// Row predicates.
401    pub filters: RowFilters,
402    /// Input fields and overall descending flag.
403    pub order: (Vec<String>, bool),
404}
405
406/// One bounded step of a retained fixture query.
407#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
408pub struct RetainedResume {
409    /// Original query.
410    pub selection: RetainedSelection,
411    /// Retained job handle.
412    pub handle: Vec<u8>,
413    /// Last saved step.
414    pub sequence: u64,
415    /// Input work allowance.
416    pub work: u32,
417    /// Output byte allowance.
418    pub bytes: u32,
419    /// Maximum results per page.
420    pub page_size: u32,
421    /// Previous result cursor.
422    pub after: Option<Vec<u8>>,
423}
424
425/// Display columns, rows and continuation shared by ordinary and retained results.
426#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
427pub struct DisplayPage {
428    /// Display column names.
429    pub columns: Vec<String>,
430    /// Display cells in column order.
431    pub rows: Vec<Vec<String>>,
432    /// Encoded continuation for a paged read.
433    pub next: Option<Vec<u8>>,
434}
435
436/// Progress reported by the local fixture after one retained query step.
437#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
438pub struct RetainedProgress {
439    /// Last saved step.
440    pub sequence: u64,
441    /// Candidates examined so far.
442    pub examined: u64,
443    /// Input bytes examined so far.
444    pub input_bytes: u64,
445    /// Encoded result bytes in this step.
446    pub output_bytes: u64,
447    /// Current phase and any completed result.
448    pub phase: RetainedPhase,
449}
450
451/// Only a completed job has output.
452#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
453pub enum RetainedPhase {
454    /// Additional input remains.
455    Running,
456    /// Completed rows and continuation.
457    Complete(DisplayPage),
458    /// Source rows changed.
459    Invalidated,
460    /// Job lifetime elapsed.
461    Expired,
462}
463
464impl RetainedPhase {
465    /// Name used by console progress messages.
466    #[must_use]
467    pub const fn label(&self) -> &'static str {
468        match self {
469            Self::Running => "Running",
470            Self::Complete(_) => "Complete",
471            Self::Invalidated => "Invalidated",
472            Self::Expired => "Expired",
473        }
474    }
475}
476
477/// Render bytes using two lowercase hexadecimal digits per byte and the supplied display prefix.
478#[must_use]
479pub fn lowercase_hex(bytes: &[u8], prefix: &str) -> String {
480    const DIGITS: &[u8; 16] = b"0123456789abcdef";
481    let mut output = String::with_capacity(prefix.len() + bytes.len() * 2);
482    output.push_str(prefix);
483    for &byte in bytes {
484        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
485        output.push(char::from(DIGITS[usize::from(byte & 15)]));
486    }
487    output
488}