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

PostgreSQL Ipnetwork support #2395

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ serde = { version = "1.0", default-features = false }
serde_json = { version = "1.0", default-features = false, optional = true }
sqlx = { version = "0.8.2", default-features = false, optional = true }
uuid = { version = "1", default-features = false, optional = true }
ipnetwork = { version = "0.20", default-features = false, optional = true }
ouroboros = { version = "0.18", default-features = false }
url = { version = "2.2", default-features = false }
thiserror = { version = "1", default-features = false }
Expand Down Expand Up @@ -72,6 +73,7 @@ default = [
"with-bigdecimal",
"with-uuid",
"with-time",
"with-ipnetwork",
]
macros = ["sea-orm-macros/derive"]
mock = []
Expand All @@ -82,6 +84,7 @@ with-rust_decimal = ["rust_decimal", "sea-query/with-rust_decimal", "sea-query-b
with-bigdecimal = ["bigdecimal", "sea-query/with-bigdecimal", "sea-query-binder?/with-bigdecimal", "sqlx?/bigdecimal"]
with-uuid = ["uuid", "sea-query/with-uuid", "sea-query-binder?/with-uuid", "sqlx?/uuid"]
with-time = ["time", "sea-query/with-time", "sea-query-binder?/with-time", "sqlx?/time"]
with-ipnetwork = ["ipnetwork", "sea-query/with-ipnetwork", "sea-query-binder?/with-ipnetwork", "sqlx?/ipnetwork"]
postgres-array = ["sea-query/postgres-array", "sea-query-binder?/postgres-array", "sea-orm-macros/postgres-array"]
json-array = ["postgres-array"] # this does not actually enable sqlx-postgres, but only a few traits to support array in sea-query
sea-orm-internal = []
Expand Down
12 changes: 7 additions & 5 deletions sea-orm-codegen/src/entity/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,10 @@ impl Column {
ColumnType::Bit(None | Some(1)) => "bool".to_owned(),
ColumnType::Bit(_) | ColumnType::VarBit(_) => "Vec<u8>".to_owned(),
ColumnType::Year => "i32".to_owned(),
ColumnType::Interval(_, _)
| ColumnType::Cidr
| ColumnType::Inet
| ColumnType::MacAddr
| ColumnType::LTree => "String".to_owned(),
ColumnType::Cidr | ColumnType::Inet => "IpNetwork".to_owned(),
ColumnType::Interval(_, _) | ColumnType::MacAddr | ColumnType::LTree => {
"String".to_owned()
}
_ => unimplemented!(),
}
}
Expand Down Expand Up @@ -112,6 +111,7 @@ impl Column {
StringLen::Max => Some("VarBinary(StringLen::Max)".to_owned()),
},
ColumnType::Blob => Some("Blob".to_owned()),
ColumnType::Cidr => Some("Cidr".to_owned()),
_ => None,
};
col_type.map(|ty| quote! { column_type = #ty })
Expand Down Expand Up @@ -168,6 +168,8 @@ impl Column {
ColumnType::Json => quote! { ColumnType::Json },
ColumnType::JsonBinary => quote! { ColumnType::JsonBinary },
ColumnType::Uuid => quote! { ColumnType::Uuid },
ColumnType::Cidr => quote! { ColumnType::Cidr },
ColumnType::Inet => quote! { ColumnType::Inet },
ColumnType::Custom(s) => {
let s = s.to_string();
quote! { ColumnType::custom(#s) }
Expand Down
1 change: 1 addition & 0 deletions sea-orm-migration/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,4 @@ with-rust_decimal = ["sea-orm/with-rust_decimal"]
with-bigdecimal = ["sea-orm/with-bigdecimal"]
with-uuid = ["sea-orm/with-uuid"]
with-time = ["sea-orm/with-time"]
with-ipnetwork = ["sea-orm/with-ipnetwork"]
4 changes: 4 additions & 0 deletions src/entity/active_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,10 @@ impl_into_active_value!(crate::prelude::TimeDateTime);
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
impl_into_active_value!(crate::prelude::TimeDateTimeWithTimeZone);

#[cfg(feature = "with-ipnetwork")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-ipnetwork")))]
impl_into_active_value!(crate::prelude::IpNetwork);

impl<V> Default for ActiveValue<V>
where
V: Into<Value>,
Expand Down
3 changes: 3 additions & 0 deletions src/entity/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,6 @@ pub use bigdecimal::BigDecimal;

#[cfg(feature = "with-uuid")]
pub use uuid::Uuid;

#[cfg(feature = "with-ipnetwork")]
pub use ipnetwork::IpNetwork;
51 changes: 51 additions & 0 deletions src/executor/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,48 @@ macro_rules! try_getable_mysql {
};
}

#[allow(unused_macros)]
macro_rules! try_getable_postgres {
( $type: ty ) => {
impl TryGetable for $type {
#[allow(unused_variables)]
fn try_get_by<I: ColIdx>(res: &QueryResult, idx: I) -> Result<Self, TryGetError> {
match &res.row {
#[cfg(feature = "sqlx-mysql")]
QueryResultRow::SqlxMySql(_) => Err(type_err(format!(
"{} unsupported by sqlx-mysql",
stringify!($type)
))
.into()),
#[cfg(feature = "sqlx-postgres")]
QueryResultRow::SqlxPostgres(row) => row
.try_get::<Option<$type>, _>(idx.as_sqlx_postgres_index())
.map_err(|e| sqlx_error_to_query_err(e).into())
.and_then(|opt| opt.ok_or_else(|| err_null_idx_col(idx))),
#[cfg(feature = "sqlx-sqlite")]
QueryResultRow::SqlxSqlite(_) => Err(type_err(format!(
"{} unsupported by sqlx-sqlite",
stringify!($type)
))
.into()),
#[cfg(feature = "mock")]
QueryResultRow::Mock(row) => row.try_get(idx).map_err(|e| {
debug_print!("{:#?}", e.to_string());
err_null_idx_col(idx)
}),
#[cfg(feature = "proxy")]
QueryResultRow::Proxy(row) => row.try_get(idx).map_err(|e| {
debug_print!("{:#?}", e.to_string());
err_null_idx_col(idx)
}),
#[allow(unreachable_patterns)]
_ => unreachable!(),
}
}
}
};
}

#[allow(unused_macros)]
macro_rules! try_getable_date_time {
( $type: ty ) => {
Expand Down Expand Up @@ -662,6 +704,9 @@ try_getable_uuid!(uuid::fmt::Simple, uuid::Uuid::simple);
#[cfg(feature = "with-uuid")]
try_getable_uuid!(uuid::fmt::Urn, uuid::Uuid::urn);

#[cfg(feature = "with-ipnetwork")]
try_getable_postgres!(ipnetwork::IpNetwork);

impl TryGetable for u32 {
#[allow(unused_variables)]
fn try_get_by<I: ColIdx>(res: &QueryResult, idx: I) -> Result<Self, TryGetError> {
Expand Down Expand Up @@ -850,6 +895,9 @@ mod postgres_array {
#[cfg(feature = "with-bigdecimal")]
try_getable_postgres_array!(bigdecimal::BigDecimal);

#[cfg(feature = "with-ipnetwork")]
try_getable_postgres_array!(ipnetwork::IpNetwork);

#[allow(unused_macros)]
macro_rules! try_getable_postgres_array_uuid {
( $type: ty, $conversion_fn: expr ) => {
Expand Down Expand Up @@ -1338,6 +1386,9 @@ try_from_u64_err!(rust_decimal::Decimal);
#[cfg(feature = "with-uuid")]
try_from_u64_err!(uuid::Uuid);

#[cfg(feature = "with-ipnetwork")]
try_from_u64_err!(ipnetwork::IpNetwork);

#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
Expand Down
4 changes: 4 additions & 0 deletions src/query/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@ impl FromQueryResult for JsonValue {
try_get_type!(uuid::Uuid, col);
#[cfg(all(feature = "with-uuid", feature = "postgres-array"))]
try_get_type!(Vec<uuid::Uuid>, col);
#[cfg(feature = "with-ipnetwork")]
try_get_type!(ipnetwork::IpNetwork, col);
#[cfg(all(feature = "with-ipnetwork", feature = "postgres-array"))]
try_get_type!(Vec<ipnetwork::IpNetwork>, col);
try_get_type!(Vec<u8>, col);
}
Ok(JsonValue::Object(map))
Expand Down
17 changes: 17 additions & 0 deletions tests/common/features/host_network.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "host_network")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub hostname: String,
pub ipaddress: IpNetwork,
#[sea_orm(column_type = "Cidr")]
pub network: IpNetwork,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
2 changes: 2 additions & 0 deletions tests/common/features/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod custom_active_model;
pub mod dyn_table_name_lazy_static;
pub mod edit_log;
pub mod event_trigger;
pub mod host_network;
pub mod insert_default;
pub mod json_struct;
pub mod json_vec;
Expand Down Expand Up @@ -41,6 +42,7 @@ pub use collection_expanded::Entity as CollectionExpanded;
pub use dyn_table_name_lazy_static::Entity as DynTableNameLazyStatic;
pub use edit_log::Entity as EditLog;
pub use event_trigger::Entity as EventTrigger;
pub use host_network::Entity as HostNetwork;
pub use insert_default::Entity as InsertDefault;
pub use json_struct::Entity as JsonStruct;
pub use json_vec::Entity as JsonVec;
Expand Down
31 changes: 31 additions & 0 deletions tests/common/features/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ pub async fn create_tables(db: &DatabaseConnection) -> Result<(), DbErr> {
create_collection_table(db).await?;
create_event_trigger_table(db).await?;
create_categories_table(db).await?;
create_host_network_table(db).await?;
}

Ok(())
Expand Down Expand Up @@ -471,6 +472,36 @@ pub async fn create_collection_table(db: &DbConn) -> Result<ExecResult, DbErr> {
create_table(db, &stmt, Collection).await
}

pub async fn create_host_network_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(host_network::Entity)
.col(
ColumnDef::new(host_network::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(host_network::Column::Hostname)
.string()
.not_null(),
)
.col(
ColumnDef::new(host_network::Column::Ipaddress)
.inet()
.not_null(),
)
.col(
ColumnDef::new(host_network::Column::Network)
.cidr()
.not_null(),
)
.to_owned();

create_table(db, &stmt, HostNetwork).await
}

pub async fn create_pi_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(pi::Entity)
Expand Down
64 changes: 64 additions & 0 deletions tests/host_network_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#![allow(unused_imports, dead_code)]

pub mod common;

use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use std::net::{Ipv4Addr, Ipv6Addr};

#[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")]
async fn main() -> Result<(), DbErr> {
let ctx = TestContext::new("host_network_tests").await;
create_tables(&ctx.db).await?;
create_and_update_host_network(&ctx.db).await?;
ctx.delete().await;

Ok(())
}

async fn create_and_update_host_network(db: &DatabaseConnection) -> Result<(), DbErr> {
let addr = IpNetwork::new(Ipv4Addr::new(192, 168, 0, 20).into(), 24).unwrap();
let net = IpNetwork::new(addr.network(), addr.prefix()).unwrap();

let host = host_network::Model {
id: 1,
hostname: "example.com".to_owned(),
ipaddress: addr,
network: net,
};
let res = host.clone().into_active_model().insert(db).await?;

let model = HostNetwork::find().one(db).await?.unwrap();
assert_eq!(model, res);
assert_eq!(model, host.clone());

let addrv6 = IpNetwork::new(
Ipv6Addr::new(0xfd89, 0x1926, 0x4cae, 0x8abd, 0, 0, 0, 0x6f52).into(),
64,
)
.unwrap();
let netv6 = IpNetwork::new(addr.network(), addr.prefix()).unwrap();

let res = host_network::ActiveModel {
id: Set(1),
ipaddress: Set(addrv6),
network: Set(netv6),
..Default::default()
}
.update(db)
.await?;

assert_eq!(
res,
host_network::Model {
id: 1,
hostname: "example.com".to_owned(),
ipaddress: addrv6,
network: netv6,
}
);

Ok(())
}
1 change: 1 addition & 0 deletions tests/type_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,5 @@ fn main() {
it_impl_traits!(time::OffsetDateTime);
it_impl_traits!(rust_decimal::Decimal);
it_impl_traits!(uuid::Uuid);
it_impl_traits!(ipnetwork::IpNetwork);
}