quack-rs 0.16.0

Production-grade Rust SDK for building DuckDB loadable extensions
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. <https://github.com/tomtom215/>
// My way of giving something small back to the open source community
// and encouraging more Rust development!

//! Semantic versioning validation for `DuckDB` community extensions.
//!
//! Extensions submitted to the `DuckDB` community repository must use
//! valid semantic versioning for the `extension.version` field.
//!
//! # `DuckDB` Extension Versioning Scheme
//!
//! `DuckDB` core extensions use a three-tier versioning scheme:
//!
//! | Level | Format | Example | Meaning |
//! |-------|--------|---------|---------|
//! | **Unstable** | Short git hash | `690bfc5` | No stability guarantees |
//! | **Pre-release** | `0.y.z` | `0.1.0` | Working toward stability, semver applies |
//! | **Stable** | `x.y.z` (x>0) | `1.0.0` | Full semver, backwards-compatible API |
//!
//! Use [`classify_extension_version`] to determine which tier a version falls into,
//! or [`validate_extension_version`] to accept both semver and git-hash formats.
//!
//! # Reference
//!
//! - <https://semver.org/>
//! - <https://duckdb.org/docs/extensions/versioning>

use crate::error::ExtensionError;

/// Validates that a version string is valid semantic versioning.
///
/// Accepts versions in the form `MAJOR.MINOR.PATCH` with optional
/// pre-release (`-alpha.1`) and build metadata (`+build.123`) suffixes.
///
/// # Rules
///
/// - Must have exactly three numeric components separated by dots
/// - Components must not have leading zeros (except `0` itself)
/// - Pre-release identifiers are alphanumeric with dots/hyphens
/// - Build metadata follows a `+` and is alphanumeric with dots/hyphens
///
/// # Errors
///
/// Returns `ExtensionError` if the version is not valid semver.
///
/// # Example
///
/// ```rust
/// use quack_rs::validate::validate_semver;
///
/// assert!(validate_semver("1.0.0").is_ok());
/// assert!(validate_semver("0.1.0").is_ok());
/// assert!(validate_semver("1.2.3-alpha.1").is_ok());
/// assert!(validate_semver("1.2.3+build.456").is_ok());
/// assert!(validate_semver("1.2.3-rc.1+build.456").is_ok());
/// assert!(validate_semver("1.2").is_err());
/// assert!(validate_semver("v1.0.0").is_err());
/// assert!(validate_semver("01.0.0").is_err());
/// ```
pub fn validate_semver(version: &str) -> Result<(), ExtensionError> {
    if version.is_empty() {
        return Err(ExtensionError::new("version must not be empty"));
    }

    // Split off build metadata first (after +)
    let (version_pre, _build) = match version.split_once('+') {
        Some((v, b)) => {
            validate_identifiers(b, "build metadata")?;
            (v, Some(b))
        }
        None => (version, None),
    };

    // Split off pre-release (after -)
    let (core, _pre) = match version_pre.split_once('-') {
        Some((c, p)) => {
            validate_identifiers(p, "pre-release")?;
            (c, Some(p))
        }
        None => (version_pre, None),
    };

    // Parse core version: MAJOR.MINOR.PATCH
    let parts: Vec<&str> = core.split('.').collect();
    if parts.len() != 3 {
        return Err(ExtensionError::new(format!(
            "version '{version}' must have exactly three components (MAJOR.MINOR.PATCH), got {}",
            parts.len()
        )));
    }

    for (i, &part) in parts.iter().enumerate() {
        let label = ["major", "minor", "patch"][i];
        validate_numeric_component(part, label, version)?;
    }

    Ok(())
}

/// The stability level of a `DuckDB` extension version.
///
/// `DuckDB` core extensions use three tiers of stability, each with different
/// expectations for API stability, release cadence, and semver semantics.
///
/// # Reference
///
/// See the [`DuckDB` extension versioning docs](https://duckdb.org/docs/extensions/versioning)
/// for the full specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExtensionStability {
    /// Version is a short git hash (e.g., `690bfc5`).
    ///
    /// No stability guarantees. Functionality may change or be removed
    /// completely with every release. No structured release cycle.
    Unstable,
    /// Version is semver `0.y.z` (e.g., `0.1.0`).
    ///
    /// Working toward stability. Semver semantics apply, but the API is
    /// not yet considered stable. Breaking changes may occur in minor versions.
    PreRelease,
    /// Version is semver `x.y.z` where `x > 0` (e.g., `1.0.0`).
    ///
    /// Full semver semantics apply. The API is stable and will only change
    /// in backwards-incompatible ways when the major version is bumped.
    Stable,
}

