surrealdb_sql/ident.rs
1use std::fmt::{self, Display};
2
3use common::fmt::EscapeKwFreeIdent;
4use surrealdb_strand::Strand;
5use surrealdb_types::{SqlFormat, ToSql};
6
7/// A single identifier naming a definition, as it appears in the syntax tree.
8///
9/// This is the form that renders: [`ToSql`] quotes the name whenever emitting
10/// it bare would read back as something else, so a definition's name survives
11/// being rendered and re-parsed. Statements hold this rather than a `String`
12/// or a [`Strand`] because both of those render their contents verbatim, which
13/// makes an unquoted name the silent default and a round-trip failure the
14/// result.
15///
16/// Escaping is decided here, once, so a statement can interpolate the name
17/// directly and be correct. A statement that reaches for an escaper itself is
18/// choosing a different rule than every other definition name.
19///
20/// Every position this appears in is introduced by a sigil or a path separator
21/// (`$name`, `mod::name`, `ml::name`), so a reserved word is unambiguous there
22/// and is emitted bare. A name in a position where it could instead be read as
23/// a keyword needs [`crate::TableName`]'s stricter rule, not this one.
24///
25/// This is for names that are a single identifier. It is not the right type for
26/// a `::`-separated path such as a function name, whose segments are escaped
27/// individually, and not for a name that may be computed at runtime, which is
28/// an `Expr`.
29#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
30#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
31#[repr(transparent)]
32pub struct Ident(Strand);
33
34impl Ident {
35 pub fn new(s: impl Into<Strand>) -> Ident {
36 Ident(s.into())
37 }
38
39 pub fn as_str(&self) -> &str {
40 self.0.as_str()
41 }
42
43 pub fn into_string(self) -> String {
44 self.0.into()
45 }
46}
47
48impl From<String> for Ident {
49 fn from(value: String) -> Self {
50 Ident(value.into())
51 }
52}
53
54impl From<&str> for Ident {
55 fn from(value: &str) -> Self {
56 Ident(value.into())
57 }
58}
59
60impl From<Strand> for Ident {
61 fn from(value: Strand) -> Self {
62 Ident(value)
63 }
64}
65
66impl From<Ident> for String {
67 fn from(value: Ident) -> Self {
68 value.0.into()
69 }
70}
71
72impl From<Ident> for Strand {
73 fn from(value: Ident) -> Self {
74 value.0
75 }
76}
77
78/// Renders the name unescaped. Use [`ToSql`] to produce SurrealQL.
79impl Display for Ident {
80 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81 Display::fmt(&self.0, f)
82 }
83}
84
85impl ToSql for Ident {
86 fn fmt_sql(&self, f: &mut String, sql_fmt: SqlFormat) {
87 EscapeKwFreeIdent(self.as_str()).fmt_sql(f, sql_fmt);
88 }
89}