Skip to main content

datafusion_common/
alias.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::sync::atomic::{AtomicUsize, Ordering};
6
7/// A utility struct that can be used to generate unique aliases when optimizing queries
8#[derive(Debug)]
9pub struct AliasGenerator {
10    next_id: AtomicUsize,
11}
12
13impl Default for AliasGenerator {
14    fn default() -> Self {
15        Self {
16            next_id: AtomicUsize::new(1),
17        }
18    }
19}
20
21impl AliasGenerator {
22    /// Create a new [`AliasGenerator`]
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Advance the counter to at least `min_id`, ensuring future aliases
28    /// won't collide with already-existing ones.
29    ///
30    /// For example, if the query already contains an alias `alias_42`, then calling
31    /// `update_min_id(42)` will ensure that future aliases generated by this
32    /// [`AliasGenerator`] will start from `alias_43`.
33    pub fn update_min_id(&self, min_id: usize) {
34        self.next_id.fetch_max(min_id + 1, Ordering::Relaxed);
35    }
36
37    /// Return a unique alias with the provided prefix
38    pub fn next(&self, prefix: &str) -> String {
39        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
40        format!("{prefix}_{id}")
41    }
42}