|
| 1 | +use crate::decode::Decode; |
| 2 | +use crate::encode::{Encode, IsNull}; |
| 3 | +use crate::error::BoxDynError; |
| 4 | +use crate::postgres::{ |
| 5 | + PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres, |
| 6 | +}; |
| 7 | +use crate::types::Type; |
| 8 | +use std::fmt::{self, Display, Formatter}; |
| 9 | +use std::io::Write; |
| 10 | +use std::ops::Deref; |
| 11 | +use std::str::FromStr; |
| 12 | + |
| 13 | +/// Represents ltree specific errors |
| 14 | +#[derive(Debug, thiserror::Error)] |
| 15 | +#[non_exhaustive] |
| 16 | +pub enum PgLTreeParseError { |
| 17 | + /// LTree labels can only contain [A-Za-z0-9_] |
| 18 | + #[error("ltree label cotains invalid characters")] |
| 19 | + InvalidLtreeLabel, |
| 20 | + |
| 21 | + /// LTree version not supported |
| 22 | + #[error("ltree version not supported")] |
| 23 | + InvalidLtreeVersion, |
| 24 | +} |
| 25 | + |
| 26 | +/// Container for a Label Tree (`ltree`) in Postgres. |
| 27 | +/// |
| 28 | +/// See https://www.postgresql.org/docs/current/ltree.html |
| 29 | +/// |
| 30 | +/// ### Note: Requires Postgres 13+ |
| 31 | +/// |
| 32 | +/// This integration requires that the `ltree` type support the binary format in the Postgres |
| 33 | +/// wire protocol, which only became available in Postgres 13. |
| 34 | +/// ([Postgres 13.0 Release Notes, Additional Modules][https://www.postgresql.org/docs/13/release-13.html#id-1.11.6.11.5.14]) |
| 35 | +/// |
| 36 | +/// Ideally, SQLx's Postgres driver should support falling back to text format for types |
| 37 | +/// which don't have `typsend` and `typrecv` entries in `pg_type`, but that work still needs |
| 38 | +/// to be done. |
| 39 | +/// |
| 40 | +/// ### Note: Extension Required |
| 41 | +/// The `ltree` extension is not enabled by default in Postgres. You will need to do so explicitly: |
| 42 | +/// |
| 43 | +/// ```ignore |
| 44 | +/// CREATE EXTENSION IF NOT EXISTS "ltree"; |
| 45 | +/// ``` |
| 46 | +#[derive(Clone, Debug, Default, PartialEq)] |
| 47 | +pub struct PgLTree { |
| 48 | + labels: Vec<String>, |
| 49 | +} |
| 50 | + |
| 51 | +impl PgLTree { |
| 52 | + /// creates default/empty ltree |
| 53 | + pub fn new() -> Self { |
| 54 | + Self::default() |
| 55 | + } |
| 56 | + |
| 57 | + /// creates ltree from a [Vec<String>] without checking labels |
| 58 | + pub fn new_unchecked(labels: Vec<String>) -> Self { |
| 59 | + Self { labels } |
| 60 | + } |
| 61 | + |
| 62 | + /// creates ltree from an iterator with checking labels |
| 63 | + pub fn from_iter<I, S>(labels: I) -> Result<Self, PgLTreeParseError> |
| 64 | + where |
| 65 | + S: Into<String>, |
| 66 | + I: IntoIterator<Item = S>, |
| 67 | + { |
| 68 | + let mut ltree = Self::default(); |
| 69 | + for label in labels { |
| 70 | + ltree.push(label.into())?; |
| 71 | + } |
| 72 | + Ok(ltree) |
| 73 | + } |
| 74 | + |
| 75 | + /// push a label to ltree |
| 76 | + pub fn push(&mut self, label: String) -> Result<(), PgLTreeParseError> { |
| 77 | + if label.len() <= 256 |
| 78 | + && label |
| 79 | + .bytes() |
| 80 | + .all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit() || c == b'_') |
| 81 | + { |
| 82 | + self.labels.push(label); |
| 83 | + Ok(()) |
| 84 | + } else { |
| 85 | + Err(PgLTreeParseError::InvalidLtreeLabel) |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /// pop a label from ltree |
| 90 | + pub fn pop(&mut self) -> Option<String> { |
| 91 | + self.labels.pop() |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +impl IntoIterator for PgLTree { |
| 96 | + type Item = String; |
| 97 | + type IntoIter = std::vec::IntoIter<Self::Item>; |
| 98 | + |
| 99 | + fn into_iter(self) -> Self::IntoIter { |
| 100 | + self.labels.into_iter() |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +impl FromStr for PgLTree { |
| 105 | + type Err = PgLTreeParseError; |
| 106 | + |
| 107 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 108 | + Ok(Self { |
| 109 | + labels: s.split('.').map(|s| s.to_owned()).collect(), |
| 110 | + }) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +impl Display for PgLTree { |
| 115 | + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 116 | + let mut iter = self.labels.iter(); |
| 117 | + if let Some(label) = iter.next() { |
| 118 | + write!(f, "{}", label)?; |
| 119 | + for label in iter { |
| 120 | + write!(f, ".{}", label)?; |
| 121 | + } |
| 122 | + } |
| 123 | + Ok(()) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl Deref for PgLTree { |
| 128 | + type Target = [String]; |
| 129 | + |
| 130 | + fn deref(&self) -> &Self::Target { |
| 131 | + &self.labels |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +impl Type<Postgres> for PgLTree { |
| 136 | + fn type_info() -> PgTypeInfo { |
| 137 | + // Since `ltree` is enabled by an extension, it does not have a stable OID. |
| 138 | + PgTypeInfo::with_name("ltree") |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +impl PgHasArrayType for PgLTree { |
| 143 | + fn array_type_info() -> PgTypeInfo { |
| 144 | + PgTypeInfo::with_name("_ltree") |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +impl Encode<'_, Postgres> for PgLTree { |
| 149 | + fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull { |
| 150 | + buf.extend(1i8.to_le_bytes()); |
| 151 | + write!(buf, "{}", self) |
| 152 | + .expect("Display implementation panicked while writing to PgArgumentBuffer"); |
| 153 | + |
| 154 | + IsNull::No |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +impl<'r> Decode<'r, Postgres> for PgLTree { |
| 159 | + fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> { |
| 160 | + match value.format() { |
| 161 | + PgValueFormat::Binary => { |
| 162 | + let bytes = value.as_bytes()?; |
| 163 | + let version = i8::from_le_bytes([bytes[0]; 1]); |
| 164 | + if version != 1 { |
| 165 | + return Err(Box::new(PgLTreeParseError::InvalidLtreeVersion)); |
| 166 | + } |
| 167 | + Ok(Self::from_str(std::str::from_utf8(&bytes[1..])?)?) |
| 168 | + } |
| 169 | + PgValueFormat::Text => Ok(Self::from_str(value.as_str()?)?), |
| 170 | + } |
| 171 | + } |
| 172 | +} |
0 commit comments