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