Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for IpAddr #1822

Merged
merged 1 commit into from
Jun 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions sqlx-core/src/postgres/types/ipaddr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use std::net::IpAddr;

use ipnetwork::IpNetwork;
abonander marked this conversation as resolved.
Show resolved Hide resolved

use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::postgres::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef, Postgres};
use crate::types::Type;

impl Type<Postgres> for IpAddr
where
IpNetwork: Type<Postgres>,
{
fn type_info() -> PgTypeInfo {
IpNetwork::type_info()
}

fn compatible(ty: &PgTypeInfo) -> bool {
IpNetwork::compatible(ty)
}
}

impl PgHasArrayType for IpAddr {
fn array_type_info() -> PgTypeInfo {
<IpNetwork as PgHasArrayType>::array_type_info()
}

fn array_compatible(ty: &PgTypeInfo) -> bool {
<IpNetwork as PgHasArrayType>::array_compatible(ty)
}
}

impl<'db> Encode<'db, Postgres> for IpAddr
where
IpNetwork: Encode<'db, Postgres>,
{
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
IpNetwork::from(*self).encode_by_ref(buf)
}

fn size_hint(&self) -> usize {
IpNetwork::from(*self).size_hint()
}
}

impl<'db> Decode<'db, Postgres> for IpAddr
where
IpNetwork: Decode<'db, Postgres>,
{
fn decode(value: PgValueRef<'db>) -> Result<Self, BoxDynError> {
let ipnetwork = IpNetwork::decode(value)?;

if ipnetwork.is_ipv4() && ipnetwork.prefix() != 32
|| ipnetwork.is_ipv6() && ipnetwork.prefix() != 128
{
Err("lossy decode from inet/cidr")?
}

Ok(ipnetwork.ip())
}
}
3 changes: 3 additions & 0 deletions sqlx-core/src/postgres/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ mod json;
#[cfg(feature = "ipnetwork")]
mod ipnetwork;

#[cfg(feature = "ipnetwork")]
abonander marked this conversation as resolved.
Show resolved Hide resolved
mod ipaddr;

#[cfg(feature = "mac_address")]
mod mac_address;

Expand Down