saya-types 0.3.0

Shared types for SAYA CLI, the database-aware terminal AI agent.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use serde::{Deserialize, Serialize};

use crate::contract::error::ContractError;

pub const MAX_NAME_CHARS: usize = 128;

/// Opaque, validated profile identity: the literal prefix `p-` followed by 64 lowercase hex digits.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String")]
pub struct ProfileIdentity(String);

impl ProfileIdentity {
    pub fn parse(value: &str) -> Result<Self, ContractError> {
        if value.len() != 66 || !value.starts_with("p-") {
            return Err(ContractError::InvalidProfileIdentity);
        }
        if !value[2..]
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        {
            return Err(ContractError::InvalidProfileIdentity);
        }
        Ok(Self(value.to_owned()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for ProfileIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl TryFrom<String> for ProfileIdentity {
    type Error = ContractError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(&value)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DatabaseObjectKind {
    Table,
    View,
}

impl DatabaseObjectKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Table => "table",
            Self::View => "view",
        }
    }

    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "table" => Some(Self::Table),
            "view" => Some(Self::View),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct DatabaseObjectRef {
    profile: ProfileIdentity,
    catalog: String,
    schema: String,
    object: String,
    kind: DatabaseObjectKind,
}

impl DatabaseObjectRef {
    pub fn new(
        profile: ProfileIdentity,
        catalog: impl Into<String>,
        schema: impl Into<String>,
        object: impl Into<String>,
        kind: DatabaseObjectKind,
    ) -> Result<Self, ContractError> {
        let catalog = catalog.into();
        let schema = schema.into();
        let object = object.into();
        validate_name(&catalog)?;
        validate_name(&schema)?;
        validate_name(&object)?;
        Ok(Self {
            profile,
            catalog,
            schema,
            object,
            kind,
        })
    }

    pub fn profile(&self) -> &ProfileIdentity {
        &self.profile
    }

    pub fn catalog(&self) -> &str {
        &self.catalog
    }

    pub fn schema(&self) -> &str {
        &self.schema
    }

    pub fn object(&self) -> &str {
        &self.object
    }

    pub fn kind(&self) -> DatabaseObjectKind {
        self.kind
    }

    pub fn qualified_name(&self) -> String {
        format!("{}.{}.{}", self.catalog, self.schema, self.object)
    }
}

pub(crate) fn validate_name(value: &str) -> Result<(), ContractError> {
    if value.is_empty() {
        return Err(ContractError::EmptyName);
    }
    if value.chars().count() > MAX_NAME_CHARS {
        return Err(ContractError::NameTooLong);
    }
    if value.chars().any(|c| c.is_control()) {
        return Err(ContractError::ControlCharacter);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_valid_profile_identity() {
        let hex = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
        let input = format!("p-{hex}");
        let id = ProfileIdentity::parse(&input).unwrap();
        assert_eq!(id.as_str(), &input);
    }

    #[test]
    fn parse_rejects_too_short() {
        assert!(ProfileIdentity::parse("p-abc").is_err());
    }

    #[test]
    fn parse_rejects_too_long() {
        let hex = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789ff";
        assert!(ProfileIdentity::parse(&format!("p-{hex}")).is_err());
    }

    #[test]
    fn parse_rejects_missing_prefix() {
        let hex = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
        assert!(ProfileIdentity::parse(hex).is_err());
    }

    #[test]
    fn parse_rejects_uppercase_hex() {
        let hex = "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789";
        assert!(ProfileIdentity::parse(&format!("p-{hex}")).is_err());
    }

    #[test]
    fn parse_rejects_non_hex() {
        let hex = "gggggg0123456789gggggg0123456789gggggg0123456789gggggg0123456789";
        assert!(ProfileIdentity::parse(&format!("p-{hex}")).is_err());
    }

    #[test]
    fn display_delegates_to_as_str() {
        let hex = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
        let input = format!("p-{hex}");
        let id = ProfileIdentity::parse(&input).unwrap();
        assert_eq!(format!("{id}"), input);
    }

    #[test]
    fn serde_round_trip() {
        let hex = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
        let input = format!("p-{hex}");
        let id = ProfileIdentity::parse(&input).unwrap();
        let json = serde_json::to_string(&id).unwrap();
        let deserialized: ProfileIdentity = serde_json::from_str(&json).unwrap();
        assert_eq!(id, deserialized);
    }

    #[test]
    fn serde_rejects_invalid_string() {
        let result: Result<ProfileIdentity, _> = serde_json::from_str(r#""p-INVALID""#);
        assert!(result.is_err());
    }

    #[test]
    fn database_object_kind_as_str() {
        assert_eq!(DatabaseObjectKind::Table.as_str(), "table");
        assert_eq!(DatabaseObjectKind::View.as_str(), "view");
    }

    #[test]
    fn database_object_kind_parse() {
        assert_eq!(
            DatabaseObjectKind::parse("table"),
            Some(DatabaseObjectKind::Table)
        );
        assert_eq!(
            DatabaseObjectKind::parse("view"),
            Some(DatabaseObjectKind::View)
        );
        assert_eq!(DatabaseObjectKind::parse("unknown"), None);
    }

    #[test]
    fn database_object_ref_new_rejects_empty() {
        let profile = ProfileIdentity::parse(&format!("p-{}", "a".repeat(64))).unwrap();
        let kind = DatabaseObjectKind::Table;
        assert!(DatabaseObjectRef::new(profile.clone(), "", "sch", "obj", kind).is_err());
        assert!(DatabaseObjectRef::new(profile.clone(), "cat", "", "obj", kind).is_err());
        assert!(DatabaseObjectRef::new(profile, "cat", "sch", "", kind).is_err());
    }

    #[test]
    fn database_object_ref_new_rejects_too_long() {
        let profile = ProfileIdentity::parse(&format!("p-{}", "a".repeat(64))).unwrap();
        let long = "a".repeat(129);
        let kind = DatabaseObjectKind::Table;
        assert!(DatabaseObjectRef::new(profile.clone(), &long, "sch", "obj", kind).is_err());
        assert!(DatabaseObjectRef::new(profile.clone(), "cat", &long, "obj", kind).is_err());
        assert!(DatabaseObjectRef::new(profile, "cat", "sch", &long, kind).is_err());
    }

    #[test]
    fn database_object_ref_new_rejects_control_chars() {
        let profile = ProfileIdentity::parse(&format!("p-{}", "a".repeat(64))).unwrap();
        let kind = DatabaseObjectKind::Table;
        assert!(DatabaseObjectRef::new(profile.clone(), "cat\n", "sch", "obj", kind).is_err());
        assert!(DatabaseObjectRef::new(profile.clone(), "cat", "sch\u{0}", "obj", kind).is_err());
        assert!(DatabaseObjectRef::new(profile, "cat", "sch", "obj\r", kind).is_err());
    }

    #[test]
    fn database_object_ref_getters() {
        let profile = ProfileIdentity::parse(&format!("p-{}", "a".repeat(64))).unwrap();
        let r = DatabaseObjectRef::new(
            profile.clone(),
            "cat",
            "sch",
            "obj",
            DatabaseObjectKind::View,
        )
        .unwrap();
        assert_eq!(r.profile(), &profile);
        assert_eq!(r.catalog(), "cat");
        assert_eq!(r.schema(), "sch");
        assert_eq!(r.object(), "obj");
        assert_eq!(r.kind(), DatabaseObjectKind::View);
    }

    #[test]
    fn qualified_name_format() {
        let profile = ProfileIdentity::parse(&format!("p-{}", "a".repeat(64))).unwrap();
        let r = DatabaseObjectRef::new(profile, "cat", "sch", "obj", DatabaseObjectKind::Table)
            .unwrap();
        assert_eq!(r.qualified_name(), "cat.sch.obj");
    }

    #[test]
    fn cross_profile_isolation() {
        let hex_a = format!("p-{}", "a".repeat(64));
        let hex_b = format!("p-{}", "b".repeat(64));
        let profile_a = ProfileIdentity::parse(&hex_a).unwrap();
        let profile_b = ProfileIdentity::parse(&hex_b).unwrap();
        let ref_a =
            DatabaseObjectRef::new(profile_a, "cat", "sch", "obj", DatabaseObjectKind::Table)
                .unwrap();
        let ref_b =
            DatabaseObjectRef::new(profile_b, "cat", "sch", "obj", DatabaseObjectKind::Table)
                .unwrap();
        assert_ne!(ref_a, ref_b);
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(ref_a.clone());
        assert!(!set.contains(&ref_b));
    }
}

#[cfg(test)]
mod property_tests {
    //! Properties 3 & 4 (spec §1): object identity separates profiles, and name
    //! validation is total — `DatabaseObjectRef::new` returns a ref whose
    //! getters round-trip the input, or a typed error, and never panics. Pure.
    use super::*;
    use proptest::prelude::*;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    /// A valid profile identity: the `p-` prefix plus 64 lowercase hex digits.
    /// Two of these are distinct unless their hex strings are identical.
    fn profile_identity(hex: String) -> ProfileIdentity {
        let full = format!("p-{}", hex);
        ProfileIdentity::parse(&full).expect("valid hex profile identity")
    }

    /// 64 lowercase hex digits.
    fn hex64() -> impl Strategy<Value = String> {
        "[0-9a-f]{64}"
    }

    fn hash_of<T: Hash>(value: &T) -> u64 {
        let mut h = DefaultHasher::new();
        value.hash(&mut h);
        h.finish()
    }

    /// Any string a user might hand in as a catalog/schema/object name.
    fn name() -> impl Strategy<Value = String> {
        // Include empty, long, control chars, and unicode — every rejection
        // path must fire, and none may panic.
        prop::collection::vec(any::<char>(), 0..=140).prop_map(|chars| chars.into_iter().collect())
    }

    /// A kind strategy: `select` needs a `Vec` here, an array does not satisfy
    /// `Into<Cow<'static, [_]>>`.
    fn kind() -> impl Strategy<Value = DatabaseObjectKind> {
        prop::sample::select(vec![DatabaseObjectKind::Table, DatabaseObjectKind::View])
    }

    proptest! {
        /// Property 3 — for two distinct profile identities and the same
        /// qualified name, the two `DatabaseObjectRef`s are unequal and hash
        /// unequally, so a profile-scoped key set cannot alias them.
        #[test]
        fn object_identity_separates_profiles(
            hex_a in hex64(),
            hex_b in hex64(),
        ) {
            prop_assume!(hex_a != hex_b);
            let pa = profile_identity(hex_a);
            let pb = profile_identity(hex_b);

            let ref_a = DatabaseObjectRef::new(pa, "c", "s", "o", DatabaseObjectKind::Table)
                .expect("valid names");
            let ref_b = DatabaseObjectRef::new(pb, "c", "s", "o", DatabaseObjectKind::Table)
                .expect("valid names");
            // Compare by reference so the values are not moved before hashing.
            prop_assert_ne!(&ref_a, &ref_b);
            let ha = hash_of(&ref_a);
            let hb = hash_of(&ref_b);
            prop_assert_ne!(ha, hb);
        }

        /// Property 4 — `DatabaseObjectRef::new` is total: for any string in any
        /// of the three name slots, it returns Ok with getters that round-trip the
        /// exact input, or a typed error. Never panics.
        #[test]
        fn name_validation_is_total(
            catalog in name(),
            schema in name(),
            object in name(),
            kind in kind(),
        ) {
            let profile = profile_identity("a".repeat(64));
            let result = DatabaseObjectRef::new(profile, &catalog, &schema, &object, kind);
            match result {
                Ok(r) => {
                    // Round-trip: the getters return the exact input bytes.
                    prop_assert_eq!(r.catalog(), catalog.as_str());
                    prop_assert_eq!(r.schema(), schema.as_str());
                    prop_assert_eq!(r.object(), object.as_str());
                    prop_assert_eq!(r.kind(), kind);
                    // A ref that round-tripped cannot contain a control char in a
                    // name — validation would have rejected it.
                    for s in [r.catalog(), r.schema(), r.object()] {
                        prop_assert!(
                            !s.chars().any(|c| c.is_control()),
                            "control char survived validation: {s:?}"
                        );
                    }
                    // The qualified name is the three parts joined by `.`.
                    prop_assert_eq!(r.qualified_name(), format!("{catalog}.{schema}.{object}"));
                }
                Err(e) => {
                    // A typed error, and it must be one of the name errors.
                    prop_assert!(
                        matches!(
                            e,
                            ContractError::EmptyName
                                | ContractError::NameTooLong
                                | ContractError::ControlCharacter
                        ),
                        "unexpected error: {e:?}"
                    );
                }
            }
        }
    }
}