impl std::fmt::Display for ExtensionStability {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unstable => f.write_str("unstable"),
            Self::PreRelease => f.write_str("pre-release"),
            Self::Stable => f.write_str("stable"),
        }
    }
}

/// Classifies an extension version into its stability level.
///
/// This follows the `DuckDB` core extension versioning scheme:
/// - **Unstable**: a short git hash (7+ lowercase hex characters)
/// - **Pre-release**: semver `0.y.z`
/// - **Stable**: semver `x.y.z` where `x > 0`
///
/// # Errors
///
/// Returns `ExtensionError` if the version string is empty or does not match
/// any recognized format.
///
/// # Example
///
/// ```rust
/// use quack_rs::validate::semver::{classify_extension_version, ExtensionStability};
///
/// let (stability, _) = classify_extension_version("1.0.0").unwrap();
/// assert_eq!(stability, ExtensionStability::Stable);
///
/// let (stability, _) = classify_extension_version("0.1.0").unwrap();
/// assert_eq!(stability, ExtensionStability::PreRelease);
///
/// let (stability, _) = classify_extension_version("690bfc5").unwrap();
/// assert_eq!(stability, ExtensionStability::Unstable);
/// ```
pub fn classify_extension_version(
    version: &str,
) -> Result<(ExtensionStability, &str), ExtensionError> {
    if version.is_empty() {
        return Err(ExtensionError::new("extension version must not be empty"));
    }

    // Try semver first
    if version.contains('.') {
        validate_semver(version)?;
        let major = version.split('.').next().unwrap_or("0");
        let stability = if major == "0" {
            ExtensionStability::PreRelease
        } else {
            ExtensionStability::Stable
        };
        return Ok((stability, version));
    }

    // Try git hash: 7+ lowercase hex characters
    if version.len() >= 7
        && version.len() <= 40
        && version
            .bytes()
            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
    {
        return Ok((ExtensionStability::Unstable, version));
    }

    Err(ExtensionError::new(format!(
        "extension version '{version}' is not a valid semver version or git hash; \
         expected MAJOR.MINOR.PATCH or a 7-40 character lowercase hex hash"
    )))
}

/// Maximum length of an extension version string.
///
/// Not a `DuckDB` rule — a sanity bound, comfortably above the 40-character git
/// hash that is the longest form anyone actually uses.
const MAX_VERSION_LEN: usize = 64;

/// Validates an extension version string for a community-extension
/// `description.yml`.
///
/// **This is deliberately permissive.** `DuckDB`'s community-extension
/// documentation specifies no version format — it says only that the descriptor
/// carries "the version of the extension" and points at existing extensions as
/// examples. Of 43 published extensions sampled, 11 use a date-based build id
/// (`2025120401`) that is neither semver nor a git hash. Rejecting those would
/// mean this validator tells most real extensions they are invalid.
///
/// So this checks only what would actually break: an empty version, one longer
/// than 64 characters, or one containing anything outside
/// `[A-Za-z0-9._+-]` — whitespace, path separators and control characters, all
/// of which would corrupt the metadata the version ends up in.
///
/// Use [`classify_extension_version`] when you want `DuckDB`'s three-tier
/// stability scheme, which *is* documented and *is* strict.
///
/// # Errors
///
/// Returns `ExtensionError` if the version is empty, too long, or contains a
/// character outside the allowed set.
///
/// # Example
///
/// ```rust
/// use quack_rs::validate::validate_extension_version;
///
/// assert!(validate_extension_version("1.0.0").is_ok());
/// assert!(validate_extension_version("0.1.0").is_ok());
/// assert!(validate_extension_version("690bfc5").is_ok());
/// // Used by 11 of 43 published community extensions.
/// assert!(validate_extension_version("2025120401").is_ok());
///
/// assert!(validate_extension_version("").is_err());
/// assert!(validate_extension_version("1.0.0 beta").is_err()); // whitespace
/// assert!(validate_extension_version("../etc/passwd").is_err()); // path separator
/// ```
pub fn validate_extension_version(version: &str) -> Result<(), ExtensionError> {
    if version.is_empty() {
        return Err(ExtensionError::new("extension version must not be empty"));
    }
    if version.len() > MAX_VERSION_LEN {
        return Err(ExtensionError::new(format!(
            "extension version is {} characters; the maximum is {MAX_VERSION_LEN}",
            version.len()
        )));
    }
    if let Some(bad) = version
        .chars()
        .find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-')))
    {
        return Err(ExtensionError::new(format!(
            "extension version '{version}' contains {bad:?}; only ASCII letters, \
             digits, '.', '_', '+' and '-' are allowed"
        )));
    }
    Ok(())
}

