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 = "host")]
5pub mod host;
6
7/// A local query result, in the fixture's positional Wire field order.
8#[derive(Debug, serde::Deserialize, serde::Serialize)]
9pub struct ConsolePage {
10    /// Displayed rows and their continuation.
11    pub page: DisplayPage,
12    /// Examined query candidates.
13    pub examined: u32,
14    /// Fetched source rows.
15    pub fetched: u32,
16    /// Encoded result bytes before transport framing.
17    pub output_bytes: u32,
18}
19
20/// Byte predicates on the fixture payload column.
21#[derive(Clone, Default, Debug, serde::Deserialize, serde::Serialize)]
22pub struct PayloadFilters {
23    /// Inclusive lower bound.
24    pub minimum: Option<Vec<u8>>,
25    /// Inclusive upper bound.
26    pub maximum: Option<Vec<u8>>,
27    /// Required prefix.
28    pub prefix: Option<Vec<u8>>,
29    /// Required suffix.
30    pub suffix: Option<Vec<u8>>,
31    /// Required contiguous bytes.
32    pub contains: Option<Vec<u8>>,
33}
34
35/// Entity restrictions shared by ordinary and retained fixture queries.
36#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
37#[cfg_attr(feature = "console", derive(clap::Args))]
38pub struct EntityFilters {
39    /// Entry.amount >= VALUE.
40    #[cfg_attr(feature = "console", arg(long = "min"))]
41    pub minimum: Option<u64>,
42    /// Entry.category == VALUE.
43    #[cfg_attr(feature = "console", arg(long))]
44    pub category: Option<u64>,
45    /// Document.entry_id == VALUE.
46    #[cfg_attr(feature = "console", arg(long))]
47    pub entry_id: Option<u64>,
48}
49
50/// Local query command in fixture Wire field order.
51#[derive(Debug, serde::Deserialize, serde::Serialize)]
52pub struct QueryRequest {
53    /// Selected entity.
54    pub entity: String,
55    /// Encoded continuation.
56    pub cursor: Option<Vec<u8>>,
57    /// Maximum rows per page.
58    pub limit: u32,
59    /// Restrictions on fixture entity fields.
60    pub entity_filters: EntityFilters,
61    /// Ordered field specifications.
62    pub order: Vec<String>,
63    /// Reverse traversal.
64    pub descending: bool,
65    /// Candidate budget.
66    pub work: u32,
67    /// Output byte budget.
68    pub bytes: u32,
69    /// Selected output.
70    pub select: String,
71    /// Grouping and predicates.
72    pub options: QueryOptions,
73}
74
75/// Options carried together by the query endpoint.
76#[derive(Debug, serde::Deserialize, serde::Serialize)]
77pub struct QueryOptions {
78    /// Request distinct output.
79    pub distinct: bool,
80    /// Lower and upper group bounds.
81    pub group_bounds: (Option<String>, Option<String>),
82    /// Group ordering.
83    pub group_order: Option<String>,
84    /// Row predicates.
85    pub filters: RowFilters,
86}
87
88/// Local fixture status.
89#[derive(Debug, serde::Deserialize, serde::Serialize)]
90pub struct Status {
91    /// Schema fingerprint.
92    pub schema: [u8; 32],
93    /// Store incarnation.
94    pub incarnation: [u8; 16],
95    /// Entry revision.
96    pub revision: u64,
97    /// Wasm linear memory pages.
98    pub pages: u64,
99}
100
101/// Local schema inspection reply.
102#[derive(Debug, serde::Deserialize, serde::Serialize)]
103pub struct SchemaResponse {
104    /// Fixture status.
105    pub status: Status,
106    /// Matching entities.
107    pub entities: Vec<EntityView>,
108    /// Named value types.
109    pub types: Vec<TypeView>,
110}
111
112/// Inspected entity.
113#[derive(Debug, serde::Deserialize, serde::Serialize)]
114pub struct EntityView {
115    /// Entity name.
116    pub name: String,
117    /// Schema entity identifier.
118    pub id: u32,
119    /// Primary key field.
120    pub primary: String,
121    /// Stored fields.
122    pub fields: Vec<FieldView>,
123    /// Declared indexes.
124    pub indexes: Vec<IndexView>,
125}
126
127/// Inspected entity field.
128#[derive(Debug, serde::Deserialize, serde::Serialize)]
129pub struct FieldView {
130    /// Field name.
131    pub name: String,
132    /// Field type.
133    pub kind: String,
134    /// Optionality.
135    pub optional: bool,
136    /// Constraints and metadata.
137    pub info: String,
138    /// Reference target and index.
139    pub reference: Option<(String, String)>,
140}
141
142///
143/// IndexView
144/// An index in the inspected schema.
145///
146#[derive(Debug, serde::Deserialize, serde::Serialize)]
147pub struct IndexView {
148    /// Index name.
149    pub name: String,
150    /// Component fields in index order.
151    pub fields: Vec<String>,
152    /// Whether the key must be unique.
153    pub unique: bool,
154    /// Whether rows with absent components are excluded.
155    pub present_only: bool,
156}
157
158///
159/// TypeView
160/// A named type in the inspected schema.
161///
162#[derive(Debug, serde::Deserialize, serde::Serialize)]
163pub struct TypeView {
164    /// Schema name.
165    pub name: String,
166    /// Type category.
167    pub kind: String,
168    /// Declared fields, variants or collection roles.
169    pub members: Vec<TypeMemberView>,
170}
171
172///
173/// TypeMemberView
174/// One member of a named schema type.
175///
176#[derive(Debug, serde::Deserialize, serde::Serialize)]
177pub struct TypeMemberView {
178    /// Member name.
179    pub name: String,
180    /// Member type.
181    #[serde(rename = "type")]
182    pub kind: String,
183    /// Whether the member permits absence.
184    pub optional: bool,
185    /// Constraints and metadata.
186    pub info: String,
187}
188
189/// Row predicates carried by the local query and retained-aggregate commands.
190#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
191pub struct RowFilters {
192    /// Lower bound, upper bound, prefix, suffix and substring on BinaryObject.payload.
193    pub payload: PayloadFilters,
194    /// Left field, comparison, right field.
195    pub compare: Option<[String; 3]>,
196    /// Field, comparison and length threshold.
197    pub length: Option<(String, String, u32)>,
198    /// Require a value in this optional field.
199    pub present: Option<String>,
200    /// Require absence in this optional field.
201    pub absent: Option<String>,
202    /// Field, comparison and exact UTF-8 literal.
203    pub text: Option<[String; 3]>,
204    /// Field and Boolean equality operand.
205    pub boolean: Option<(String, bool)>,
206    /// Field, inclusive lower field and inclusive upper field.
207    pub between_fields: Option<[String; 3]>,
208    /// Field, lower field and upper field for the strict outside-range comparison.
209    pub not_between_fields: Option<[String; 3]>,
210}
211
212/// Selection shared by the private retained fixture when starting and resuming a job.
213#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
214pub struct RetainedSelection {
215    /// Entity name.
216    pub entity: String,
217    /// Aggregate selection.
218    pub select: String,
219    /// Minimum, category and entry ID restrictions.
220    pub entity_filters: EntityFilters,
221    /// Maximum output groups.
222    pub limit: u32,
223    /// Inclusive lower and upper group bounds.
224    pub group_bounds: (Option<String>, Option<String>),
225    /// Completed-group order.
226    pub group_order: Option<String>,
227    /// Row predicates.
228    pub filters: RowFilters,
229    /// Input fields and overall descending flag.
230    pub order: (Vec<String>, bool),
231}
232
233/// One bounded step of a retained fixture query.
234#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
235pub struct RetainedResume {
236    /// Original query.
237    pub selection: RetainedSelection,
238    /// Retained job handle.
239    pub handle: Vec<u8>,
240    /// Last saved step.
241    pub sequence: u64,
242    /// Input work allowance.
243    pub work: u32,
244    /// Output byte allowance.
245    pub bytes: u32,
246    /// Maximum results per page.
247    pub page_size: u32,
248    /// Previous result cursor.
249    pub after: Option<Vec<u8>>,
250}
251
252/// Display columns, rows and continuation shared by ordinary and retained results.
253#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
254pub struct DisplayPage {
255    /// Display column names.
256    pub columns: Vec<String>,
257    /// Display cells in column order.
258    pub rows: Vec<Vec<String>>,
259    /// Encoded continuation for a paged read.
260    pub next: Option<Vec<u8>>,
261}
262
263/// Progress reported by the local fixture after one retained query step.
264#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
265pub struct RetainedProgress {
266    /// Last saved step.
267    pub sequence: u64,
268    /// Candidates examined so far.
269    pub examined: u64,
270    /// Input bytes examined so far.
271    pub input_bytes: u64,
272    /// Encoded result bytes in this step.
273    pub output_bytes: u64,
274    /// Current phase and any completed result.
275    pub phase: RetainedPhase,
276}
277
278/// Only a completed job has output.
279#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
280pub enum RetainedPhase {
281    /// Additional input remains.
282    Running,
283    /// Completed rows and continuation.
284    Complete(DisplayPage),
285    /// Source rows changed.
286    Invalidated,
287    /// Job lifetime elapsed.
288    Expired,
289}
290
291impl RetainedPhase {
292    /// Name used by console progress messages.
293    #[must_use]
294    pub const fn label(&self) -> &'static str {
295        match self {
296            Self::Running => "Running",
297            Self::Complete(_) => "Complete",
298            Self::Invalidated => "Invalidated",
299            Self::Expired => "Expired",
300        }
301    }
302}
303
304/// Render bytes using two lowercase hexadecimal digits per byte and the supplied display prefix.
305#[must_use]
306pub fn lowercase_hex(bytes: &[u8], prefix: &str) -> String {
307    const DIGITS: &[u8; 16] = b"0123456789abcdef";
308    let mut output = String::with_capacity(prefix.len() + bytes.len() * 2);
309    output.push_str(prefix);
310    for &byte in bytes {
311        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
312        output.push(char::from(DIGITS[usize::from(byte & 15)]));
313    }
314    output
315}