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