/// Validates a single numeric version component (no leading zeros).
fn validate_numeric_component(
    s: &str,
    label: &str,
    full_version: &str,
) -> Result<(), ExtensionError> {
    if s.is_empty() {
        return Err(ExtensionError::new(format!(
            "version '{full_version}': {label} component is empty"
        )));
    }

    if !s.bytes().all(|b| b.is_ascii_digit()) {
        return Err(ExtensionError::new(format!(
            "version '{full_version}': {label} component '{s}' is not a valid number"
        )));
    }

    // No leading zeros (except "0" itself)
    if s.len() > 1 && s.starts_with('0') {
        return Err(ExtensionError::new(format!(
            "version '{full_version}': {label} component '{s}' has a leading zero"
        )));
    }

    Ok(())
}

/// Validates dot-separated identifiers (pre-release or build metadata).
fn validate_identifiers(s: &str, label: &str) -> Result<(), ExtensionError> {
    if s.is_empty() {
        return Err(ExtensionError::new(format!(
            "{label} identifier must not be empty"
        )));
    }

    for ident in s.split('.') {
        if ident.is_empty() {
            return Err(ExtensionError::new(format!(
                "{label} contains an empty identifier"
            )));
        }
        if !ident
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-')
        {
            return Err(ExtensionError::new(format!(
                "{label} identifier '{ident}' contains invalid characters"
            )));
        }
    }

    Ok(())
}

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

    #[test]
    fn valid_simple() {
        assert!(validate_semver("1.0.0").is_ok());
        assert!(validate_semver("0.1.0").is_ok());
        assert!(validate_semver("0.0.1").is_ok());
        assert!(validate_semver("123.456.789").is_ok());
    }

    #[test]
    fn valid_prerelease() {
        assert!(validate_semver("1.0.0-alpha").is_ok());
        assert!(validate_semver("1.0.0-alpha.1").is_ok());
        assert!(validate_semver("1.0.0-0.3.7").is_ok());
        assert!(validate_semver("1.0.0-x.7.z.92").is_ok());
        assert!(validate_semver("1.0.0-rc-1").is_ok());
    }

    #[test]
    fn valid_build_metadata() {
        assert!(validate_semver("1.0.0+build").is_ok());
        assert!(validate_semver("1.0.0+build.456").is_ok());
        assert!(validate_semver("1.0.0+20130313144700").is_ok());
    }

    #[test]
    fn valid_prerelease_and_build() {
        assert!(validate_semver("1.0.0-alpha+001").is_ok());
        assert!(validate_semver("1.0.0-rc.1+build.456").is_ok());
    }

    #[test]
    fn empty_rejected() {
        assert!(validate_semver("").is_err());
    }

    #[test]
    fn two_components_rejected() {
        let err = validate_semver("1.2").unwrap_err();
        assert!(err.as_str().contains("three components"));
    }

    #[test]
    fn four_components_rejected() {
        let err = validate_semver("1.2.3.4").unwrap_err();
        assert!(err.as_str().contains("three components"));
    }

    #[test]
    fn leading_v_rejected() {
        let err = validate_semver("v1.0.0").unwrap_err();
        assert!(err.as_str().contains("not a valid number"));
    }

    #[test]
    fn leading_zero_rejected() {
        assert!(validate_semver("01.0.0").is_err());
        assert!(validate_semver("1.01.0").is_err());
        assert!(validate_semver("1.0.01").is_err());
    }

    #[test]
    fn leading_zero_on_zero_itself_accepted() {
        assert!(validate_semver("0.0.0").is_ok());
    }

    #[test]
    fn non_numeric_rejected() {
        assert!(validate_semver("a.b.c").is_err());
        assert!(validate_semver("1.0.x").is_err());
    }

    #[test]
    fn empty_component_rejected() {
        assert!(validate_semver("1..0").is_err());
        assert!(validate_semver(".1.0").is_err());
    }

    #[test]
    fn single_number_rejected() {
        assert!(validate_semver("1").is_err());
    }

    // --- Extension version classification tests ---

    #[test]
    fn classify_stable() {
        let (stability, _) = classify_extension_version("1.0.0").unwrap();
        assert_eq!(stability, ExtensionStability::Stable);
    }

    #[test]
    fn classify_stable_high_major() {
        let (stability, _) = classify_extension_version("13.11.0").unwrap();
        assert_eq!(stability, ExtensionStability::Stable);
    }

    #[test]
    fn classify_pre_release() {
        let (stability, _) = classify_extension_version("0.1.0").unwrap();
        assert_eq!(stability, ExtensionStability::PreRelease);
    }

    #[test]
    fn classify_pre_release_with_suffix() {
        let (stability, _) = classify_extension_version("0.1.0-alpha.1").unwrap();
        assert_eq!(stability, ExtensionStability::PreRelease);
    }

    #[test]
    fn classify_unstable_git_hash() {
        let (stability, _) = classify_extension_version("690bfc5").unwrap();
        assert_eq!(stability, ExtensionStability::Unstable);
    }

    #[test]
    fn classify_unstable_long_hash() {
        let (stability, _) =
            classify_extension_version("d9e5cc104c61e4a2b3f8a9c7d1e5f0a2b4c6d8e0").unwrap();
        assert_eq!(stability, ExtensionStability::Unstable);
    }

    #[test]
    fn classify_empty_rejected() {
        assert!(classify_extension_version("").is_err());
    }

    #[test]
    fn classify_uppercase_hash_rejected() {
        assert!(classify_extension_version("690BFC5").is_err());
    }

    #[test]
    fn classify_too_short_hash_rejected() {
        assert!(classify_extension_version("abc12").is_err());
    }

    #[test]
    fn classify_not_hex_rejected() {
        assert!(classify_extension_version("not-valid").is_err());
    }

    #[test]
    fn validate_extension_version_semver() {
        assert!(validate_extension_version("1.0.0").is_ok());
        assert!(validate_extension_version("0.1.0").is_ok());
    }

    #[test]
    fn validate_extension_version_hash() {
        assert!(validate_extension_version("690bfc5").is_ok());
    }

    #[test]
    fn validate_extension_version_invalid() {
        assert!(validate_extension_version("").is_err());
        assert!(
            validate_extension_version("1.0.0 beta").is_err(),
            "whitespace"
        );
        assert!(
            validate_extension_version("../etc/passwd").is_err(),
            "path separator"
        );
        assert!(
            validate_extension_version("v1.0.0\n").is_err(),
            "control character"
        );
        assert!(
            validate_extension_version(&"a".repeat(65)).is_err(),
            "too long"
        );
    }

    #[test]
    fn validate_extension_version_accepts_what_duckdb_accepts() {
        // DuckDB's community-extension docs specify no version format. These
        // are all in use by published extensions, and rejecting them would make
        // the validator wrong about most of the ecosystem.
        for version in [
            "1.0.0",
            "0.1.0",
            "690bfc5",
            "2025120401", // 11 of 43 sampled extensions
            "0.1.0-alpha+build.1",
            "v2.6.1",
            &"a".repeat(64),
        ] {
            assert!(
                validate_extension_version(version).is_ok(),
                "{version} should be accepted"
            );
        }
    }

    #[test]
    fn stability_display() {
        assert_eq!(ExtensionStability::Unstable.to_string(), "unstable");
        assert_eq!(ExtensionStability::PreRelease.to_string(), "pre-release");
        assert_eq!(ExtensionStability::Stable.to_string(), "stable");
    }
}