use super::expr::Expr;
use super::query::{Op, WhereExpr};
use super::SqlValue;
#[must_use]
pub fn aliased(alias: &'static str, column: &'static str) -> Expr {
Expr::AliasedColumn { alias, column }
}
const MAX_LABEL: usize = 63;
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct JoinedLabel {
buf: [u8; MAX_LABEL],
len: usize,
}
impl JoinedLabel {
const EMPTY: Self = Self {
buf: [0; MAX_LABEL],
len: 0,
};
fn push(&mut self, part: &str) {
let end = self.len + part.len();
self.buf[self.len..end].copy_from_slice(part.as_bytes());
self.len = end;
}
#[must_use]
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.buf[..self.len]).unwrap_or_default()
}
}
impl std::ops::Deref for JoinedLabel {
type Target = str;
fn deref(&self) -> &str {
self.as_str()
}
}
impl std::fmt::Display for JoinedLabel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::fmt::Debug for JoinedLabel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_str(), f)
}
}
impl PartialEq<&str> for JoinedLabel {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
#[doc(hidden)]
#[must_use]
pub fn joined_label(alias: &str, column: &str) -> JoinedLabel {
let mut label = JoinedLabel::EMPTY;
if alias.len() + 2 + column.len() <= MAX_LABEL {
label.push(alias);
label.push("__");
label.push(column);
} else {
label.push(&sql_label(&joined_key(alias, column)));
}
label
}
pub(crate) fn sql_label(name: &str) -> std::borrow::Cow<'_, str> {
const MAX: usize = MAX_LABEL;
if name.len() <= MAX {
return name.into();
}
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
});
let mut head = MAX - 17;
while !name.is_char_boundary(head) {
head -= 1;
}
format!("{}_{hash:016x}", &name[..head]).into()
}
pub(crate) fn joined_key(alias: &str, column: &str) -> String {
let mut out = String::with_capacity(alias.len() + 2 + column.len());
push_joined_key(&mut out, alias, column);
out
}
pub(crate) fn push_joined_key(out: &mut String, alias: &str, column: &str) {
out.push_str(alias);
out.push_str("__");
out.push_str(column);
}
#[must_use]
pub fn col_filter(
alias: &'static str,
column: &'static str,
op: Op,
value: impl Into<SqlValue>,
) -> WhereExpr {
WhereExpr::ExprCompare {
lhs: Expr::AliasedColumn { alias, column },
op,
rhs: Expr::Literal(value.into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn aliased_emits_aliased_column_variant() {
let e = aliased("comments", "post_id");
assert_eq!(
e,
Expr::AliasedColumn {
alias: "comments",
column: "post_id",
},
);
}
#[test]
fn long_joined_labels_fit_and_stay_distinct() {
assert_eq!(joined_label("author", "name"), "author__name");
let alias = "a".repeat(60);
let (x, y) = (
joined_label(&alias, "first"),
joined_label(&alias, "second"),
);
assert!(x.len() <= 63 && y.len() <= 63, "{x} {y}");
assert_ne!(x, y);
assert_eq!(x, joined_label(&alias, "first"));
}
#[test]
fn joined_label_matches_the_written_label() {
for (alias, column) in [
("author", "name"),
(&*"a".repeat(55), "abcdef"), (&*"a".repeat(55), "abcdefg"), (&*"é".repeat(30), "colonne"),
] {
let label = joined_label(alias, column);
assert_eq!(label.as_str(), sql_label(&joined_key(alias, column)));
}
}
#[test]
fn joined_label_is_inline() {
fn copy<T: Copy>(_: T) {}
copy(joined_label("author", "name"));
}
#[test]
fn col_filter_wraps_into_expr_compare_with_aliased_lhs() {
let w = col_filter("post", "status", Op::Eq, "draft");
match w {
WhereExpr::ExprCompare {
lhs: Expr::AliasedColumn { alias, column },
op,
rhs: Expr::Literal(SqlValue::String(s)),
} => {
assert_eq!(alias, "post");
assert_eq!(column, "status");
assert_eq!(op, Op::Eq);
assert_eq!(s, "draft");
}
_ => panic!("expected ExprCompare with aliased LHS + literal RHS, got {w:?}"),
}
}
}