postgres-types-0.2.6/.cargo_vcs_info.json0000644000000001540000000000100140510ustar { "git": { "sha1": "6f7ab44d5bc8548a4e7fb69d46d3b85a14101144" }, "path_in_vcs": "postgres-types" }postgres-types-0.2.6/CHANGELOG.md000064400000000000000000000043141046102023000144540ustar 00000000000000# Change Log ## v0.2.6 - 2023-08-19 ### Fixed * Fixed serialization to `OIDVECTOR` and `INT2VECTOR`. ### Added * Removed the `'static` requirement for the `impl BorrowToSql for Box`. * Added a `ToSql` implementation for `Cow<[u8]>`. ## v0.2.5 - 2023-03-27 ### Added * Added support for multi-range types. ## v0.2.4 - 2022-08-20 ### Added * Added `ToSql` and `FromSql` implementations for `Box<[T]>`. * Added `ToSql` and `FromSql` implementations for `[u8; N]` via the `array-impls` feature. * Added support for `smol_str` 0.1 via the `with-smol_str-01` feature. * Added `ToSql::encode_format` to support text encodings of parameters. ## v0.2.3 - 2022-04-30 ### Added * Added `ToSql` and `FromSql` implementations for `Box`. * Added `BorrowToSql` implementations for `Box` and `Box`. * Added support for `cidr` 0.2 via the `with-cidr-02` feature. * Added conversions between the `LTREE`, `LQUERY` and `LTXTQUERY` types and Rust strings. * Added support for `uuid` 1.0 via the `with-uuid-1` feature. ## v0.2.2 - 2021-09-29 ### Added * Added support for `eui48` 1.0 via the `with-eui48-1` feature. * Added `ToSql` and `FromSql` implementations for array types via the `array-impls` feature. * Added support for `time` 0.3 via the `with-time-0_3` feature. ## v0.2.1 - 2021-04-03 ### Added * Added support for `geo-types` 0.7 via `with-geo-types-0_7` feature. * Added the `PgLsn` type, corresponding to `PG_LSN`. ## v0.2.0 - 2020-12-25 ### Changed * Upgraded `bytes` to 1.0. ### Removed * Removed support for `geo-types` 0.4. ## v0.1.3 - 2020-10-17 ### Added * Implemented `Clone`, `PartialEq`, and `Eq` for `Json`. ### Fixed * Checked for overflow in `NaiveDate` and `NaiveDateTime` conversions. ## v0.1.2 - 2020-07-03 ### Added * Added support for `geo-types` 0.6. ## v0.1.1 - 2020-03-05 ### Added * Added support for `time` 0.2. ## v0.1.0 - 2019-12-23 ### Changed * `Kind` is now a true non-exhaustive enum. ### Removed * Removed `uuid` 0.7 support. ### Added * Added a `Hash` implementation for `Type`. ## v0.1.0-alpha.2 - 2019-11-27 ### Changed * Upgraded `bytes` to 0.5. * Upgraded `uuid` to 0.8. ## v0.1.0-alpha.1 - 2019-10-14 Initial release postgres-types-0.2.6/Cargo.toml0000644000000053720000000000100120560ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "postgres-types" version = "0.2.6" authors = ["Steven Fackler "] description = "Conversions between Rust and Postgres values" readme = "README.md" keywords = [ "database", "postgres", "postgresql", "sql", ] categories = ["database"] license = "MIT/Apache-2.0" repository = "https://github.com/sfackler/rust-postgres" resolver = "2" [dependencies.array-init] version = "2" optional = true [dependencies.bit-vec-06] version = "0.6" optional = true package = "bit-vec" [dependencies.bytes] version = "1.0" [dependencies.chrono-04] version = "0.4.16" features = ["clock"] optional = true default-features = false package = "chrono" [dependencies.cidr-02] version = "0.2" optional = true package = "cidr" [dependencies.eui48-04] version = "0.4" optional = true package = "eui48" [dependencies.eui48-1] version = "1.0" optional = true package = "eui48" [dependencies.fallible-iterator] version = "0.2" [dependencies.geo-types-06] version = "0.6" optional = true package = "geo-types" [dependencies.geo-types-0_7] version = "0.7" optional = true package = "geo-types" [dependencies.postgres-derive] version = "0.4.5" optional = true [dependencies.postgres-protocol] version = "0.6.5" [dependencies.serde-1] version = "1.0" optional = true package = "serde" [dependencies.serde_json-1] version = "1.0" optional = true package = "serde_json" [dependencies.smol_str-01] version = "0.1.23" optional = true default-features = false package = "smol_str" [dependencies.time-02] version = "0.2" optional = true package = "time" [dependencies.time-03] version = "0.3" optional = true default-features = false package = "time" [dependencies.uuid-08] version = "0.8" optional = true package = "uuid" [dependencies.uuid-1] version = "1.0" optional = true package = "uuid" [features] array-impls = ["array-init"] derive = ["postgres-derive"] with-bit-vec-0_6 = ["bit-vec-06"] with-chrono-0_4 = ["chrono-04"] with-cidr-0_2 = ["cidr-02"] with-eui48-0_4 = ["eui48-04"] with-eui48-1 = ["eui48-1"] with-geo-types-0_6 = ["geo-types-06"] with-geo-types-0_7 = ["geo-types-0_7"] with-serde_json-1 = [ "serde-1", "serde_json-1", ] with-smol_str-01 = ["smol_str-01"] with-time-0_2 = ["time-02"] with-time-0_3 = ["time-03"] with-uuid-0_8 = ["uuid-08"] with-uuid-1 = ["uuid-1"] postgres-types-0.2.6/Cargo.toml.orig000064400000000000000000000042311046102023000155300ustar 00000000000000[package] name = "postgres-types" version = "0.2.6" authors = ["Steven Fackler "] edition = "2018" license = "MIT/Apache-2.0" description = "Conversions between Rust and Postgres values" repository = "https://github.com/sfackler/rust-postgres" readme = "../README.md" keywords = ["database", "postgres", "postgresql", "sql"] categories = ["database"] [features] derive = ["postgres-derive"] array-impls = ["array-init"] with-bit-vec-0_6 = ["bit-vec-06"] with-cidr-0_2 = ["cidr-02"] with-chrono-0_4 = ["chrono-04"] with-eui48-0_4 = ["eui48-04"] with-eui48-1 = ["eui48-1"] with-geo-types-0_6 = ["geo-types-06"] with-geo-types-0_7 = ["geo-types-0_7"] with-serde_json-1 = ["serde-1", "serde_json-1"] with-smol_str-01 = ["smol_str-01"] with-uuid-0_8 = ["uuid-08"] with-uuid-1 = ["uuid-1"] with-time-0_2 = ["time-02"] with-time-0_3 = ["time-03"] [dependencies] bytes = "1.0" fallible-iterator = "0.2" postgres-protocol = { version = "0.6.5", path = "../postgres-protocol" } postgres-derive = { version = "0.4.5", optional = true, path = "../postgres-derive" } array-init = { version = "2", optional = true } bit-vec-06 = { version = "0.6", package = "bit-vec", optional = true } chrono-04 = { version = "0.4.16", package = "chrono", default-features = false, features = [ "clock", ], optional = true } cidr-02 = { version = "0.2", package = "cidr", optional = true } eui48-04 = { version = "0.4", package = "eui48", optional = true } eui48-1 = { version = "1.0", package = "eui48", optional = true } geo-types-06 = { version = "0.6", package = "geo-types", optional = true } geo-types-0_7 = { version = "0.7", package = "geo-types", optional = true } serde-1 = { version = "1.0", package = "serde", optional = true } serde_json-1 = { version = "1.0", package = "serde_json", optional = true } uuid-08 = { version = "0.8", package = "uuid", optional = true } uuid-1 = { version = "1.0", package = "uuid", optional = true } time-02 = { version = "0.2", package = "time", optional = true } time-03 = { version = "0.3", package = "time", default-features = false, optional = true } smol_str-01 = { version = "0.1.23", package = "smol_str", default-features = false, optional = true } postgres-types-0.2.6/LICENSE-APACHE000064400000000000000000000251371046102023000145750ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. postgres-types-0.2.6/LICENSE-MIT000064400000000000000000000020721046102023000142760ustar 00000000000000The MIT License (MIT) Copyright (c) 2016 Steven Fackler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. postgres-types-0.2.6/README.md000064400000000000000000000032371046102023000141250ustar 00000000000000# Rust-Postgres PostgreSQL support for Rust. ## postgres [![Latest Version](https://img.shields.io/crates/v/postgres.svg)](https://crates.io/crates/postgres) [Documentation](https://docs.rs/postgres) A native, synchronous PostgreSQL client. ## tokio-postgres [![Latest Version](https://img.shields.io/crates/v/tokio-postgres.svg)](https://crates.io/crates/tokio-postgres) [Documentation](https://docs.rs/tokio-postgres) A native, asynchronous PostgreSQL client. ## postgres-types [![Latest Version](https://img.shields.io/crates/v/postgres-types.svg)](https://crates.io/crates/postgres-types) [Documentation](https://docs.rs/postgres-types) Conversions between Rust and Postgres types. ## postgres-native-tls [![Latest Version](https://img.shields.io/crates/v/postgres-native-tls.svg)](https://crates.io/crates/postgres-native-tls) [Documentation](https://docs.rs/postgres-native-tls) TLS support for postgres and tokio-postgres via native-tls. ## postgres-openssl [![Latest Version](https://img.shields.io/crates/v/postgres-openssl.svg)](https://crates.io/crates/postgres-openssl) [Documentation](https://docs.rs/postgres-openssl) TLS support for postgres and tokio-postgres via openssl. # Running test suite The test suite requires postgres to be running in the correct configuration. The easiest way to do this is with docker: 1. Install `docker` and `docker-compose`. 1. On ubuntu: `sudo apt install docker.io docker-compose`. 1. Make sure your user has permissions for docker. 1. On ubuntu: ``sudo usermod -aG docker $USER`` 1. Change to top-level directory of `rust-postgres` repo. 1. Run `docker-compose up -d`. 1. Run `cargo test`. 1. Run `docker-compose stop`. postgres-types-0.2.6/src/bit_vec_06.rs000064400000000000000000000014361046102023000157220ustar 00000000000000use bit_vec_06::BitVec; use bytes::BytesMut; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for BitVec { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let varbit = types::varbit_from_sql(raw)?; let mut bitvec = BitVec::from_bytes(varbit.bytes()); while bitvec.len() > varbit.len() { bitvec.pop(); } Ok(bitvec) } accepts!(BIT, VARBIT); } impl ToSql for BitVec { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { types::varbit_to_sql(self.len(), self.to_bytes().into_iter(), out)?; Ok(IsNull::No) } accepts!(BIT, VARBIT); to_sql_checked!(); } postgres-types-0.2.6/src/chrono_04.rs000064400000000000000000000106241046102023000155740ustar 00000000000000use bytes::BytesMut; use chrono_04::{DateTime, Duration, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, Utc}; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; fn base() -> NaiveDateTime { NaiveDate::from_ymd_opt(2000, 1, 1) .unwrap() .and_hms_opt(0, 0, 0) .unwrap() } impl<'a> FromSql<'a> for NaiveDateTime { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let t = types::timestamp_from_sql(raw)?; base() .checked_add_signed(Duration::microseconds(t)) .ok_or_else(|| "value too large to decode".into()) } accepts!(TIMESTAMP); } impl ToSql for NaiveDateTime { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let time = match self.signed_duration_since(base()).num_microseconds() { Some(time) => time, None => return Err("value too large to transmit".into()), }; types::timestamp_to_sql(time, w); Ok(IsNull::No) } accepts!(TIMESTAMP); to_sql_checked!(); } impl<'a> FromSql<'a> for DateTime { fn from_sql(type_: &Type, raw: &[u8]) -> Result, Box> { let naive = NaiveDateTime::from_sql(type_, raw)?; Ok(DateTime::from_utc(naive, Utc)) } accepts!(TIMESTAMPTZ); } impl ToSql for DateTime { fn to_sql( &self, type_: &Type, w: &mut BytesMut, ) -> Result> { self.naive_utc().to_sql(type_, w) } accepts!(TIMESTAMPTZ); to_sql_checked!(); } impl<'a> FromSql<'a> for DateTime { fn from_sql(type_: &Type, raw: &[u8]) -> Result, Box> { let utc = DateTime::::from_sql(type_, raw)?; Ok(utc.with_timezone(&Local)) } accepts!(TIMESTAMPTZ); } impl ToSql for DateTime { fn to_sql( &self, type_: &Type, w: &mut BytesMut, ) -> Result> { self.with_timezone(&Utc).to_sql(type_, w) } accepts!(TIMESTAMPTZ); to_sql_checked!(); } impl<'a> FromSql<'a> for DateTime { fn from_sql( type_: &Type, raw: &[u8], ) -> Result, Box> { let utc = DateTime::::from_sql(type_, raw)?; Ok(utc.with_timezone(&FixedOffset::east_opt(0).unwrap())) } accepts!(TIMESTAMPTZ); } impl ToSql for DateTime { fn to_sql( &self, type_: &Type, w: &mut BytesMut, ) -> Result> { self.with_timezone(&Utc).to_sql(type_, w) } accepts!(TIMESTAMPTZ); to_sql_checked!(); } impl<'a> FromSql<'a> for NaiveDate { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let jd = types::date_from_sql(raw)?; base() .date() .checked_add_signed(Duration::days(i64::from(jd))) .ok_or_else(|| "value too large to decode".into()) } accepts!(DATE); } impl ToSql for NaiveDate { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let jd = self.signed_duration_since(base().date()).num_days(); if jd > i64::from(i32::max_value()) || jd < i64::from(i32::min_value()) { return Err("value too large to transmit".into()); } types::date_to_sql(jd as i32, w); Ok(IsNull::No) } accepts!(DATE); to_sql_checked!(); } impl<'a> FromSql<'a> for NaiveTime { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let usec = types::time_from_sql(raw)?; Ok(NaiveTime::from_hms_opt(0, 0, 0).unwrap() + Duration::microseconds(usec)) } accepts!(TIME); } impl ToSql for NaiveTime { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let delta = self.signed_duration_since(NaiveTime::from_hms_opt(0, 0, 0).unwrap()); let time = match delta.num_microseconds() { Some(time) => time, None => return Err("value too large to transmit".into()), }; types::time_to_sql(time, w); Ok(IsNull::No) } accepts!(TIME); to_sql_checked!(); } postgres-types-0.2.6/src/cidr_02.rs000064400000000000000000000022531046102023000152220ustar 00000000000000use bytes::BytesMut; use cidr_02::{IpCidr, IpInet}; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for IpCidr { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let inet = types::inet_from_sql(raw)?; Ok(IpCidr::new(inet.addr(), inet.netmask())?) } accepts!(CIDR); } impl ToSql for IpCidr { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::inet_to_sql(self.first_address(), self.network_length(), w); Ok(IsNull::No) } accepts!(CIDR); to_sql_checked!(); } impl<'a> FromSql<'a> for IpInet { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let inet = types::inet_from_sql(raw)?; Ok(IpInet::new(inet.addr(), inet.netmask())?) } accepts!(INET); } impl ToSql for IpInet { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::inet_to_sql(self.address(), self.network_length(), w); Ok(IsNull::No) } accepts!(INET); to_sql_checked!(); } postgres-types-0.2.6/src/eui48_04.rs000064400000000000000000000013201046102023000152330ustar 00000000000000use bytes::BytesMut; use eui48_04::MacAddress; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for MacAddress { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let bytes = types::macaddr_from_sql(raw)?; Ok(MacAddress::new(bytes)) } accepts!(MACADDR); } impl ToSql for MacAddress { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let mut bytes = [0; 6]; bytes.copy_from_slice(self.as_bytes()); types::macaddr_to_sql(bytes, w); Ok(IsNull::No) } accepts!(MACADDR); to_sql_checked!(); } postgres-types-0.2.6/src/eui48_1.rs000064400000000000000000000013171046102023000151560ustar 00000000000000use bytes::BytesMut; use eui48_1::MacAddress; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for MacAddress { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let bytes = types::macaddr_from_sql(raw)?; Ok(MacAddress::new(bytes)) } accepts!(MACADDR); } impl ToSql for MacAddress { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let mut bytes = [0; 6]; bytes.copy_from_slice(self.as_bytes()); types::macaddr_to_sql(bytes, w); Ok(IsNull::No) } accepts!(MACADDR); to_sql_checked!(); } postgres-types-0.2.6/src/geo_types_06.rs000064400000000000000000000040641046102023000163050ustar 00000000000000use bytes::BytesMut; use fallible_iterator::FallibleIterator; use geo_types_06::{Coordinate, LineString, Point, Rect}; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for Point { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let point = types::point_from_sql(raw)?; Ok(Point::new(point.x(), point.y())) } accepts!(POINT); } impl ToSql for Point { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { types::point_to_sql(self.x(), self.y(), out); Ok(IsNull::No) } accepts!(POINT); to_sql_checked!(); } impl<'a> FromSql<'a> for Rect { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let rect = types::box_from_sql(raw)?; Ok(Rect::new( (rect.lower_left().x(), rect.lower_left().y()), (rect.upper_right().x(), rect.upper_right().y()), )) } accepts!(BOX); } impl ToSql for Rect { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { types::box_to_sql(self.min().x, self.min().y, self.max().x, self.max().y, out); Ok(IsNull::No) } accepts!(BOX); to_sql_checked!(); } impl<'a> FromSql<'a> for LineString { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let path = types::path_from_sql(raw)?; let points = path .points() .map(|p| Ok(Coordinate { x: p.x(), y: p.y() })) .collect()?; Ok(LineString(points)) } accepts!(PATH); } impl ToSql for LineString { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { let closed = false; // always encode an open path from LineString types::path_to_sql(closed, self.0.iter().map(|p| (p.x, p.y)), out)?; Ok(IsNull::No) } accepts!(PATH); to_sql_checked!(); } postgres-types-0.2.6/src/geo_types_07.rs000064400000000000000000000040531046102023000163040ustar 00000000000000use bytes::BytesMut; use fallible_iterator::FallibleIterator; use geo_types_0_7::{Coord, LineString, Point, Rect}; use postgres_protocol::types; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for Point { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let point = types::point_from_sql(raw)?; Ok(Point::new(point.x(), point.y())) } accepts!(POINT); } impl ToSql for Point { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { types::point_to_sql(self.x(), self.y(), out); Ok(IsNull::No) } accepts!(POINT); to_sql_checked!(); } impl<'a> FromSql<'a> for Rect { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let rect = types::box_from_sql(raw)?; Ok(Rect::new( (rect.lower_left().x(), rect.lower_left().y()), (rect.upper_right().x(), rect.upper_right().y()), )) } accepts!(BOX); } impl ToSql for Rect { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { types::box_to_sql(self.min().x, self.min().y, self.max().x, self.max().y, out); Ok(IsNull::No) } accepts!(BOX); to_sql_checked!(); } impl<'a> FromSql<'a> for LineString { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let path = types::path_from_sql(raw)?; let points = path .points() .map(|p| Ok(Coord { x: p.x(), y: p.y() })) .collect()?; Ok(LineString(points)) } accepts!(PATH); } impl ToSql for LineString { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { let closed = false; // always encode an open path from LineString types::path_to_sql(closed, self.0.iter().map(|p| (p.x, p.y)), out)?; Ok(IsNull::No) } accepts!(PATH); to_sql_checked!(); } postgres-types-0.2.6/src/lib.rs000064400000000000000000001144601046102023000145520ustar 00000000000000//! Conversions to and from Postgres types. //! //! This crate is used by the `tokio-postgres` and `postgres` crates. You normally don't need to depend directly on it //! unless you want to define your own `ToSql` or `FromSql` definitions. //! //! # Derive //! //! If the `derive` cargo feature is enabled, you can derive `ToSql` and `FromSql` implementations for custom Postgres //! types. Explicitly, modify your `Cargo.toml` file to include the following: //! //! ```toml //! [dependencies] //! postgres-types = { version = "0.X.X", features = ["derive"] } //! ``` //! //! ## Enums //! //! Postgres enums correspond to C-like enums in Rust: //! //! ```sql //! CREATE TYPE "Mood" AS ENUM ( //! 'Sad', //! 'Ok', //! 'Happy' //! ); //! ``` //! //! ```rust //! # #[cfg(feature = "derive")] //! use postgres_types::{ToSql, FromSql}; //! //! # #[cfg(feature = "derive")] //! #[derive(Debug, ToSql, FromSql)] //! enum Mood { //! Sad, //! Ok, //! Happy, //! } //! ``` //! //! ## Domains //! //! Postgres domains correspond to tuple structs with one member in Rust: //! //! ```sql //! CREATE DOMAIN "SessionId" AS BYTEA CHECK(octet_length(VALUE) = 16); //! ``` //! //! ```rust //! # #[cfg(feature = "derive")] //! use postgres_types::{ToSql, FromSql}; //! //! # #[cfg(feature = "derive")] //! #[derive(Debug, ToSql, FromSql)] //! struct SessionId(Vec); //! ``` //! //! ## Newtypes //! //! The `#[postgres(transparent)]` attribute can be used on a single-field tuple struct to create a //! Rust-only wrapper type that will use the [`ToSql`] & [`FromSql`] implementation of the inner //! value : //! ```rust //! # #[cfg(feature = "derive")] //! use postgres_types::{ToSql, FromSql}; //! //! # #[cfg(feature = "derive")] //! #[derive(Debug, ToSql, FromSql)] //! #[postgres(transparent)] //! struct UserId(i32); //! ``` //! //! ## Composites //! //! Postgres composite types correspond to structs in Rust: //! //! ```sql //! CREATE TYPE "InventoryItem" AS ( //! name TEXT, //! supplier_id INT, //! price DOUBLE PRECISION //! ); //! ``` //! //! ```rust //! # #[cfg(feature = "derive")] //! use postgres_types::{ToSql, FromSql}; //! //! # #[cfg(feature = "derive")] //! #[derive(Debug, ToSql, FromSql)] //! struct InventoryItem { //! name: String, //! supplier_id: i32, //! price: Option, //! } //! ``` //! //! ## Naming //! //! The derived implementations will enforce exact matches of type, field, and variant names between the Rust and //! Postgres types. The `#[postgres(name = "...")]` attribute can be used to adjust the name on a type, variant, or //! field: //! //! ```sql //! CREATE TYPE mood AS ENUM ( //! 'sad', //! 'ok', //! 'happy' //! ); //! ``` //! //! ```rust //! # #[cfg(feature = "derive")] //! use postgres_types::{ToSql, FromSql}; //! //! # #[cfg(feature = "derive")] //! #[derive(Debug, ToSql, FromSql)] //! #[postgres(name = "mood")] //! enum Mood { //! #[postgres(name = "sad")] //! Sad, //! #[postgres(name = "ok")] //! Ok, //! #[postgres(name = "happy")] //! Happy, //! } //! ``` //! //! Alternatively, the `#[postgres(rename_all = "...")]` attribute can be used to rename all fields or variants //! with the chosen casing convention. This will not affect the struct or enum's type name. Note that //! `#[postgres(name = "...")]` takes precendence when used in conjunction with `#[postgres(rename_all = "...")]`: //! //! ```rust //! # #[cfg(feature = "derive")] //! use postgres_types::{ToSql, FromSql}; //! //! # #[cfg(feature = "derive")] //! #[derive(Debug, ToSql, FromSql)] //! #[postgres(name = "mood", rename_all = "snake_case")] //! enum Mood { //! #[postgres(name = "ok")] //! Ok, // ok //! VeryHappy, // very_happy //! } //! ``` //! //! The following case conventions are supported: //! - `"lowercase"` //! - `"UPPERCASE"` //! - `"PascalCase"` //! - `"camelCase"` //! - `"snake_case"` //! - `"SCREAMING_SNAKE_CASE"` //! - `"kebab-case"` //! - `"SCREAMING-KEBAB-CASE"` //! - `"Train-Case"` //! //! ## Allowing Enum Mismatches //! //! By default the generated implementation of [`ToSql`] & [`FromSql`] for enums will require an exact match of the enum //! variants between the Rust and Postgres types. //! To allow mismatches, the `#[postgres(allow_mismatch)]` attribute can be used on the enum definition: //! //! ```sql //! CREATE TYPE mood AS ENUM ( //! 'Sad', //! 'Ok', //! 'Happy' //! ); //! ``` //! #[postgres(allow_mismatch)] //! enum Mood { //! Happy, //! Meh, //! } //! ``` #![warn(clippy::all, rust_2018_idioms, missing_docs)] use fallible_iterator::FallibleIterator; use postgres_protocol::types::{self, ArrayDimension}; use std::any::type_name; use std::borrow::Cow; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::hash::BuildHasher; use std::net::IpAddr; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; #[cfg(feature = "derive")] pub use postgres_derive::{FromSql, ToSql}; #[cfg(feature = "with-serde_json-1")] pub use crate::serde_json_1::Json; use crate::type_gen::{Inner, Other}; #[doc(inline)] pub use postgres_protocol::Oid; #[doc(inline)] pub use pg_lsn::PgLsn; pub use crate::special::{Date, Timestamp}; use bytes::BytesMut; // Number of seconds from 1970-01-01 to 2000-01-01 const TIME_SEC_CONVERSION: u64 = 946_684_800; const USEC_PER_SEC: u64 = 1_000_000; const NSEC_PER_USEC: u64 = 1_000; /// Generates a simple implementation of `ToSql::accepts` which accepts the /// types passed to it. #[macro_export] macro_rules! accepts { ($($expected:ident),+) => ( fn accepts(ty: &$crate::Type) -> bool { matches!(*ty, $($crate::Type::$expected)|+) } ) } /// Generates an implementation of `ToSql::to_sql_checked`. /// /// All `ToSql` implementations should use this macro. #[macro_export] macro_rules! to_sql_checked { () => { fn to_sql_checked( &self, ty: &$crate::Type, out: &mut $crate::private::BytesMut, ) -> ::std::result::Result< $crate::IsNull, Box, > { $crate::__to_sql_checked(self, ty, out) } }; } // WARNING: this function is not considered part of this crate's public API. // It is subject to change at any time. #[doc(hidden)] pub fn __to_sql_checked( v: &T, ty: &Type, out: &mut BytesMut, ) -> Result> where T: ToSql, { if !T::accepts(ty) { return Err(Box::new(WrongType::new::(ty.clone()))); } v.to_sql(ty, out) } #[cfg(feature = "with-bit-vec-0_6")] mod bit_vec_06; #[cfg(feature = "with-chrono-0_4")] mod chrono_04; #[cfg(feature = "with-cidr-0_2")] mod cidr_02; #[cfg(feature = "with-eui48-0_4")] mod eui48_04; #[cfg(feature = "with-eui48-1")] mod eui48_1; #[cfg(feature = "with-geo-types-0_6")] mod geo_types_06; #[cfg(feature = "with-geo-types-0_7")] mod geo_types_07; #[cfg(feature = "with-serde_json-1")] mod serde_json_1; #[cfg(feature = "with-smol_str-01")] mod smol_str_01; #[cfg(feature = "with-time-0_2")] mod time_02; #[cfg(feature = "with-time-0_3")] mod time_03; #[cfg(feature = "with-uuid-0_8")] mod uuid_08; #[cfg(feature = "with-uuid-1")] mod uuid_1; // The time::{date, time} macros produce compile errors if the crate package is renamed. #[cfg(feature = "with-time-0_2")] extern crate time_02 as time; mod pg_lsn; #[doc(hidden)] pub mod private; mod special; mod type_gen; /// A Postgres type. #[derive(PartialEq, Eq, Clone, Hash)] pub struct Type(Inner); impl fmt::Debug for Type { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.0, fmt) } } impl fmt::Display for Type { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match self.schema() { "public" | "pg_catalog" => {} schema => write!(fmt, "{}.", schema)?, } fmt.write_str(self.name()) } } impl Type { /// Creates a new `Type`. pub fn new(name: String, oid: Oid, kind: Kind, schema: String) -> Type { Type(Inner::Other(Arc::new(Other { name, oid, kind, schema, }))) } /// Returns the `Type` corresponding to the provided `Oid` if it /// corresponds to a built-in type. pub fn from_oid(oid: Oid) -> Option { Inner::from_oid(oid).map(Type) } /// Returns the OID of the `Type`. pub fn oid(&self) -> Oid { self.0.oid() } /// Returns the kind of this type. pub fn kind(&self) -> &Kind { self.0.kind() } /// Returns the schema of this type. pub fn schema(&self) -> &str { match self.0 { Inner::Other(ref u) => &u.schema, _ => "pg_catalog", } } /// Returns the name of this type. pub fn name(&self) -> &str { self.0.name() } } /// Represents the kind of a Postgres type. #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Kind { /// A simple type like `VARCHAR` or `INTEGER`. Simple, /// An enumerated type along with its variants. Enum(Vec), /// A pseudo-type. Pseudo, /// An array type along with the type of its elements. Array(Type), /// A range type along with the type of its elements. Range(Type), /// A multirange type along with the type of its elements. Multirange(Type), /// A domain type along with its underlying type. Domain(Type), /// A composite type along with information about its fields. Composite(Vec), } /// Information about a field of a composite type. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Field { name: String, type_: Type, } impl Field { /// Creates a new `Field`. pub fn new(name: String, type_: Type) -> Field { Field { name, type_ } } /// Returns the name of the field. pub fn name(&self) -> &str { &self.name } /// Returns the type of the field. pub fn type_(&self) -> &Type { &self.type_ } } /// An error indicating that a `NULL` Postgres value was passed to a `FromSql` /// implementation that does not support `NULL` values. #[derive(Debug, Clone, Copy)] pub struct WasNull; impl fmt::Display for WasNull { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str("a Postgres value was `NULL`") } } impl Error for WasNull {} /// An error indicating that a conversion was attempted between incompatible /// Rust and Postgres types. #[derive(Debug)] pub struct WrongType { postgres: Type, rust: &'static str, } impl fmt::Display for WrongType { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "cannot convert between the Rust type `{}` and the Postgres type `{}`", self.rust, self.postgres, ) } } impl Error for WrongType {} impl WrongType { /// Creates a new `WrongType` error. pub fn new(ty: Type) -> WrongType { WrongType { postgres: ty, rust: type_name::(), } } } /// A trait for types that can be created from a Postgres value. /// /// # Types /// /// The following implementations are provided by this crate, along with the /// corresponding Postgres types: /// /// | Rust type | Postgres type(s) | /// |-----------------------------------|-----------------------------------------------| /// | `bool` | BOOL | /// | `i8` | "char" | /// | `i16` | SMALLINT, SMALLSERIAL | /// | `i32` | INT, SERIAL | /// | `u32` | OID | /// | `i64` | BIGINT, BIGSERIAL | /// | `f32` | REAL | /// | `f64` | DOUBLE PRECISION | /// | `&str`/`String` | VARCHAR, CHAR(n), TEXT, CITEXT, NAME, UNKNOWN | /// | | LTREE, LQUERY, LTXTQUERY | /// | `&[u8]`/`Vec` | BYTEA | /// | `HashMap>` | HSTORE | /// | `SystemTime` | TIMESTAMP, TIMESTAMP WITH TIME ZONE | /// | `IpAddr` | INET | /// /// In addition, some implementations are provided for types in third party /// crates. These are disabled by default; to opt into one of these /// implementations, activate the Cargo feature corresponding to the crate's /// name prefixed by `with-`. For example, the `with-serde_json-1` feature enables /// the implementation for the `serde_json::Value` type. /// /// | Rust type | Postgres type(s) | /// |---------------------------------|-------------------------------------| /// | `chrono::NaiveDateTime` | TIMESTAMP | /// | `chrono::DateTime` | TIMESTAMP WITH TIME ZONE | /// | `chrono::DateTime` | TIMESTAMP WITH TIME ZONE | /// | `chrono::DateTime` | TIMESTAMP WITH TIME ZONE | /// | `chrono::NaiveDate` | DATE | /// | `chrono::NaiveTime` | TIME | /// | `time::PrimitiveDateTime` | TIMESTAMP | /// | `time::OffsetDateTime` | TIMESTAMP WITH TIME ZONE | /// | `time::Date` | DATE | /// | `time::Time` | TIME | /// | `eui48::MacAddress` | MACADDR | /// | `geo_types::Point` | POINT | /// | `geo_types::Rect` | BOX | /// | `geo_types::LineString` | PATH | /// | `serde_json::Value` | JSON, JSONB | /// | `uuid::Uuid` | UUID | /// | `bit_vec::BitVec` | BIT, VARBIT | /// | `eui48::MacAddress` | MACADDR | /// | `cidr::InetCidr` | CIDR | /// | `cidr::InetAddr` | INET | /// | `smol_str::SmolStr` | VARCHAR, CHAR(n), TEXT, CITEXT, | /// | | NAME, UNKNOWN, LTREE, LQUERY, | /// | | LTXTQUERY | /// /// # Nullability /// /// In addition to the types listed above, `FromSql` is implemented for /// `Option` where `T` implements `FromSql`. An `Option` represents a /// nullable Postgres value. /// /// # Arrays /// /// `FromSql` is implemented for `Vec`, `Box<[T]>` and `[T; N]` where `T` /// implements `FromSql`, and corresponds to one-dimensional Postgres arrays. /// /// **Note:** the impl for arrays only exist when the Cargo feature `array-impls` /// is enabled. pub trait FromSql<'a>: Sized { /// Creates a new value of this type from a buffer of data of the specified /// Postgres `Type` in its binary format. /// /// The caller of this method is responsible for ensuring that this type /// is compatible with the Postgres `Type`. fn from_sql(ty: &Type, raw: &'a [u8]) -> Result>; /// Creates a new value of this type from a `NULL` SQL value. /// /// The caller of this method is responsible for ensuring that this type /// is compatible with the Postgres `Type`. /// /// The default implementation returns `Err(Box::new(WasNull))`. #[allow(unused_variables)] fn from_sql_null(ty: &Type) -> Result> { Err(Box::new(WasNull)) } /// A convenience function that delegates to `from_sql` and `from_sql_null` depending on the /// value of `raw`. fn from_sql_nullable( ty: &Type, raw: Option<&'a [u8]>, ) -> Result> { match raw { Some(raw) => Self::from_sql(ty, raw), None => Self::from_sql_null(ty), } } /// Determines if a value of this type can be created from the specified /// Postgres `Type`. fn accepts(ty: &Type) -> bool; } /// A trait for types which can be created from a Postgres value without borrowing any data. /// /// This is primarily useful for trait bounds on functions. pub trait FromSqlOwned: for<'a> FromSql<'a> {} impl FromSqlOwned for T where T: for<'a> FromSql<'a> {} impl<'a, T: FromSql<'a>> FromSql<'a> for Option { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result, Box> { ::from_sql(ty, raw).map(Some) } fn from_sql_null(_: &Type) -> Result, Box> { Ok(None) } fn accepts(ty: &Type) -> bool { ::accepts(ty) } } impl<'a, T: FromSql<'a>> FromSql<'a> for Vec { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result, Box> { let member_type = match *ty.kind() { Kind::Array(ref member) => member, _ => panic!("expected array type"), }; let array = types::array_from_sql(raw)?; if array.dimensions().count()? > 1 { return Err("array contains too many dimensions".into()); } array .values() .map(|v| T::from_sql_nullable(member_type, v)) .collect() } fn accepts(ty: &Type) -> bool { match *ty.kind() { Kind::Array(ref inner) => T::accepts(inner), _ => false, } } } #[cfg(feature = "array-impls")] impl<'a, T: FromSql<'a>, const N: usize> FromSql<'a> for [T; N] { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { let member_type = match *ty.kind() { Kind::Array(ref member) => member, _ => panic!("expected array type"), }; let array = types::array_from_sql(raw)?; if array.dimensions().count()? > 1 { return Err("array contains too many dimensions".into()); } let mut values = array.values(); let out = array_init::try_array_init(|i| { let v = values .next()? .ok_or_else(|| -> Box { format!("too few elements in array (expected {}, got {})", N, i).into() })?; T::from_sql_nullable(member_type, v) })?; if values.next()?.is_some() { return Err(format!( "excess elements in array (expected {}, got more than that)", N, ) .into()); } Ok(out) } fn accepts(ty: &Type) -> bool { match *ty.kind() { Kind::Array(ref inner) => T::accepts(inner), _ => false, } } } impl<'a, T: FromSql<'a>> FromSql<'a> for Box<[T]> { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { Vec::::from_sql(ty, raw).map(Vec::into_boxed_slice) } fn accepts(ty: &Type) -> bool { Vec::::accepts(ty) } } impl<'a> FromSql<'a> for Vec { fn from_sql(_: &Type, raw: &'a [u8]) -> Result, Box> { Ok(types::bytea_from_sql(raw).to_owned()) } accepts!(BYTEA); } impl<'a> FromSql<'a> for &'a [u8] { fn from_sql(_: &Type, raw: &'a [u8]) -> Result<&'a [u8], Box> { Ok(types::bytea_from_sql(raw)) } accepts!(BYTEA); } impl<'a> FromSql<'a> for String { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { <&str as FromSql>::from_sql(ty, raw).map(ToString::to_string) } fn accepts(ty: &Type) -> bool { <&str as FromSql>::accepts(ty) } } impl<'a> FromSql<'a> for Box { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result, Box> { <&str as FromSql>::from_sql(ty, raw) .map(ToString::to_string) .map(String::into_boxed_str) } fn accepts(ty: &Type) -> bool { <&str as FromSql>::accepts(ty) } } impl<'a> FromSql<'a> for &'a str { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<&'a str, Box> { match *ty { ref ty if ty.name() == "ltree" => types::ltree_from_sql(raw), ref ty if ty.name() == "lquery" => types::lquery_from_sql(raw), ref ty if ty.name() == "ltxtquery" => types::ltxtquery_from_sql(raw), _ => types::text_from_sql(raw), } } fn accepts(ty: &Type) -> bool { match *ty { Type::VARCHAR | Type::TEXT | Type::BPCHAR | Type::NAME | Type::UNKNOWN => true, ref ty if (ty.name() == "citext" || ty.name() == "ltree" || ty.name() == "lquery" || ty.name() == "ltxtquery") => { true } _ => false, } } } macro_rules! simple_from { ($t:ty, $f:ident, $($expected:ident),+) => { impl<'a> FromSql<'a> for $t { fn from_sql(_: &Type, raw: &'a [u8]) -> Result<$t, Box> { types::$f(raw) } accepts!($($expected),+); } } } simple_from!(bool, bool_from_sql, BOOL); simple_from!(i8, char_from_sql, CHAR); simple_from!(i16, int2_from_sql, INT2); simple_from!(i32, int4_from_sql, INT4); simple_from!(u32, oid_from_sql, OID); simple_from!(i64, int8_from_sql, INT8); simple_from!(f32, float4_from_sql, FLOAT4); simple_from!(f64, float8_from_sql, FLOAT8); impl<'a, S> FromSql<'a> for HashMap, S> where S: Default + BuildHasher, { fn from_sql( _: &Type, raw: &'a [u8], ) -> Result, S>, Box> { types::hstore_from_sql(raw)? .map(|(k, v)| Ok((k.to_owned(), v.map(str::to_owned)))) .collect() } fn accepts(ty: &Type) -> bool { ty.name() == "hstore" } } impl<'a> FromSql<'a> for SystemTime { fn from_sql(_: &Type, raw: &'a [u8]) -> Result> { let time = types::timestamp_from_sql(raw)?; let epoch = UNIX_EPOCH + Duration::from_secs(TIME_SEC_CONVERSION); let negative = time < 0; let time = time.unsigned_abs(); let secs = time / USEC_PER_SEC; let nsec = (time % USEC_PER_SEC) * NSEC_PER_USEC; let offset = Duration::new(secs, nsec as u32); let time = if negative { epoch - offset } else { epoch + offset }; Ok(time) } accepts!(TIMESTAMP, TIMESTAMPTZ); } impl<'a> FromSql<'a> for IpAddr { fn from_sql(_: &Type, raw: &'a [u8]) -> Result> { let inet = types::inet_from_sql(raw)?; Ok(inet.addr()) } accepts!(INET); } /// An enum representing the nullability of a Postgres value. pub enum IsNull { /// The value is NULL. Yes, /// The value is not NULL. No, } /// A trait for types that can be converted into Postgres values. /// /// # Types /// /// The following implementations are provided by this crate, along with the /// corresponding Postgres types: /// /// | Rust type | Postgres type(s) | /// |-----------------------------------|--------------------------------------| /// | `bool` | BOOL | /// | `i8` | "char" | /// | `i16` | SMALLINT, SMALLSERIAL | /// | `i32` | INT, SERIAL | /// | `u32` | OID | /// | `i64` | BIGINT, BIGSERIAL | /// | `f32` | REAL | /// | `f64` | DOUBLE PRECISION | /// | `&str`/`String` | VARCHAR, CHAR(n), TEXT, CITEXT, NAME | /// | | LTREE, LQUERY, LTXTQUERY | /// | `&[u8]`/`Vec`/`[u8; N]` | BYTEA | /// | `HashMap>` | HSTORE | /// | `SystemTime` | TIMESTAMP, TIMESTAMP WITH TIME ZONE | /// | `IpAddr` | INET | /// /// In addition, some implementations are provided for types in third party /// crates. These are disabled by default; to opt into one of these /// implementations, activate the Cargo feature corresponding to the crate's /// name prefixed by `with-`. For example, the `with-serde_json-1` feature enables /// the implementation for the `serde_json::Value` type. /// /// | Rust type | Postgres type(s) | /// |---------------------------------|-------------------------------------| /// | `chrono::NaiveDateTime` | TIMESTAMP | /// | `chrono::DateTime` | TIMESTAMP WITH TIME ZONE | /// | `chrono::DateTime` | TIMESTAMP WITH TIME ZONE | /// | `chrono::DateTime` | TIMESTAMP WITH TIME ZONE | /// | `chrono::NaiveDate` | DATE | /// | `chrono::NaiveTime` | TIME | /// | `time::PrimitiveDateTime` | TIMESTAMP | /// | `time::OffsetDateTime` | TIMESTAMP WITH TIME ZONE | /// | `time::Date` | DATE | /// | `time::Time` | TIME | /// | `eui48::MacAddress` | MACADDR | /// | `geo_types::Point` | POINT | /// | `geo_types::Rect` | BOX | /// | `geo_types::LineString` | PATH | /// | `serde_json::Value` | JSON, JSONB | /// | `uuid::Uuid` | UUID | /// | `bit_vec::BitVec` | BIT, VARBIT | /// | `eui48::MacAddress` | MACADDR | /// /// # Nullability /// /// In addition to the types listed above, `ToSql` is implemented for /// `Option` where `T` implements `ToSql`. An `Option` represents a /// nullable Postgres value. /// /// # Arrays /// /// `ToSql` is implemented for `[u8; N]`, `Vec`, `&[T]`, `Box<[T]>` and `[T; N]` /// where `T` implements `ToSql` and `N` is const usize, and corresponds to one-dimensional /// Postgres arrays with an index offset of 1. /// /// **Note:** the impl for arrays only exist when the Cargo feature `array-impls` /// is enabled. pub trait ToSql: fmt::Debug { /// Converts the value of `self` into the binary format of the specified /// Postgres `Type`, appending it to `out`. /// /// The caller of this method is responsible for ensuring that this type /// is compatible with the Postgres `Type`. /// /// The return value indicates if this value should be represented as /// `NULL`. If this is the case, implementations **must not** write /// anything to `out`. fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result> where Self: Sized; /// Determines if a value of this type can be converted to the specified /// Postgres `Type`. fn accepts(ty: &Type) -> bool where Self: Sized; /// An adaptor method used internally by Rust-Postgres. /// /// *All* implementations of this method should be generated by the /// `to_sql_checked!()` macro. fn to_sql_checked( &self, ty: &Type, out: &mut BytesMut, ) -> Result>; /// Specify the encode format fn encode_format(&self, _ty: &Type) -> Format { Format::Binary } } /// Supported Postgres message format types /// /// Using Text format in a message assumes a Postgres `SERVER_ENCODING` of `UTF8` #[derive(Clone, Copy, Debug)] pub enum Format { /// Text format (UTF-8) Text, /// Compact, typed binary format Binary, } impl<'a, T> ToSql for &'a T where T: ToSql, { fn to_sql( &self, ty: &Type, out: &mut BytesMut, ) -> Result> { (*self).to_sql(ty, out) } fn accepts(ty: &Type) -> bool { T::accepts(ty) } fn encode_format(&self, ty: &Type) -> Format { (*self).encode_format(ty) } to_sql_checked!(); } impl ToSql for Option { fn to_sql( &self, ty: &Type, out: &mut BytesMut, ) -> Result> { match *self { Some(ref val) => val.to_sql(ty, out), None => Ok(IsNull::Yes), } } fn accepts(ty: &Type) -> bool { ::accepts(ty) } fn encode_format(&self, ty: &Type) -> Format { match self { Some(ref val) => val.encode_format(ty), None => Format::Binary, } } to_sql_checked!(); } impl<'a, T: ToSql> ToSql for &'a [T] { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { let member_type = match *ty.kind() { Kind::Array(ref member) => member, _ => panic!("expected array type"), }; // Arrays are normally one indexed by default but oidvector and int2vector *require* zero indexing let lower_bound = match *ty { Type::OID_VECTOR | Type::INT2_VECTOR => 0, _ => 1, }; let dimension = ArrayDimension { len: downcast(self.len())?, lower_bound, }; types::array_to_sql( Some(dimension), member_type.oid(), self.iter(), |e, w| match e.to_sql(member_type, w)? { IsNull::No => Ok(postgres_protocol::IsNull::No), IsNull::Yes => Ok(postgres_protocol::IsNull::Yes), }, w, )?; Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { match *ty.kind() { Kind::Array(ref member) => T::accepts(member), _ => false, } } to_sql_checked!(); } impl<'a> ToSql for &'a [u8] { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::bytea_to_sql(self, w); Ok(IsNull::No) } accepts!(BYTEA); to_sql_checked!(); } #[cfg(feature = "array-impls")] impl ToSql for [u8; N] { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::bytea_to_sql(&self[..], w); Ok(IsNull::No) } accepts!(BYTEA); to_sql_checked!(); } #[cfg(feature = "array-impls")] impl ToSql for [T; N] { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&[T] as ToSql>::to_sql(&&self[..], ty, w) } fn accepts(ty: &Type) -> bool { <&[T] as ToSql>::accepts(ty) } to_sql_checked!(); } impl ToSql for Vec { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&[T] as ToSql>::to_sql(&&**self, ty, w) } fn accepts(ty: &Type) -> bool { <&[T] as ToSql>::accepts(ty) } to_sql_checked!(); } impl ToSql for Box<[T]> { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&[T] as ToSql>::to_sql(&&**self, ty, w) } fn accepts(ty: &Type) -> bool { <&[T] as ToSql>::accepts(ty) } to_sql_checked!(); } impl<'a> ToSql for Cow<'a, [u8]> { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&[u8] as ToSql>::to_sql(&self.as_ref(), ty, w) } fn accepts(ty: &Type) -> bool { <&[u8] as ToSql>::accepts(ty) } to_sql_checked!(); } impl ToSql for Vec { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&[u8] as ToSql>::to_sql(&&**self, ty, w) } fn accepts(ty: &Type) -> bool { <&[u8] as ToSql>::accepts(ty) } to_sql_checked!(); } impl<'a> ToSql for &'a str { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { match ty.name() { "ltree" => types::ltree_to_sql(self, w), "lquery" => types::lquery_to_sql(self, w), "ltxtquery" => types::ltxtquery_to_sql(self, w), _ => types::text_to_sql(self, w), } Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { matches!( *ty, Type::VARCHAR | Type::TEXT | Type::BPCHAR | Type::NAME | Type::UNKNOWN ) || matches!(ty.name(), "citext" | "ltree" | "lquery" | "ltxtquery") } to_sql_checked!(); } impl<'a> ToSql for Cow<'a, str> { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&str as ToSql>::to_sql(&self.as_ref(), ty, w) } fn accepts(ty: &Type) -> bool { <&str as ToSql>::accepts(ty) } to_sql_checked!(); } impl ToSql for String { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&str as ToSql>::to_sql(&&**self, ty, w) } fn accepts(ty: &Type) -> bool { <&str as ToSql>::accepts(ty) } to_sql_checked!(); } impl ToSql for Box { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&str as ToSql>::to_sql(&&**self, ty, w) } fn accepts(ty: &Type) -> bool { <&str as ToSql>::accepts(ty) } to_sql_checked!(); } macro_rules! simple_to { ($t:ty, $f:ident, $($expected:ident),+) => { impl ToSql for $t { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::$f(*self, w); Ok(IsNull::No) } accepts!($($expected),+); to_sql_checked!(); } } } simple_to!(bool, bool_to_sql, BOOL); simple_to!(i8, char_to_sql, CHAR); simple_to!(i16, int2_to_sql, INT2); simple_to!(i32, int4_to_sql, INT4); simple_to!(u32, oid_to_sql, OID); simple_to!(i64, int8_to_sql, INT8); simple_to!(f32, float4_to_sql, FLOAT4); simple_to!(f64, float8_to_sql, FLOAT8); impl ToSql for HashMap, H> where H: BuildHasher, { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::hstore_to_sql( self.iter().map(|(k, v)| (&**k, v.as_ref().map(|v| &**v))), w, )?; Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { ty.name() == "hstore" } to_sql_checked!(); } impl ToSql for SystemTime { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let epoch = UNIX_EPOCH + Duration::from_secs(TIME_SEC_CONVERSION); let to_usec = |d: Duration| d.as_secs() * USEC_PER_SEC + u64::from(d.subsec_nanos()) / NSEC_PER_USEC; let time = match self.duration_since(epoch) { Ok(duration) => to_usec(duration) as i64, Err(e) => -(to_usec(e.duration()) as i64), }; types::timestamp_to_sql(time, w); Ok(IsNull::No) } accepts!(TIMESTAMP, TIMESTAMPTZ); to_sql_checked!(); } impl ToSql for IpAddr { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let netmask = match self { IpAddr::V4(_) => 32, IpAddr::V6(_) => 128, }; types::inet_to_sql(*self, netmask, w); Ok(IsNull::No) } accepts!(INET); to_sql_checked!(); } fn downcast(len: usize) -> Result> { if len > i32::max_value() as usize { Err("value too large to transmit".into()) } else { Ok(len as i32) } } mod sealed { pub trait Sealed {} } /// A trait used by clients to abstract over `&dyn ToSql` and `T: ToSql`. /// /// This cannot be implemented outside of this crate. pub trait BorrowToSql: sealed::Sealed { /// Returns a reference to `self` as a `ToSql` trait object. fn borrow_to_sql(&self) -> &dyn ToSql; } impl sealed::Sealed for &dyn ToSql {} impl BorrowToSql for &dyn ToSql { #[inline] fn borrow_to_sql(&self) -> &dyn ToSql { *self } } impl<'a> sealed::Sealed for Box {} impl<'a> BorrowToSql for Box { #[inline] fn borrow_to_sql(&self) -> &dyn ToSql { self.as_ref() } } impl<'a> sealed::Sealed for Box {} impl<'a> BorrowToSql for Box { #[inline] fn borrow_to_sql(&self) -> &dyn ToSql { self.as_ref() } } impl sealed::Sealed for &(dyn ToSql + Sync) {} /// In async contexts it is sometimes necessary to have the additional /// Sync requirement on parameters for queries since this enables the /// resulting Futures to be Send, hence usable in, e.g., tokio::spawn. /// This instance is provided for those cases. impl BorrowToSql for &(dyn ToSql + Sync) { #[inline] fn borrow_to_sql(&self) -> &dyn ToSql { *self } } impl sealed::Sealed for T where T: ToSql {} impl BorrowToSql for T where T: ToSql, { #[inline] fn borrow_to_sql(&self) -> &dyn ToSql { self } } postgres-types-0.2.6/src/pg_lsn.rs000064400000000000000000000036261046102023000152670ustar 00000000000000//! Log Sequence Number (LSN) type for PostgreSQL Write-Ahead Log //! (WAL), also known as the transaction log. use bytes::BytesMut; use postgres_protocol::types; use std::error::Error; use std::fmt; use std::str::FromStr; use crate::{FromSql, IsNull, ToSql, Type}; /// Postgres `PG_LSN` type. #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] pub struct PgLsn(u64); /// Error parsing LSN. #[derive(Debug)] pub struct ParseLsnError(()); impl From for PgLsn { fn from(lsn_u64: u64) -> Self { PgLsn(lsn_u64) } } impl From for u64 { fn from(lsn: PgLsn) -> u64 { lsn.0 } } impl FromStr for PgLsn { type Err = ParseLsnError; fn from_str(lsn_str: &str) -> Result { let split: Vec<&str> = lsn_str.split('/').collect(); if split.len() == 2 { let (hi, lo) = ( u64::from_str_radix(split[0], 16).map_err(|_| ParseLsnError(()))?, u64::from_str_radix(split[1], 16).map_err(|_| ParseLsnError(()))?, ); Ok(PgLsn((hi << 32) | lo)) } else { Err(ParseLsnError(())) } } } impl fmt::Display for PgLsn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:X}/{:X}", self.0 >> 32, self.0 & 0x00000000ffffffff) } } impl fmt::Debug for PgLsn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!("{}", self)) } } impl<'a> FromSql<'a> for PgLsn { fn from_sql(_: &Type, raw: &'a [u8]) -> Result> { let v = types::lsn_from_sql(raw)?; Ok(v.into()) } accepts!(PG_LSN); } impl ToSql for PgLsn { fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result> { types::lsn_to_sql((*self).into(), out); Ok(IsNull::No) } accepts!(PG_LSN); to_sql_checked!(); } postgres-types-0.2.6/src/private.rs000064400000000000000000000015061046102023000154520ustar 00000000000000use crate::{FromSql, Type}; pub use bytes::BytesMut; use std::error::Error; pub fn read_be_i32(buf: &mut &[u8]) -> Result> { if buf.len() < 4 { return Err("invalid buffer size".into()); } let mut bytes = [0; 4]; bytes.copy_from_slice(&buf[..4]); *buf = &buf[4..]; Ok(i32::from_be_bytes(bytes)) } pub fn read_value<'a, T>( type_: &Type, buf: &mut &'a [u8], ) -> Result> where T: FromSql<'a>, { let len = read_be_i32(buf)?; let value = if len < 0 { None } else { if len as usize > buf.len() { return Err("invalid buffer size".into()); } let (head, tail) = buf.split_at(len as usize); *buf = tail; Some(head) }; T::from_sql_nullable(type_, value) } postgres-types-0.2.6/src/serde_json_1.rs000064400000000000000000000034631046102023000163570ustar 00000000000000use crate::{FromSql, IsNull, ToSql, Type}; use bytes::{BufMut, BytesMut}; use serde_1::{Deserialize, Serialize}; use serde_json_1::Value; use std::error::Error; use std::fmt::Debug; use std::io::Read; /// A wrapper type to allow arbitrary `Serialize`/`Deserialize` types to convert to Postgres JSON values. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Json(pub T); impl<'a, T> FromSql<'a> for Json where T: Deserialize<'a>, { fn from_sql(ty: &Type, mut raw: &'a [u8]) -> Result, Box> { if *ty == Type::JSONB { let mut b = [0; 1]; raw.read_exact(&mut b)?; // We only support version 1 of the jsonb binary format if b[0] != 1 { return Err("unsupported JSONB encoding version".into()); } } serde_json_1::de::from_slice(raw) .map(Json) .map_err(Into::into) } accepts!(JSON, JSONB); } impl ToSql for Json where T: Serialize + Debug, { fn to_sql( &self, ty: &Type, out: &mut BytesMut, ) -> Result> { if *ty == Type::JSONB { out.put_u8(1); } serde_json_1::ser::to_writer(out.writer(), &self.0)?; Ok(IsNull::No) } accepts!(JSON, JSONB); to_sql_checked!(); } impl<'a> FromSql<'a> for Value { fn from_sql(ty: &Type, raw: &[u8]) -> Result> { Json::::from_sql(ty, raw).map(|json| json.0) } accepts!(JSON, JSONB); } impl ToSql for Value { fn to_sql( &self, ty: &Type, out: &mut BytesMut, ) -> Result> { Json(self).to_sql(ty, out) } accepts!(JSON, JSONB); to_sql_checked!(); } postgres-types-0.2.6/src/smol_str_01.rs000064400000000000000000000012541046102023000161420ustar 00000000000000use bytes::BytesMut; use smol_str_01::SmolStr; use std::error::Error; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for SmolStr { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { <&str as FromSql>::from_sql(ty, raw).map(SmolStr::from) } fn accepts(ty: &Type) -> bool { <&str as FromSql>::accepts(ty) } } impl ToSql for SmolStr { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&str as ToSql>::to_sql(&&**self, ty, w) } fn accepts(ty: &Type) -> bool { <&str as ToSql>::accepts(ty) } to_sql_checked!(); } postgres-types-0.2.6/src/special.rs000064400000000000000000000057201046102023000154220ustar 00000000000000use bytes::BytesMut; use postgres_protocol::types; use std::error::Error; use std::{i32, i64}; use crate::{FromSql, IsNull, ToSql, Type}; /// A wrapper that can be used to represent infinity with `Type::Date` types. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Date { /// Represents `infinity`, a date that is later than all other dates. PosInfinity, /// Represents `-infinity`, a date that is earlier than all other dates. NegInfinity, /// The wrapped date. Value(T), } impl<'a, T: FromSql<'a>> FromSql<'a> for Date { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { match types::date_from_sql(raw)? { i32::MAX => Ok(Date::PosInfinity), i32::MIN => Ok(Date::NegInfinity), _ => T::from_sql(ty, raw).map(Date::Value), } } fn accepts(ty: &Type) -> bool { *ty == Type::DATE && T::accepts(ty) } } impl ToSql for Date { fn to_sql( &self, ty: &Type, out: &mut BytesMut, ) -> Result> { let value = match *self { Date::PosInfinity => i32::MAX, Date::NegInfinity => i32::MIN, Date::Value(ref v) => return v.to_sql(ty, out), }; types::date_to_sql(value, out); Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { *ty == Type::DATE && T::accepts(ty) } to_sql_checked!(); } /// A wrapper that can be used to represent infinity with `Type::Timestamp` and `Type::Timestamptz` /// types. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Timestamp { /// Represents `infinity`, a timestamp that is later than all other timestamps. PosInfinity, /// Represents `-infinity`, a timestamp that is earlier than all other timestamps. NegInfinity, /// The wrapped timestamp. Value(T), } impl<'a, T: FromSql<'a>> FromSql<'a> for Timestamp { fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { match types::timestamp_from_sql(raw)? { i64::MAX => Ok(Timestamp::PosInfinity), i64::MIN => Ok(Timestamp::NegInfinity), _ => T::from_sql(ty, raw).map(Timestamp::Value), } } fn accepts(ty: &Type) -> bool { matches!(*ty, Type::TIMESTAMP | Type::TIMESTAMPTZ if T::accepts(ty)) } } impl ToSql for Timestamp { fn to_sql( &self, ty: &Type, out: &mut BytesMut, ) -> Result> { let value = match *self { Timestamp::PosInfinity => i64::MAX, Timestamp::NegInfinity => i64::MIN, Timestamp::Value(ref v) => return v.to_sql(ty, out), }; types::timestamp_to_sql(value, out); Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { matches!(*ty, Type::TIMESTAMP | Type::TIMESTAMPTZ if T::accepts(ty)) } to_sql_checked!(); } postgres-types-0.2.6/src/time_02.rs000064400000000000000000000062521046102023000152420ustar 00000000000000use bytes::BytesMut; use postgres_protocol::types; use std::convert::TryFrom; use std::error::Error; use time_02::{date, time, Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; use crate::{FromSql, IsNull, ToSql, Type}; #[rustfmt::skip] const fn base() -> PrimitiveDateTime { PrimitiveDateTime::new(date!(2000-01-01), time!(00:00:00)) } impl<'a> FromSql<'a> for PrimitiveDateTime { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let t = types::timestamp_from_sql(raw)?; Ok(base() + Duration::microseconds(t)) } accepts!(TIMESTAMP); } impl ToSql for PrimitiveDateTime { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let time = match i64::try_from((*self - base()).whole_microseconds()) { Ok(time) => time, Err(_) => return Err("value too large to transmit".into()), }; types::timestamp_to_sql(time, w); Ok(IsNull::No) } accepts!(TIMESTAMP); to_sql_checked!(); } impl<'a> FromSql<'a> for OffsetDateTime { fn from_sql(type_: &Type, raw: &[u8]) -> Result> { let primitive = PrimitiveDateTime::from_sql(type_, raw)?; Ok(primitive.assume_utc()) } accepts!(TIMESTAMPTZ); } impl ToSql for OffsetDateTime { fn to_sql( &self, type_: &Type, w: &mut BytesMut, ) -> Result> { let utc_datetime = self.to_offset(UtcOffset::UTC); let date = utc_datetime.date(); let time = utc_datetime.time(); let primitive = PrimitiveDateTime::new(date, time); primitive.to_sql(type_, w) } accepts!(TIMESTAMPTZ); to_sql_checked!(); } impl<'a> FromSql<'a> for Date { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let jd = types::date_from_sql(raw)?; Ok(base().date() + Duration::days(i64::from(jd))) } accepts!(DATE); } impl ToSql for Date { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let jd = (*self - base().date()).whole_days(); if jd > i64::from(i32::max_value()) || jd < i64::from(i32::min_value()) { return Err("value too large to transmit".into()); } types::date_to_sql(jd as i32, w); Ok(IsNull::No) } accepts!(DATE); to_sql_checked!(); } impl<'a> FromSql<'a> for Time { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let usec = types::time_from_sql(raw)?; Ok(time!(00:00:00) + Duration::microseconds(usec)) } accepts!(TIME); } impl ToSql for Time { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let delta = *self - time!(00:00:00); let time = match i64::try_from(delta.whole_microseconds()) { Ok(time) => time, Err(_) => return Err("value too large to transmit".into()), }; types::time_to_sql(time, w); Ok(IsNull::No) } accepts!(TIME); to_sql_checked!(); } postgres-types-0.2.6/src/time_03.rs000064400000000000000000000062341046102023000152430ustar 00000000000000use bytes::BytesMut; use postgres_protocol::types; use std::convert::TryFrom; use std::error::Error; use time_03::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; use crate::{FromSql, IsNull, ToSql, Type}; fn base() -> PrimitiveDateTime { PrimitiveDateTime::new(Date::from_ordinal_date(2000, 1).unwrap(), Time::MIDNIGHT) } impl<'a> FromSql<'a> for PrimitiveDateTime { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let t = types::timestamp_from_sql(raw)?; Ok(base() + Duration::microseconds(t)) } accepts!(TIMESTAMP); } impl ToSql for PrimitiveDateTime { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let time = match i64::try_from((*self - base()).whole_microseconds()) { Ok(time) => time, Err(_) => return Err("value too large to transmit".into()), }; types::timestamp_to_sql(time, w); Ok(IsNull::No) } accepts!(TIMESTAMP); to_sql_checked!(); } impl<'a> FromSql<'a> for OffsetDateTime { fn from_sql(type_: &Type, raw: &[u8]) -> Result> { let primitive = PrimitiveDateTime::from_sql(type_, raw)?; Ok(primitive.assume_utc()) } accepts!(TIMESTAMPTZ); } impl ToSql for OffsetDateTime { fn to_sql( &self, type_: &Type, w: &mut BytesMut, ) -> Result> { let utc_datetime = self.to_offset(UtcOffset::UTC); let date = utc_datetime.date(); let time = utc_datetime.time(); let primitive = PrimitiveDateTime::new(date, time); primitive.to_sql(type_, w) } accepts!(TIMESTAMPTZ); to_sql_checked!(); } impl<'a> FromSql<'a> for Date { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let jd = types::date_from_sql(raw)?; Ok(base().date() + Duration::days(i64::from(jd))) } accepts!(DATE); } impl ToSql for Date { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let jd = (*self - base().date()).whole_days(); if jd > i64::from(i32::max_value()) || jd < i64::from(i32::min_value()) { return Err("value too large to transmit".into()); } types::date_to_sql(jd as i32, w); Ok(IsNull::No) } accepts!(DATE); to_sql_checked!(); } impl<'a> FromSql<'a> for Time { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let usec = types::time_from_sql(raw)?; Ok(Time::MIDNIGHT + Duration::microseconds(usec)) } accepts!(TIME); } impl ToSql for Time { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { let delta = *self - Time::MIDNIGHT; let time = match i64::try_from(delta.whole_microseconds()) { Ok(time) => time, Err(_) => return Err("value too large to transmit".into()), }; types::time_to_sql(time, w); Ok(IsNull::No) } accepts!(TIME); to_sql_checked!(); } postgres-types-0.2.6/src/type_gen.rs000064400000000000000000001603411046102023000156150ustar 00000000000000// Autogenerated file - DO NOT EDIT use std::sync::Arc; use crate::{Kind, Oid, Type}; #[derive(PartialEq, Eq, Debug, Hash)] pub struct Other { pub name: String, pub oid: Oid, pub kind: Kind, pub schema: String, } #[derive(PartialEq, Eq, Clone, Debug, Hash)] pub enum Inner { Bool, Bytea, Char, Name, Int8, Int2, Int2Vector, Int4, Regproc, Text, Oid, Tid, Xid, Cid, OidVector, PgDdlCommand, Json, Xml, XmlArray, PgNodeTree, JsonArray, TableAmHandler, Xid8Array, IndexAmHandler, Point, Lseg, Path, Box, Polygon, Line, LineArray, Cidr, CidrArray, Float4, Float8, Unknown, Circle, CircleArray, Macaddr8, Macaddr8Array, Money, MoneyArray, Macaddr, Inet, BoolArray, ByteaArray, CharArray, NameArray, Int2Array, Int2VectorArray, Int4Array, RegprocArray, TextArray, TidArray, XidArray, CidArray, OidVectorArray, BpcharArray, VarcharArray, Int8Array, PointArray, LsegArray, PathArray, BoxArray, Float4Array, Float8Array, PolygonArray, OidArray, Aclitem, AclitemArray, MacaddrArray, InetArray, Bpchar, Varchar, Date, Time, Timestamp, TimestampArray, DateArray, TimeArray, Timestamptz, TimestamptzArray, Interval, IntervalArray, NumericArray, CstringArray, Timetz, TimetzArray, Bit, BitArray, Varbit, VarbitArray, Numeric, Refcursor, RefcursorArray, Regprocedure, Regoper, Regoperator, Regclass, Regtype, RegprocedureArray, RegoperArray, RegoperatorArray, RegclassArray, RegtypeArray, Record, Cstring, Any, Anyarray, Void, Trigger, LanguageHandler, Internal, Anyelement, RecordArray, Anynonarray, TxidSnapshotArray, Uuid, UuidArray, TxidSnapshot, FdwHandler, PgLsn, PgLsnArray, TsmHandler, PgNdistinct, PgDependencies, Anyenum, TsVector, Tsquery, GtsVector, TsVectorArray, GtsVectorArray, TsqueryArray, Regconfig, RegconfigArray, Regdictionary, RegdictionaryArray, Jsonb, JsonbArray, AnyRange, EventTrigger, Int4Range, Int4RangeArray, NumRange, NumRangeArray, TsRange, TsRangeArray, TstzRange, TstzRangeArray, DateRange, DateRangeArray, Int8Range, Int8RangeArray, Jsonpath, JsonpathArray, Regnamespace, RegnamespaceArray, Regrole, RegroleArray, Regcollation, RegcollationArray, Int4multiRange, NummultiRange, TsmultiRange, TstzmultiRange, DatemultiRange, Int8multiRange, AnymultiRange, AnycompatiblemultiRange, PgBrinBloomSummary, PgBrinMinmaxMultiSummary, PgMcvList, PgSnapshot, PgSnapshotArray, Xid8, Anycompatible, Anycompatiblearray, Anycompatiblenonarray, AnycompatibleRange, Int4multiRangeArray, NummultiRangeArray, TsmultiRangeArray, TstzmultiRangeArray, DatemultiRangeArray, Int8multiRangeArray, Other(Arc), } impl Inner { pub fn from_oid(oid: Oid) -> Option { match oid { 16 => Some(Inner::Bool), 17 => Some(Inner::Bytea), 18 => Some(Inner::Char), 19 => Some(Inner::Name), 20 => Some(Inner::Int8), 21 => Some(Inner::Int2), 22 => Some(Inner::Int2Vector), 23 => Some(Inner::Int4), 24 => Some(Inner::Regproc), 25 => Some(Inner::Text), 26 => Some(Inner::Oid), 27 => Some(Inner::Tid), 28 => Some(Inner::Xid), 29 => Some(Inner::Cid), 30 => Some(Inner::OidVector), 32 => Some(Inner::PgDdlCommand), 114 => Some(Inner::Json), 142 => Some(Inner::Xml), 143 => Some(Inner::XmlArray), 194 => Some(Inner::PgNodeTree), 199 => Some(Inner::JsonArray), 269 => Some(Inner::TableAmHandler), 271 => Some(Inner::Xid8Array), 325 => Some(Inner::IndexAmHandler), 600 => Some(Inner::Point), 601 => Some(Inner::Lseg), 602 => Some(Inner::Path), 603 => Some(Inner::Box), 604 => Some(Inner::Polygon), 628 => Some(Inner::Line), 629 => Some(Inner::LineArray), 650 => Some(Inner::Cidr), 651 => Some(Inner::CidrArray), 700 => Some(Inner::Float4), 701 => Some(Inner::Float8), 705 => Some(Inner::Unknown), 718 => Some(Inner::Circle), 719 => Some(Inner::CircleArray), 774 => Some(Inner::Macaddr8), 775 => Some(Inner::Macaddr8Array), 790 => Some(Inner::Money), 791 => Some(Inner::MoneyArray), 829 => Some(Inner::Macaddr), 869 => Some(Inner::Inet), 1000 => Some(Inner::BoolArray), 1001 => Some(Inner::ByteaArray), 1002 => Some(Inner::CharArray), 1003 => Some(Inner::NameArray), 1005 => Some(Inner::Int2Array), 1006 => Some(Inner::Int2VectorArray), 1007 => Some(Inner::Int4Array), 1008 => Some(Inner::RegprocArray), 1009 => Some(Inner::TextArray), 1010 => Some(Inner::TidArray), 1011 => Some(Inner::XidArray), 1012 => Some(Inner::CidArray), 1013 => Some(Inner::OidVectorArray), 1014 => Some(Inner::BpcharArray), 1015 => Some(Inner::VarcharArray), 1016 => Some(Inner::Int8Array), 1017 => Some(Inner::PointArray), 1018 => Some(Inner::LsegArray), 1019 => Some(Inner::PathArray), 1020 => Some(Inner::BoxArray), 1021 => Some(Inner::Float4Array), 1022 => Some(Inner::Float8Array), 1027 => Some(Inner::PolygonArray), 1028 => Some(Inner::OidArray), 1033 => Some(Inner::Aclitem), 1034 => Some(Inner::AclitemArray), 1040 => Some(Inner::MacaddrArray), 1041 => Some(Inner::InetArray), 1042 => Some(Inner::Bpchar), 1043 => Some(Inner::Varchar), 1082 => Some(Inner::Date), 1083 => Some(Inner::Time), 1114 => Some(Inner::Timestamp), 1115 => Some(Inner::TimestampArray), 1182 => Some(Inner::DateArray), 1183 => Some(Inner::TimeArray), 1184 => Some(Inner::Timestamptz), 1185 => Some(Inner::TimestamptzArray), 1186 => Some(Inner::Interval), 1187 => Some(Inner::IntervalArray), 1231 => Some(Inner::NumericArray), 1263 => Some(Inner::CstringArray), 1266 => Some(Inner::Timetz), 1270 => Some(Inner::TimetzArray), 1560 => Some(Inner::Bit), 1561 => Some(Inner::BitArray), 1562 => Some(Inner::Varbit), 1563 => Some(Inner::VarbitArray), 1700 => Some(Inner::Numeric), 1790 => Some(Inner::Refcursor), 2201 => Some(Inner::RefcursorArray), 2202 => Some(Inner::Regprocedure), 2203 => Some(Inner::Regoper), 2204 => Some(Inner::Regoperator), 2205 => Some(Inner::Regclass), 2206 => Some(Inner::Regtype), 2207 => Some(Inner::RegprocedureArray), 2208 => Some(Inner::RegoperArray), 2209 => Some(Inner::RegoperatorArray), 2210 => Some(Inner::RegclassArray), 2211 => Some(Inner::RegtypeArray), 2249 => Some(Inner::Record), 2275 => Some(Inner::Cstring), 2276 => Some(Inner::Any), 2277 => Some(Inner::Anyarray), 2278 => Some(Inner::Void), 2279 => Some(Inner::Trigger), 2280 => Some(Inner::LanguageHandler), 2281 => Some(Inner::Internal), 2283 => Some(Inner::Anyelement), 2287 => Some(Inner::RecordArray), 2776 => Some(Inner::Anynonarray), 2949 => Some(Inner::TxidSnapshotArray), 2950 => Some(Inner::Uuid), 2951 => Some(Inner::UuidArray), 2970 => Some(Inner::TxidSnapshot), 3115 => Some(Inner::FdwHandler), 3220 => Some(Inner::PgLsn), 3221 => Some(Inner::PgLsnArray), 3310 => Some(Inner::TsmHandler), 3361 => Some(Inner::PgNdistinct), 3402 => Some(Inner::PgDependencies), 3500 => Some(Inner::Anyenum), 3614 => Some(Inner::TsVector), 3615 => Some(Inner::Tsquery), 3642 => Some(Inner::GtsVector), 3643 => Some(Inner::TsVectorArray), 3644 => Some(Inner::GtsVectorArray), 3645 => Some(Inner::TsqueryArray), 3734 => Some(Inner::Regconfig), 3735 => Some(Inner::RegconfigArray), 3769 => Some(Inner::Regdictionary), 3770 => Some(Inner::RegdictionaryArray), 3802 => Some(Inner::Jsonb), 3807 => Some(Inner::JsonbArray), 3831 => Some(Inner::AnyRange), 3838 => Some(Inner::EventTrigger), 3904 => Some(Inner::Int4Range), 3905 => Some(Inner::Int4RangeArray), 3906 => Some(Inner::NumRange), 3907 => Some(Inner::NumRangeArray), 3908 => Some(Inner::TsRange), 3909 => Some(Inner::TsRangeArray), 3910 => Some(Inner::TstzRange), 3911 => Some(Inner::TstzRangeArray), 3912 => Some(Inner::DateRange), 3913 => Some(Inner::DateRangeArray), 3926 => Some(Inner::Int8Range), 3927 => Some(Inner::Int8RangeArray), 4072 => Some(Inner::Jsonpath), 4073 => Some(Inner::JsonpathArray), 4089 => Some(Inner::Regnamespace), 4090 => Some(Inner::RegnamespaceArray), 4096 => Some(Inner::Regrole), 4097 => Some(Inner::RegroleArray), 4191 => Some(Inner::Regcollation), 4192 => Some(Inner::RegcollationArray), 4451 => Some(Inner::Int4multiRange), 4532 => Some(Inner::NummultiRange), 4533 => Some(Inner::TsmultiRange), 4534 => Some(Inner::TstzmultiRange), 4535 => Some(Inner::DatemultiRange), 4536 => Some(Inner::Int8multiRange), 4537 => Some(Inner::AnymultiRange), 4538 => Some(Inner::AnycompatiblemultiRange), 4600 => Some(Inner::PgBrinBloomSummary), 4601 => Some(Inner::PgBrinMinmaxMultiSummary), 5017 => Some(Inner::PgMcvList), 5038 => Some(Inner::PgSnapshot), 5039 => Some(Inner::PgSnapshotArray), 5069 => Some(Inner::Xid8), 5077 => Some(Inner::Anycompatible), 5078 => Some(Inner::Anycompatiblearray), 5079 => Some(Inner::Anycompatiblenonarray), 5080 => Some(Inner::AnycompatibleRange), 6150 => Some(Inner::Int4multiRangeArray), 6151 => Some(Inner::NummultiRangeArray), 6152 => Some(Inner::TsmultiRangeArray), 6153 => Some(Inner::TstzmultiRangeArray), 6155 => Some(Inner::DatemultiRangeArray), 6157 => Some(Inner::Int8multiRangeArray), _ => None, } } pub fn oid(&self) -> Oid { match *self { Inner::Bool => 16, Inner::Bytea => 17, Inner::Char => 18, Inner::Name => 19, Inner::Int8 => 20, Inner::Int2 => 21, Inner::Int2Vector => 22, Inner::Int4 => 23, Inner::Regproc => 24, Inner::Text => 25, Inner::Oid => 26, Inner::Tid => 27, Inner::Xid => 28, Inner::Cid => 29, Inner::OidVector => 30, Inner::PgDdlCommand => 32, Inner::Json => 114, Inner::Xml => 142, Inner::XmlArray => 143, Inner::PgNodeTree => 194, Inner::JsonArray => 199, Inner::TableAmHandler => 269, Inner::Xid8Array => 271, Inner::IndexAmHandler => 325, Inner::Point => 600, Inner::Lseg => 601, Inner::Path => 602, Inner::Box => 603, Inner::Polygon => 604, Inner::Line => 628, Inner::LineArray => 629, Inner::Cidr => 650, Inner::CidrArray => 651, Inner::Float4 => 700, Inner::Float8 => 701, Inner::Unknown => 705, Inner::Circle => 718, Inner::CircleArray => 719, Inner::Macaddr8 => 774, Inner::Macaddr8Array => 775, Inner::Money => 790, Inner::MoneyArray => 791, Inner::Macaddr => 829, Inner::Inet => 869, Inner::BoolArray => 1000, Inner::ByteaArray => 1001, Inner::CharArray => 1002, Inner::NameArray => 1003, Inner::Int2Array => 1005, Inner::Int2VectorArray => 1006, Inner::Int4Array => 1007, Inner::RegprocArray => 1008, Inner::TextArray => 1009, Inner::TidArray => 1010, Inner::XidArray => 1011, Inner::CidArray => 1012, Inner::OidVectorArray => 1013, Inner::BpcharArray => 1014, Inner::VarcharArray => 1015, Inner::Int8Array => 1016, Inner::PointArray => 1017, Inner::LsegArray => 1018, Inner::PathArray => 1019, Inner::BoxArray => 1020, Inner::Float4Array => 1021, Inner::Float8Array => 1022, Inner::PolygonArray => 1027, Inner::OidArray => 1028, Inner::Aclitem => 1033, Inner::AclitemArray => 1034, Inner::MacaddrArray => 1040, Inner::InetArray => 1041, Inner::Bpchar => 1042, Inner::Varchar => 1043, Inner::Date => 1082, Inner::Time => 1083, Inner::Timestamp => 1114, Inner::TimestampArray => 1115, Inner::DateArray => 1182, Inner::TimeArray => 1183, Inner::Timestamptz => 1184, Inner::TimestamptzArray => 1185, Inner::Interval => 1186, Inner::IntervalArray => 1187, Inner::NumericArray => 1231, Inner::CstringArray => 1263, Inner::Timetz => 1266, Inner::TimetzArray => 1270, Inner::Bit => 1560, Inner::BitArray => 1561, Inner::Varbit => 1562, Inner::VarbitArray => 1563, Inner::Numeric => 1700, Inner::Refcursor => 1790, Inner::RefcursorArray => 2201, Inner::Regprocedure => 2202, Inner::Regoper => 2203, Inner::Regoperator => 2204, Inner::Regclass => 2205, Inner::Regtype => 2206, Inner::RegprocedureArray => 2207, Inner::RegoperArray => 2208, Inner::RegoperatorArray => 2209, Inner::RegclassArray => 2210, Inner::RegtypeArray => 2211, Inner::Record => 2249, Inner::Cstring => 2275, Inner::Any => 2276, Inner::Anyarray => 2277, Inner::Void => 2278, Inner::Trigger => 2279, Inner::LanguageHandler => 2280, Inner::Internal => 2281, Inner::Anyelement => 2283, Inner::RecordArray => 2287, Inner::Anynonarray => 2776, Inner::TxidSnapshotArray => 2949, Inner::Uuid => 2950, Inner::UuidArray => 2951, Inner::TxidSnapshot => 2970, Inner::FdwHandler => 3115, Inner::PgLsn => 3220, Inner::PgLsnArray => 3221, Inner::TsmHandler => 3310, Inner::PgNdistinct => 3361, Inner::PgDependencies => 3402, Inner::Anyenum => 3500, Inner::TsVector => 3614, Inner::Tsquery => 3615, Inner::GtsVector => 3642, Inner::TsVectorArray => 3643, Inner::GtsVectorArray => 3644, Inner::TsqueryArray => 3645, Inner::Regconfig => 3734, Inner::RegconfigArray => 3735, Inner::Regdictionary => 3769, Inner::RegdictionaryArray => 3770, Inner::Jsonb => 3802, Inner::JsonbArray => 3807, Inner::AnyRange => 3831, Inner::EventTrigger => 3838, Inner::Int4Range => 3904, Inner::Int4RangeArray => 3905, Inner::NumRange => 3906, Inner::NumRangeArray => 3907, Inner::TsRange => 3908, Inner::TsRangeArray => 3909, Inner::TstzRange => 3910, Inner::TstzRangeArray => 3911, Inner::DateRange => 3912, Inner::DateRangeArray => 3913, Inner::Int8Range => 3926, Inner::Int8RangeArray => 3927, Inner::Jsonpath => 4072, Inner::JsonpathArray => 4073, Inner::Regnamespace => 4089, Inner::RegnamespaceArray => 4090, Inner::Regrole => 4096, Inner::RegroleArray => 4097, Inner::Regcollation => 4191, Inner::RegcollationArray => 4192, Inner::Int4multiRange => 4451, Inner::NummultiRange => 4532, Inner::TsmultiRange => 4533, Inner::TstzmultiRange => 4534, Inner::DatemultiRange => 4535, Inner::Int8multiRange => 4536, Inner::AnymultiRange => 4537, Inner::AnycompatiblemultiRange => 4538, Inner::PgBrinBloomSummary => 4600, Inner::PgBrinMinmaxMultiSummary => 4601, Inner::PgMcvList => 5017, Inner::PgSnapshot => 5038, Inner::PgSnapshotArray => 5039, Inner::Xid8 => 5069, Inner::Anycompatible => 5077, Inner::Anycompatiblearray => 5078, Inner::Anycompatiblenonarray => 5079, Inner::AnycompatibleRange => 5080, Inner::Int4multiRangeArray => 6150, Inner::NummultiRangeArray => 6151, Inner::TsmultiRangeArray => 6152, Inner::TstzmultiRangeArray => 6153, Inner::DatemultiRangeArray => 6155, Inner::Int8multiRangeArray => 6157, Inner::Other(ref u) => u.oid, } } pub fn kind(&self) -> &Kind { match *self { Inner::Bool => &Kind::Simple, Inner::Bytea => &Kind::Simple, Inner::Char => &Kind::Simple, Inner::Name => &Kind::Simple, Inner::Int8 => &Kind::Simple, Inner::Int2 => &Kind::Simple, Inner::Int2Vector => &Kind::Array(Type(Inner::Int2)), Inner::Int4 => &Kind::Simple, Inner::Regproc => &Kind::Simple, Inner::Text => &Kind::Simple, Inner::Oid => &Kind::Simple, Inner::Tid => &Kind::Simple, Inner::Xid => &Kind::Simple, Inner::Cid => &Kind::Simple, Inner::OidVector => &Kind::Array(Type(Inner::Oid)), Inner::PgDdlCommand => &Kind::Pseudo, Inner::Json => &Kind::Simple, Inner::Xml => &Kind::Simple, Inner::XmlArray => &Kind::Array(Type(Inner::Xml)), Inner::PgNodeTree => &Kind::Simple, Inner::JsonArray => &Kind::Array(Type(Inner::Json)), Inner::TableAmHandler => &Kind::Pseudo, Inner::Xid8Array => &Kind::Array(Type(Inner::Xid8)), Inner::IndexAmHandler => &Kind::Pseudo, Inner::Point => &Kind::Simple, Inner::Lseg => &Kind::Simple, Inner::Path => &Kind::Simple, Inner::Box => &Kind::Simple, Inner::Polygon => &Kind::Simple, Inner::Line => &Kind::Simple, Inner::LineArray => &Kind::Array(Type(Inner::Line)), Inner::Cidr => &Kind::Simple, Inner::CidrArray => &Kind::Array(Type(Inner::Cidr)), Inner::Float4 => &Kind::Simple, Inner::Float8 => &Kind::Simple, Inner::Unknown => &Kind::Simple, Inner::Circle => &Kind::Simple, Inner::CircleArray => &Kind::Array(Type(Inner::Circle)), Inner::Macaddr8 => &Kind::Simple, Inner::Macaddr8Array => &Kind::Array(Type(Inner::Macaddr8)), Inner::Money => &Kind::Simple, Inner::MoneyArray => &Kind::Array(Type(Inner::Money)), Inner::Macaddr => &Kind::Simple, Inner::Inet => &Kind::Simple, Inner::BoolArray => &Kind::Array(Type(Inner::Bool)), Inner::ByteaArray => &Kind::Array(Type(Inner::Bytea)), Inner::CharArray => &Kind::Array(Type(Inner::Char)), Inner::NameArray => &Kind::Array(Type(Inner::Name)), Inner::Int2Array => &Kind::Array(Type(Inner::Int2)), Inner::Int2VectorArray => &Kind::Array(Type(Inner::Int2Vector)), Inner::Int4Array => &Kind::Array(Type(Inner::Int4)), Inner::RegprocArray => &Kind::Array(Type(Inner::Regproc)), Inner::TextArray => &Kind::Array(Type(Inner::Text)), Inner::TidArray => &Kind::Array(Type(Inner::Tid)), Inner::XidArray => &Kind::Array(Type(Inner::Xid)), Inner::CidArray => &Kind::Array(Type(Inner::Cid)), Inner::OidVectorArray => &Kind::Array(Type(Inner::OidVector)), Inner::BpcharArray => &Kind::Array(Type(Inner::Bpchar)), Inner::VarcharArray => &Kind::Array(Type(Inner::Varchar)), Inner::Int8Array => &Kind::Array(Type(Inner::Int8)), Inner::PointArray => &Kind::Array(Type(Inner::Point)), Inner::LsegArray => &Kind::Array(Type(Inner::Lseg)), Inner::PathArray => &Kind::Array(Type(Inner::Path)), Inner::BoxArray => &Kind::Array(Type(Inner::Box)), Inner::Float4Array => &Kind::Array(Type(Inner::Float4)), Inner::Float8Array => &Kind::Array(Type(Inner::Float8)), Inner::PolygonArray => &Kind::Array(Type(Inner::Polygon)), Inner::OidArray => &Kind::Array(Type(Inner::Oid)), Inner::Aclitem => &Kind::Simple, Inner::AclitemArray => &Kind::Array(Type(Inner::Aclitem)), Inner::MacaddrArray => &Kind::Array(Type(Inner::Macaddr)), Inner::InetArray => &Kind::Array(Type(Inner::Inet)), Inner::Bpchar => &Kind::Simple, Inner::Varchar => &Kind::Simple, Inner::Date => &Kind::Simple, Inner::Time => &Kind::Simple, Inner::Timestamp => &Kind::Simple, Inner::TimestampArray => &Kind::Array(Type(Inner::Timestamp)), Inner::DateArray => &Kind::Array(Type(Inner::Date)), Inner::TimeArray => &Kind::Array(Type(Inner::Time)), Inner::Timestamptz => &Kind::Simple, Inner::TimestamptzArray => &Kind::Array(Type(Inner::Timestamptz)), Inner::Interval => &Kind::Simple, Inner::IntervalArray => &Kind::Array(Type(Inner::Interval)), Inner::NumericArray => &Kind::Array(Type(Inner::Numeric)), Inner::CstringArray => &Kind::Array(Type(Inner::Cstring)), Inner::Timetz => &Kind::Simple, Inner::TimetzArray => &Kind::Array(Type(Inner::Timetz)), Inner::Bit => &Kind::Simple, Inner::BitArray => &Kind::Array(Type(Inner::Bit)), Inner::Varbit => &Kind::Simple, Inner::VarbitArray => &Kind::Array(Type(Inner::Varbit)), Inner::Numeric => &Kind::Simple, Inner::Refcursor => &Kind::Simple, Inner::RefcursorArray => &Kind::Array(Type(Inner::Refcursor)), Inner::Regprocedure => &Kind::Simple, Inner::Regoper => &Kind::Simple, Inner::Regoperator => &Kind::Simple, Inner::Regclass => &Kind::Simple, Inner::Regtype => &Kind::Simple, Inner::RegprocedureArray => &Kind::Array(Type(Inner::Regprocedure)), Inner::RegoperArray => &Kind::Array(Type(Inner::Regoper)), Inner::RegoperatorArray => &Kind::Array(Type(Inner::Regoperator)), Inner::RegclassArray => &Kind::Array(Type(Inner::Regclass)), Inner::RegtypeArray => &Kind::Array(Type(Inner::Regtype)), Inner::Record => &Kind::Pseudo, Inner::Cstring => &Kind::Pseudo, Inner::Any => &Kind::Pseudo, Inner::Anyarray => &Kind::Pseudo, Inner::Void => &Kind::Pseudo, Inner::Trigger => &Kind::Pseudo, Inner::LanguageHandler => &Kind::Pseudo, Inner::Internal => &Kind::Pseudo, Inner::Anyelement => &Kind::Pseudo, Inner::RecordArray => &Kind::Pseudo, Inner::Anynonarray => &Kind::Pseudo, Inner::TxidSnapshotArray => &Kind::Array(Type(Inner::TxidSnapshot)), Inner::Uuid => &Kind::Simple, Inner::UuidArray => &Kind::Array(Type(Inner::Uuid)), Inner::TxidSnapshot => &Kind::Simple, Inner::FdwHandler => &Kind::Pseudo, Inner::PgLsn => &Kind::Simple, Inner::PgLsnArray => &Kind::Array(Type(Inner::PgLsn)), Inner::TsmHandler => &Kind::Pseudo, Inner::PgNdistinct => &Kind::Simple, Inner::PgDependencies => &Kind::Simple, Inner::Anyenum => &Kind::Pseudo, Inner::TsVector => &Kind::Simple, Inner::Tsquery => &Kind::Simple, Inner::GtsVector => &Kind::Simple, Inner::TsVectorArray => &Kind::Array(Type(Inner::TsVector)), Inner::GtsVectorArray => &Kind::Array(Type(Inner::GtsVector)), Inner::TsqueryArray => &Kind::Array(Type(Inner::Tsquery)), Inner::Regconfig => &Kind::Simple, Inner::RegconfigArray => &Kind::Array(Type(Inner::Regconfig)), Inner::Regdictionary => &Kind::Simple, Inner::RegdictionaryArray => &Kind::Array(Type(Inner::Regdictionary)), Inner::Jsonb => &Kind::Simple, Inner::JsonbArray => &Kind::Array(Type(Inner::Jsonb)), Inner::AnyRange => &Kind::Pseudo, Inner::EventTrigger => &Kind::Pseudo, Inner::Int4Range => &Kind::Range(Type(Inner::Int4)), Inner::Int4RangeArray => &Kind::Array(Type(Inner::Int4Range)), Inner::NumRange => &Kind::Range(Type(Inner::Numeric)), Inner::NumRangeArray => &Kind::Array(Type(Inner::NumRange)), Inner::TsRange => &Kind::Range(Type(Inner::Timestamp)), Inner::TsRangeArray => &Kind::Array(Type(Inner::TsRange)), Inner::TstzRange => &Kind::Range(Type(Inner::Timestamptz)), Inner::TstzRangeArray => &Kind::Array(Type(Inner::TstzRange)), Inner::DateRange => &Kind::Range(Type(Inner::Date)), Inner::DateRangeArray => &Kind::Array(Type(Inner::DateRange)), Inner::Int8Range => &Kind::Range(Type(Inner::Int8)), Inner::Int8RangeArray => &Kind::Array(Type(Inner::Int8Range)), Inner::Jsonpath => &Kind::Simple, Inner::JsonpathArray => &Kind::Array(Type(Inner::Jsonpath)), Inner::Regnamespace => &Kind::Simple, Inner::RegnamespaceArray => &Kind::Array(Type(Inner::Regnamespace)), Inner::Regrole => &Kind::Simple, Inner::RegroleArray => &Kind::Array(Type(Inner::Regrole)), Inner::Regcollation => &Kind::Simple, Inner::RegcollationArray => &Kind::Array(Type(Inner::Regcollation)), Inner::Int4multiRange => &Kind::Multirange(Type(Inner::Int4)), Inner::NummultiRange => &Kind::Multirange(Type(Inner::Numeric)), Inner::TsmultiRange => &Kind::Multirange(Type(Inner::Timestamp)), Inner::TstzmultiRange => &Kind::Multirange(Type(Inner::Timestamptz)), Inner::DatemultiRange => &Kind::Multirange(Type(Inner::Date)), Inner::Int8multiRange => &Kind::Multirange(Type(Inner::Int8)), Inner::AnymultiRange => &Kind::Pseudo, Inner::AnycompatiblemultiRange => &Kind::Pseudo, Inner::PgBrinBloomSummary => &Kind::Simple, Inner::PgBrinMinmaxMultiSummary => &Kind::Simple, Inner::PgMcvList => &Kind::Simple, Inner::PgSnapshot => &Kind::Simple, Inner::PgSnapshotArray => &Kind::Array(Type(Inner::PgSnapshot)), Inner::Xid8 => &Kind::Simple, Inner::Anycompatible => &Kind::Pseudo, Inner::Anycompatiblearray => &Kind::Pseudo, Inner::Anycompatiblenonarray => &Kind::Pseudo, Inner::AnycompatibleRange => &Kind::Pseudo, Inner::Int4multiRangeArray => &Kind::Array(Type(Inner::Int4multiRange)), Inner::NummultiRangeArray => &Kind::Array(Type(Inner::NummultiRange)), Inner::TsmultiRangeArray => &Kind::Array(Type(Inner::TsmultiRange)), Inner::TstzmultiRangeArray => &Kind::Array(Type(Inner::TstzmultiRange)), Inner::DatemultiRangeArray => &Kind::Array(Type(Inner::DatemultiRange)), Inner::Int8multiRangeArray => &Kind::Array(Type(Inner::Int8multiRange)), Inner::Other(ref u) => &u.kind, } } pub fn name(&self) -> &str { match *self { Inner::Bool => "bool", Inner::Bytea => "bytea", Inner::Char => "char", Inner::Name => "name", Inner::Int8 => "int8", Inner::Int2 => "int2", Inner::Int2Vector => "int2vector", Inner::Int4 => "int4", Inner::Regproc => "regproc", Inner::Text => "text", Inner::Oid => "oid", Inner::Tid => "tid", Inner::Xid => "xid", Inner::Cid => "cid", Inner::OidVector => "oidvector", Inner::PgDdlCommand => "pg_ddl_command", Inner::Json => "json", Inner::Xml => "xml", Inner::XmlArray => "_xml", Inner::PgNodeTree => "pg_node_tree", Inner::JsonArray => "_json", Inner::TableAmHandler => "table_am_handler", Inner::Xid8Array => "_xid8", Inner::IndexAmHandler => "index_am_handler", Inner::Point => "point", Inner::Lseg => "lseg", Inner::Path => "path", Inner::Box => "box", Inner::Polygon => "polygon", Inner::Line => "line", Inner::LineArray => "_line", Inner::Cidr => "cidr", Inner::CidrArray => "_cidr", Inner::Float4 => "float4", Inner::Float8 => "float8", Inner::Unknown => "unknown", Inner::Circle => "circle", Inner::CircleArray => "_circle", Inner::Macaddr8 => "macaddr8", Inner::Macaddr8Array => "_macaddr8", Inner::Money => "money", Inner::MoneyArray => "_money", Inner::Macaddr => "macaddr", Inner::Inet => "inet", Inner::BoolArray => "_bool", Inner::ByteaArray => "_bytea", Inner::CharArray => "_char", Inner::NameArray => "_name", Inner::Int2Array => "_int2", Inner::Int2VectorArray => "_int2vector", Inner::Int4Array => "_int4", Inner::RegprocArray => "_regproc", Inner::TextArray => "_text", Inner::TidArray => "_tid", Inner::XidArray => "_xid", Inner::CidArray => "_cid", Inner::OidVectorArray => "_oidvector", Inner::BpcharArray => "_bpchar", Inner::VarcharArray => "_varchar", Inner::Int8Array => "_int8", Inner::PointArray => "_point", Inner::LsegArray => "_lseg", Inner::PathArray => "_path", Inner::BoxArray => "_box", Inner::Float4Array => "_float4", Inner::Float8Array => "_float8", Inner::PolygonArray => "_polygon", Inner::OidArray => "_oid", Inner::Aclitem => "aclitem", Inner::AclitemArray => "_aclitem", Inner::MacaddrArray => "_macaddr", Inner::InetArray => "_inet", Inner::Bpchar => "bpchar", Inner::Varchar => "varchar", Inner::Date => "date", Inner::Time => "time", Inner::Timestamp => "timestamp", Inner::TimestampArray => "_timestamp", Inner::DateArray => "_date", Inner::TimeArray => "_time", Inner::Timestamptz => "timestamptz", Inner::TimestamptzArray => "_timestamptz", Inner::Interval => "interval", Inner::IntervalArray => "_interval", Inner::NumericArray => "_numeric", Inner::CstringArray => "_cstring", Inner::Timetz => "timetz", Inner::TimetzArray => "_timetz", Inner::Bit => "bit", Inner::BitArray => "_bit", Inner::Varbit => "varbit", Inner::VarbitArray => "_varbit", Inner::Numeric => "numeric", Inner::Refcursor => "refcursor", Inner::RefcursorArray => "_refcursor", Inner::Regprocedure => "regprocedure", Inner::Regoper => "regoper", Inner::Regoperator => "regoperator", Inner::Regclass => "regclass", Inner::Regtype => "regtype", Inner::RegprocedureArray => "_regprocedure", Inner::RegoperArray => "_regoper", Inner::RegoperatorArray => "_regoperator", Inner::RegclassArray => "_regclass", Inner::RegtypeArray => "_regtype", Inner::Record => "record", Inner::Cstring => "cstring", Inner::Any => "any", Inner::Anyarray => "anyarray", Inner::Void => "void", Inner::Trigger => "trigger", Inner::LanguageHandler => "language_handler", Inner::Internal => "internal", Inner::Anyelement => "anyelement", Inner::RecordArray => "_record", Inner::Anynonarray => "anynonarray", Inner::TxidSnapshotArray => "_txid_snapshot", Inner::Uuid => "uuid", Inner::UuidArray => "_uuid", Inner::TxidSnapshot => "txid_snapshot", Inner::FdwHandler => "fdw_handler", Inner::PgLsn => "pg_lsn", Inner::PgLsnArray => "_pg_lsn", Inner::TsmHandler => "tsm_handler", Inner::PgNdistinct => "pg_ndistinct", Inner::PgDependencies => "pg_dependencies", Inner::Anyenum => "anyenum", Inner::TsVector => "tsvector", Inner::Tsquery => "tsquery", Inner::GtsVector => "gtsvector", Inner::TsVectorArray => "_tsvector", Inner::GtsVectorArray => "_gtsvector", Inner::TsqueryArray => "_tsquery", Inner::Regconfig => "regconfig", Inner::RegconfigArray => "_regconfig", Inner::Regdictionary => "regdictionary", Inner::RegdictionaryArray => "_regdictionary", Inner::Jsonb => "jsonb", Inner::JsonbArray => "_jsonb", Inner::AnyRange => "anyrange", Inner::EventTrigger => "event_trigger", Inner::Int4Range => "int4range", Inner::Int4RangeArray => "_int4range", Inner::NumRange => "numrange", Inner::NumRangeArray => "_numrange", Inner::TsRange => "tsrange", Inner::TsRangeArray => "_tsrange", Inner::TstzRange => "tstzrange", Inner::TstzRangeArray => "_tstzrange", Inner::DateRange => "daterange", Inner::DateRangeArray => "_daterange", Inner::Int8Range => "int8range", Inner::Int8RangeArray => "_int8range", Inner::Jsonpath => "jsonpath", Inner::JsonpathArray => "_jsonpath", Inner::Regnamespace => "regnamespace", Inner::RegnamespaceArray => "_regnamespace", Inner::Regrole => "regrole", Inner::RegroleArray => "_regrole", Inner::Regcollation => "regcollation", Inner::RegcollationArray => "_regcollation", Inner::Int4multiRange => "int4multirange", Inner::NummultiRange => "nummultirange", Inner::TsmultiRange => "tsmultirange", Inner::TstzmultiRange => "tstzmultirange", Inner::DatemultiRange => "datemultirange", Inner::Int8multiRange => "int8multirange", Inner::AnymultiRange => "anymultirange", Inner::AnycompatiblemultiRange => "anycompatiblemultirange", Inner::PgBrinBloomSummary => "pg_brin_bloom_summary", Inner::PgBrinMinmaxMultiSummary => "pg_brin_minmax_multi_summary", Inner::PgMcvList => "pg_mcv_list", Inner::PgSnapshot => "pg_snapshot", Inner::PgSnapshotArray => "_pg_snapshot", Inner::Xid8 => "xid8", Inner::Anycompatible => "anycompatible", Inner::Anycompatiblearray => "anycompatiblearray", Inner::Anycompatiblenonarray => "anycompatiblenonarray", Inner::AnycompatibleRange => "anycompatiblerange", Inner::Int4multiRangeArray => "_int4multirange", Inner::NummultiRangeArray => "_nummultirange", Inner::TsmultiRangeArray => "_tsmultirange", Inner::TstzmultiRangeArray => "_tstzmultirange", Inner::DatemultiRangeArray => "_datemultirange", Inner::Int8multiRangeArray => "_int8multirange", Inner::Other(ref u) => &u.name, } } } impl Type { /// BOOL - boolean, 'true'/'false' pub const BOOL: Type = Type(Inner::Bool); /// BYTEA - variable-length string, binary values escaped pub const BYTEA: Type = Type(Inner::Bytea); /// CHAR - single character pub const CHAR: Type = Type(Inner::Char); /// NAME - 63-byte type for storing system identifiers pub const NAME: Type = Type(Inner::Name); /// INT8 - ~18 digit integer, 8-byte storage pub const INT8: Type = Type(Inner::Int8); /// INT2 - -32 thousand to 32 thousand, 2-byte storage pub const INT2: Type = Type(Inner::Int2); /// INT2VECTOR - array of int2, used in system tables pub const INT2_VECTOR: Type = Type(Inner::Int2Vector); /// INT4 - -2 billion to 2 billion integer, 4-byte storage pub const INT4: Type = Type(Inner::Int4); /// REGPROC - registered procedure pub const REGPROC: Type = Type(Inner::Regproc); /// TEXT - variable-length string, no limit specified pub const TEXT: Type = Type(Inner::Text); /// OID - object identifier(oid), maximum 4 billion pub const OID: Type = Type(Inner::Oid); /// TID - (block, offset), physical location of tuple pub const TID: Type = Type(Inner::Tid); /// XID - transaction id pub const XID: Type = Type(Inner::Xid); /// CID - command identifier type, sequence in transaction id pub const CID: Type = Type(Inner::Cid); /// OIDVECTOR - array of oids, used in system tables pub const OID_VECTOR: Type = Type(Inner::OidVector); /// PG_DDL_COMMAND - internal type for passing CollectedCommand pub const PG_DDL_COMMAND: Type = Type(Inner::PgDdlCommand); /// JSON - JSON stored as text pub const JSON: Type = Type(Inner::Json); /// XML - XML content pub const XML: Type = Type(Inner::Xml); /// XML[] pub const XML_ARRAY: Type = Type(Inner::XmlArray); /// PG_NODE_TREE - string representing an internal node tree pub const PG_NODE_TREE: Type = Type(Inner::PgNodeTree); /// JSON[] pub const JSON_ARRAY: Type = Type(Inner::JsonArray); /// TABLE_AM_HANDLER pub const TABLE_AM_HANDLER: Type = Type(Inner::TableAmHandler); /// XID8[] pub const XID8_ARRAY: Type = Type(Inner::Xid8Array); /// INDEX_AM_HANDLER - pseudo-type for the result of an index AM handler function pub const INDEX_AM_HANDLER: Type = Type(Inner::IndexAmHandler); /// POINT - geometric point '(x, y)' pub const POINT: Type = Type(Inner::Point); /// LSEG - geometric line segment '(pt1,pt2)' pub const LSEG: Type = Type(Inner::Lseg); /// PATH - geometric path '(pt1,...)' pub const PATH: Type = Type(Inner::Path); /// BOX - geometric box '(lower left,upper right)' pub const BOX: Type = Type(Inner::Box); /// POLYGON - geometric polygon '(pt1,...)' pub const POLYGON: Type = Type(Inner::Polygon); /// LINE - geometric line pub const LINE: Type = Type(Inner::Line); /// LINE[] pub const LINE_ARRAY: Type = Type(Inner::LineArray); /// CIDR - network IP address/netmask, network address pub const CIDR: Type = Type(Inner::Cidr); /// CIDR[] pub const CIDR_ARRAY: Type = Type(Inner::CidrArray); /// FLOAT4 - single-precision floating point number, 4-byte storage pub const FLOAT4: Type = Type(Inner::Float4); /// FLOAT8 - double-precision floating point number, 8-byte storage pub const FLOAT8: Type = Type(Inner::Float8); /// UNKNOWN - pseudo-type representing an undetermined type pub const UNKNOWN: Type = Type(Inner::Unknown); /// CIRCLE - geometric circle '(center,radius)' pub const CIRCLE: Type = Type(Inner::Circle); /// CIRCLE[] pub const CIRCLE_ARRAY: Type = Type(Inner::CircleArray); /// MACADDR8 - XX:XX:XX:XX:XX:XX:XX:XX, MAC address pub const MACADDR8: Type = Type(Inner::Macaddr8); /// MACADDR8[] pub const MACADDR8_ARRAY: Type = Type(Inner::Macaddr8Array); /// MONEY - monetary amounts, $d,ddd.cc pub const MONEY: Type = Type(Inner::Money); /// MONEY[] pub const MONEY_ARRAY: Type = Type(Inner::MoneyArray); /// MACADDR - XX:XX:XX:XX:XX:XX, MAC address pub const MACADDR: Type = Type(Inner::Macaddr); /// INET - IP address/netmask, host address, netmask optional pub const INET: Type = Type(Inner::Inet); /// BOOL[] pub const BOOL_ARRAY: Type = Type(Inner::BoolArray); /// BYTEA[] pub const BYTEA_ARRAY: Type = Type(Inner::ByteaArray); /// CHAR[] pub const CHAR_ARRAY: Type = Type(Inner::CharArray); /// NAME[] pub const NAME_ARRAY: Type = Type(Inner::NameArray); /// INT2[] pub const INT2_ARRAY: Type = Type(Inner::Int2Array); /// INT2VECTOR[] pub const INT2_VECTOR_ARRAY: Type = Type(Inner::Int2VectorArray); /// INT4[] pub const INT4_ARRAY: Type = Type(Inner::Int4Array); /// REGPROC[] pub const REGPROC_ARRAY: Type = Type(Inner::RegprocArray); /// TEXT[] pub const TEXT_ARRAY: Type = Type(Inner::TextArray); /// TID[] pub const TID_ARRAY: Type = Type(Inner::TidArray); /// XID[] pub const XID_ARRAY: Type = Type(Inner::XidArray); /// CID[] pub const CID_ARRAY: Type = Type(Inner::CidArray); /// OIDVECTOR[] pub const OID_VECTOR_ARRAY: Type = Type(Inner::OidVectorArray); /// BPCHAR[] pub const BPCHAR_ARRAY: Type = Type(Inner::BpcharArray); /// VARCHAR[] pub const VARCHAR_ARRAY: Type = Type(Inner::VarcharArray); /// INT8[] pub const INT8_ARRAY: Type = Type(Inner::Int8Array); /// POINT[] pub const POINT_ARRAY: Type = Type(Inner::PointArray); /// LSEG[] pub const LSEG_ARRAY: Type = Type(Inner::LsegArray); /// PATH[] pub const PATH_ARRAY: Type = Type(Inner::PathArray); /// BOX[] pub const BOX_ARRAY: Type = Type(Inner::BoxArray); /// FLOAT4[] pub const FLOAT4_ARRAY: Type = Type(Inner::Float4Array); /// FLOAT8[] pub const FLOAT8_ARRAY: Type = Type(Inner::Float8Array); /// POLYGON[] pub const POLYGON_ARRAY: Type = Type(Inner::PolygonArray); /// OID[] pub const OID_ARRAY: Type = Type(Inner::OidArray); /// ACLITEM - access control list pub const ACLITEM: Type = Type(Inner::Aclitem); /// ACLITEM[] pub const ACLITEM_ARRAY: Type = Type(Inner::AclitemArray); /// MACADDR[] pub const MACADDR_ARRAY: Type = Type(Inner::MacaddrArray); /// INET[] pub const INET_ARRAY: Type = Type(Inner::InetArray); /// BPCHAR - char(length), blank-padded string, fixed storage length pub const BPCHAR: Type = Type(Inner::Bpchar); /// VARCHAR - varchar(length), non-blank-padded string, variable storage length pub const VARCHAR: Type = Type(Inner::Varchar); /// DATE - date pub const DATE: Type = Type(Inner::Date); /// TIME - time of day pub const TIME: Type = Type(Inner::Time); /// TIMESTAMP - date and time pub const TIMESTAMP: Type = Type(Inner::Timestamp); /// TIMESTAMP[] pub const TIMESTAMP_ARRAY: Type = Type(Inner::TimestampArray); /// DATE[] pub const DATE_ARRAY: Type = Type(Inner::DateArray); /// TIME[] pub const TIME_ARRAY: Type = Type(Inner::TimeArray); /// TIMESTAMPTZ - date and time with time zone pub const TIMESTAMPTZ: Type = Type(Inner::Timestamptz); /// TIMESTAMPTZ[] pub const TIMESTAMPTZ_ARRAY: Type = Type(Inner::TimestamptzArray); /// INTERVAL - @ <number> <units>, time interval pub const INTERVAL: Type = Type(Inner::Interval); /// INTERVAL[] pub const INTERVAL_ARRAY: Type = Type(Inner::IntervalArray); /// NUMERIC[] pub const NUMERIC_ARRAY: Type = Type(Inner::NumericArray); /// CSTRING[] pub const CSTRING_ARRAY: Type = Type(Inner::CstringArray); /// TIMETZ - time of day with time zone pub const TIMETZ: Type = Type(Inner::Timetz); /// TIMETZ[] pub const TIMETZ_ARRAY: Type = Type(Inner::TimetzArray); /// BIT - fixed-length bit string pub const BIT: Type = Type(Inner::Bit); /// BIT[] pub const BIT_ARRAY: Type = Type(Inner::BitArray); /// VARBIT - variable-length bit string pub const VARBIT: Type = Type(Inner::Varbit); /// VARBIT[] pub const VARBIT_ARRAY: Type = Type(Inner::VarbitArray); /// NUMERIC - numeric(precision, decimal), arbitrary precision number pub const NUMERIC: Type = Type(Inner::Numeric); /// REFCURSOR - reference to cursor (portal name) pub const REFCURSOR: Type = Type(Inner::Refcursor); /// REFCURSOR[] pub const REFCURSOR_ARRAY: Type = Type(Inner::RefcursorArray); /// REGPROCEDURE - registered procedure (with args) pub const REGPROCEDURE: Type = Type(Inner::Regprocedure); /// REGOPER - registered operator pub const REGOPER: Type = Type(Inner::Regoper); /// REGOPERATOR - registered operator (with args) pub const REGOPERATOR: Type = Type(Inner::Regoperator); /// REGCLASS - registered class pub const REGCLASS: Type = Type(Inner::Regclass); /// REGTYPE - registered type pub const REGTYPE: Type = Type(Inner::Regtype); /// REGPROCEDURE[] pub const REGPROCEDURE_ARRAY: Type = Type(Inner::RegprocedureArray); /// REGOPER[] pub const REGOPER_ARRAY: Type = Type(Inner::RegoperArray); /// REGOPERATOR[] pub const REGOPERATOR_ARRAY: Type = Type(Inner::RegoperatorArray); /// REGCLASS[] pub const REGCLASS_ARRAY: Type = Type(Inner::RegclassArray); /// REGTYPE[] pub const REGTYPE_ARRAY: Type = Type(Inner::RegtypeArray); /// RECORD - pseudo-type representing any composite type pub const RECORD: Type = Type(Inner::Record); /// CSTRING - C-style string pub const CSTRING: Type = Type(Inner::Cstring); /// ANY - pseudo-type representing any type pub const ANY: Type = Type(Inner::Any); /// ANYARRAY - pseudo-type representing a polymorphic array type pub const ANYARRAY: Type = Type(Inner::Anyarray); /// VOID - pseudo-type for the result of a function with no real result pub const VOID: Type = Type(Inner::Void); /// TRIGGER - pseudo-type for the result of a trigger function pub const TRIGGER: Type = Type(Inner::Trigger); /// LANGUAGE_HANDLER - pseudo-type for the result of a language handler function pub const LANGUAGE_HANDLER: Type = Type(Inner::LanguageHandler); /// INTERNAL - pseudo-type representing an internal data structure pub const INTERNAL: Type = Type(Inner::Internal); /// ANYELEMENT - pseudo-type representing a polymorphic base type pub const ANYELEMENT: Type = Type(Inner::Anyelement); /// RECORD[] pub const RECORD_ARRAY: Type = Type(Inner::RecordArray); /// ANYNONARRAY - pseudo-type representing a polymorphic base type that is not an array pub const ANYNONARRAY: Type = Type(Inner::Anynonarray); /// TXID_SNAPSHOT[] pub const TXID_SNAPSHOT_ARRAY: Type = Type(Inner::TxidSnapshotArray); /// UUID - UUID datatype pub const UUID: Type = Type(Inner::Uuid); /// UUID[] pub const UUID_ARRAY: Type = Type(Inner::UuidArray); /// TXID_SNAPSHOT - txid snapshot pub const TXID_SNAPSHOT: Type = Type(Inner::TxidSnapshot); /// FDW_HANDLER - pseudo-type for the result of an FDW handler function pub const FDW_HANDLER: Type = Type(Inner::FdwHandler); /// PG_LSN - PostgreSQL LSN datatype pub const PG_LSN: Type = Type(Inner::PgLsn); /// PG_LSN[] pub const PG_LSN_ARRAY: Type = Type(Inner::PgLsnArray); /// TSM_HANDLER - pseudo-type for the result of a tablesample method function pub const TSM_HANDLER: Type = Type(Inner::TsmHandler); /// PG_NDISTINCT - multivariate ndistinct coefficients pub const PG_NDISTINCT: Type = Type(Inner::PgNdistinct); /// PG_DEPENDENCIES - multivariate dependencies pub const PG_DEPENDENCIES: Type = Type(Inner::PgDependencies); /// ANYENUM - pseudo-type representing a polymorphic base type that is an enum pub const ANYENUM: Type = Type(Inner::Anyenum); /// TSVECTOR - text representation for text search pub const TS_VECTOR: Type = Type(Inner::TsVector); /// TSQUERY - query representation for text search pub const TSQUERY: Type = Type(Inner::Tsquery); /// GTSVECTOR - GiST index internal text representation for text search pub const GTS_VECTOR: Type = Type(Inner::GtsVector); /// TSVECTOR[] pub const TS_VECTOR_ARRAY: Type = Type(Inner::TsVectorArray); /// GTSVECTOR[] pub const GTS_VECTOR_ARRAY: Type = Type(Inner::GtsVectorArray); /// TSQUERY[] pub const TSQUERY_ARRAY: Type = Type(Inner::TsqueryArray); /// REGCONFIG - registered text search configuration pub const REGCONFIG: Type = Type(Inner::Regconfig); /// REGCONFIG[] pub const REGCONFIG_ARRAY: Type = Type(Inner::RegconfigArray); /// REGDICTIONARY - registered text search dictionary pub const REGDICTIONARY: Type = Type(Inner::Regdictionary); /// REGDICTIONARY[] pub const REGDICTIONARY_ARRAY: Type = Type(Inner::RegdictionaryArray); /// JSONB - Binary JSON pub const JSONB: Type = Type(Inner::Jsonb); /// JSONB[] pub const JSONB_ARRAY: Type = Type(Inner::JsonbArray); /// ANYRANGE - pseudo-type representing a range over a polymorphic base type pub const ANY_RANGE: Type = Type(Inner::AnyRange); /// EVENT_TRIGGER - pseudo-type for the result of an event trigger function pub const EVENT_TRIGGER: Type = Type(Inner::EventTrigger); /// INT4RANGE - range of integers pub const INT4_RANGE: Type = Type(Inner::Int4Range); /// INT4RANGE[] pub const INT4_RANGE_ARRAY: Type = Type(Inner::Int4RangeArray); /// NUMRANGE - range of numerics pub const NUM_RANGE: Type = Type(Inner::NumRange); /// NUMRANGE[] pub const NUM_RANGE_ARRAY: Type = Type(Inner::NumRangeArray); /// TSRANGE - range of timestamps without time zone pub const TS_RANGE: Type = Type(Inner::TsRange); /// TSRANGE[] pub const TS_RANGE_ARRAY: Type = Type(Inner::TsRangeArray); /// TSTZRANGE - range of timestamps with time zone pub const TSTZ_RANGE: Type = Type(Inner::TstzRange); /// TSTZRANGE[] pub const TSTZ_RANGE_ARRAY: Type = Type(Inner::TstzRangeArray); /// DATERANGE - range of dates pub const DATE_RANGE: Type = Type(Inner::DateRange); /// DATERANGE[] pub const DATE_RANGE_ARRAY: Type = Type(Inner::DateRangeArray); /// INT8RANGE - range of bigints pub const INT8_RANGE: Type = Type(Inner::Int8Range); /// INT8RANGE[] pub const INT8_RANGE_ARRAY: Type = Type(Inner::Int8RangeArray); /// JSONPATH - JSON path pub const JSONPATH: Type = Type(Inner::Jsonpath); /// JSONPATH[] pub const JSONPATH_ARRAY: Type = Type(Inner::JsonpathArray); /// REGNAMESPACE - registered namespace pub const REGNAMESPACE: Type = Type(Inner::Regnamespace); /// REGNAMESPACE[] pub const REGNAMESPACE_ARRAY: Type = Type(Inner::RegnamespaceArray); /// REGROLE - registered role pub const REGROLE: Type = Type(Inner::Regrole); /// REGROLE[] pub const REGROLE_ARRAY: Type = Type(Inner::RegroleArray); /// REGCOLLATION - registered collation pub const REGCOLLATION: Type = Type(Inner::Regcollation); /// REGCOLLATION[] pub const REGCOLLATION_ARRAY: Type = Type(Inner::RegcollationArray); /// INT4MULTIRANGE - multirange of integers pub const INT4MULTI_RANGE: Type = Type(Inner::Int4multiRange); /// NUMMULTIRANGE - multirange of numerics pub const NUMMULTI_RANGE: Type = Type(Inner::NummultiRange); /// TSMULTIRANGE - multirange of timestamps without time zone pub const TSMULTI_RANGE: Type = Type(Inner::TsmultiRange); /// TSTZMULTIRANGE - multirange of timestamps with time zone pub const TSTZMULTI_RANGE: Type = Type(Inner::TstzmultiRange); /// DATEMULTIRANGE - multirange of dates pub const DATEMULTI_RANGE: Type = Type(Inner::DatemultiRange); /// INT8MULTIRANGE - multirange of bigints pub const INT8MULTI_RANGE: Type = Type(Inner::Int8multiRange); /// ANYMULTIRANGE - pseudo-type representing a polymorphic base type that is a multirange pub const ANYMULTI_RANGE: Type = Type(Inner::AnymultiRange); /// ANYCOMPATIBLEMULTIRANGE - pseudo-type representing a multirange over a polymorphic common type pub const ANYCOMPATIBLEMULTI_RANGE: Type = Type(Inner::AnycompatiblemultiRange); /// PG_BRIN_BLOOM_SUMMARY - BRIN bloom summary pub const PG_BRIN_BLOOM_SUMMARY: Type = Type(Inner::PgBrinBloomSummary); /// PG_BRIN_MINMAX_MULTI_SUMMARY - BRIN minmax-multi summary pub const PG_BRIN_MINMAX_MULTI_SUMMARY: Type = Type(Inner::PgBrinMinmaxMultiSummary); /// PG_MCV_LIST - multivariate MCV list pub const PG_MCV_LIST: Type = Type(Inner::PgMcvList); /// PG_SNAPSHOT - snapshot pub const PG_SNAPSHOT: Type = Type(Inner::PgSnapshot); /// PG_SNAPSHOT[] pub const PG_SNAPSHOT_ARRAY: Type = Type(Inner::PgSnapshotArray); /// XID8 - full transaction id pub const XID8: Type = Type(Inner::Xid8); /// ANYCOMPATIBLE - pseudo-type representing a polymorphic common type pub const ANYCOMPATIBLE: Type = Type(Inner::Anycompatible); /// ANYCOMPATIBLEARRAY - pseudo-type representing an array of polymorphic common type elements pub const ANYCOMPATIBLEARRAY: Type = Type(Inner::Anycompatiblearray); /// ANYCOMPATIBLENONARRAY - pseudo-type representing a polymorphic common type that is not an array pub const ANYCOMPATIBLENONARRAY: Type = Type(Inner::Anycompatiblenonarray); /// ANYCOMPATIBLERANGE - pseudo-type representing a range over a polymorphic common type pub const ANYCOMPATIBLE_RANGE: Type = Type(Inner::AnycompatibleRange); /// INT4MULTIRANGE[] pub const INT4MULTI_RANGE_ARRAY: Type = Type(Inner::Int4multiRangeArray); /// NUMMULTIRANGE[] pub const NUMMULTI_RANGE_ARRAY: Type = Type(Inner::NummultiRangeArray); /// TSMULTIRANGE[] pub const TSMULTI_RANGE_ARRAY: Type = Type(Inner::TsmultiRangeArray); /// TSTZMULTIRANGE[] pub const TSTZMULTI_RANGE_ARRAY: Type = Type(Inner::TstzmultiRangeArray); /// DATEMULTIRANGE[] pub const DATEMULTI_RANGE_ARRAY: Type = Type(Inner::DatemultiRangeArray); /// INT8MULTIRANGE[] pub const INT8MULTI_RANGE_ARRAY: Type = Type(Inner::Int8multiRangeArray); } postgres-types-0.2.6/src/uuid_08.rs000064400000000000000000000011471046102023000152560ustar 00000000000000use bytes::BytesMut; use postgres_protocol::types; use std::error::Error; use uuid_08::Uuid; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for Uuid { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let bytes = types::uuid_from_sql(raw)?; Ok(Uuid::from_bytes(bytes)) } accepts!(UUID); } impl ToSql for Uuid { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::uuid_to_sql(*self.as_bytes(), w); Ok(IsNull::No) } accepts!(UUID); to_sql_checked!(); } postgres-types-0.2.6/src/uuid_1.rs000064400000000000000000000011461046102023000151660ustar 00000000000000use bytes::BytesMut; use postgres_protocol::types; use std::error::Error; use uuid_1::Uuid; use crate::{FromSql, IsNull, ToSql, Type}; impl<'a> FromSql<'a> for Uuid { fn from_sql(_: &Type, raw: &[u8]) -> Result> { let bytes = types::uuid_from_sql(raw)?; Ok(Uuid::from_bytes(bytes)) } accepts!(UUID); } impl ToSql for Uuid { fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result> { types::uuid_to_sql(*self.as_bytes(), w); Ok(IsNull::No) } accepts!(UUID); to_sql_checked!(); }