Skip to content

Commit 9621c43

Browse files
authored
Support casting to bytea (#43)
Should close #42
1 parent 2f7965c commit 9621c43

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/lib.rs

+18
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,13 @@ fn ulid_to_uuid(input: ulid) -> Uuid {
110110
Uuid::from_bytes(bytes)
111111
}
112112

113+
#[pg_extern(immutable, parallel_safe)]
114+
fn ulid_to_bytea(input: ulid) -> Vec<u8> {
115+
let mut bytes = input.0.to_ne_bytes();
116+
bytes.reverse();
117+
bytes.to_vec()
118+
}
119+
113120
#[pg_extern(immutable, parallel_safe)]
114121
fn ulid_to_timestamp(input: ulid) -> Timestamp {
115122
let inner_seconds = (InnerUlid(input.0).timestamp_ms() as f64) / 1000.0;
@@ -135,6 +142,7 @@ extension_sql!(
135142
r#"
136143
CREATE CAST (uuid AS ulid) WITH FUNCTION ulid_from_uuid(uuid) AS IMPLICIT;
137144
CREATE CAST (ulid AS uuid) WITH FUNCTION ulid_to_uuid(ulid) AS IMPLICIT;
145+
CREATE CAST (ulid AS bytea) WITH FUNCTION ulid_to_bytea(ulid) AS IMPLICIT;
138146
CREATE CAST (ulid AS timestamp) WITH FUNCTION ulid_to_timestamp(ulid) AS IMPLICIT;
139147
CREATE CAST (timestamp AS ulid) WITH FUNCTION timestamp_to_ulid(timestamp) AS IMPLICIT;
140148
"#,
@@ -149,6 +157,9 @@ mod tests {
149157
const INT: u128 = 2029121117734015635515926905565997019;
150158
const TEXT: &str = "01GV5PA9EQG7D82Q3Y4PKBZSYV";
151159
const UUID: &str = "0186cb65-25d7-81da-815c-7e25a6bfe7db";
160+
const BYTEA: &[u8] = &[
161+
1, 134, 203, 101, 37, 215, 129, 218, 129, 92, 126, 37, 166, 191, 231, 219,
162+
];
152163
const TIMESTAMP: &str = "2023-03-10 12:00:49.111";
153164

154165
#[pg_test]
@@ -211,6 +222,13 @@ mod tests {
211222
assert_eq!(Some(UUID), result);
212223
}
213224

225+
#[pg_test]
226+
fn test_ulid_to_bytea() {
227+
let result = Spi::get_one::<&[u8]>(&format!("SELECT '{TEXT}'::ulid::bytea;")).unwrap();
228+
229+
assert_eq!(Some(BYTEA), result);
230+
}
231+
214232
#[pg_test]
215233
fn test_uuid_to_ulid() {
216234
let result = Spi::get_one::<ulid>(&format!("SELECT '{UUID}'::uuid::ulid;")).unwrap();

0 commit comments

Comments
 (0)