-
-
Notifications
You must be signed in to change notification settings - Fork 261
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
feat: auto-generate type alignment (#[pgrx(alignment = "on")]) #1942
Merged
eeeebbbbrrrr
merged 1 commit into
pgcentralfoundation:develop
from
JamesGuthrie:jg/postgrestype-derive-alignment
Feb 26, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
//LICENSE Portions Copyright 2019-2021 ZomboDB, LLC. | ||
//LICENSE | ||
//LICENSE Portions Copyright 2021-2023 Technology Concepts & Design, Inc. | ||
//LICENSE | ||
//LICENSE Portions Copyright 2023-2023 PgCentral Foundation, Inc. <[email protected]> | ||
//LICENSE | ||
//LICENSE All rights reserved. | ||
//LICENSE | ||
//LICENSE Use of this source code is governed by the MIT license that can be found in the LICENSE file. | ||
use pgrx::prelude::*; | ||
use serde::*; | ||
|
||
#[derive(PostgresType, Serialize, Deserialize)] | ||
#[pgrx(alignment = "on")] | ||
pub struct AlignedTo4Bytes { | ||
v1: u32, | ||
v2: [u32; 3], | ||
} | ||
|
||
#[derive(PostgresType, Serialize, Deserialize)] | ||
#[pgrx(alignment = "on")] | ||
pub struct AlignedTo8Bytes { | ||
v1: u64, | ||
v2: [u64; 3], | ||
} | ||
|
||
#[derive(PostgresType, Serialize, Deserialize)] | ||
#[pgrx(alignment = "off")] | ||
pub struct NotAlignedTo8Bytes { | ||
v1: u64, | ||
v2: [u64; 3], | ||
} | ||
|
||
#[cfg(any(test, feature = "pg_test"))] | ||
#[pg_schema] | ||
mod tests { | ||
use pgrx::prelude::*; | ||
|
||
#[cfg(not(feature = "no-schema-generation"))] | ||
#[pg_test] | ||
fn test_alignment_is_correct() { | ||
let val = Spi::get_one::<String>(r#"SELECT typalign::text FROM pg_type WHERE typname = 'alignedto4bytes'"#).unwrap().unwrap(); | ||
|
||
assert!(val == "i"); | ||
|
||
let val = Spi::get_one::<String>(r#"SELECT typalign::text FROM pg_type WHERE typname = 'alignedto8bytes'"#).unwrap().unwrap(); | ||
|
||
assert!(val == "d"); | ||
|
||
let val = Spi::get_one::<String>(r#"SELECT typalign::text FROM pg_type WHERE typname = 'notalignedto8bytes'"#).unwrap().unwrap(); | ||
|
||
assert!(val == "i"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,13 +16,82 @@ | |
|
||
*/ | ||
use crate::mapping::RustSqlMapping; | ||
use crate::pgrx_attribute::{ArgValue, PgrxArg, PgrxAttribute}; | ||
use crate::pgrx_sql::PgrxSql; | ||
use crate::to_sql::entity::ToSqlConfigEntity; | ||
use crate::to_sql::ToSql; | ||
use crate::{SqlGraphEntity, SqlGraphIdentifier, TypeMatch}; | ||
use eyre::eyre; | ||
use proc_macro2::TokenStream; | ||
use quote::{format_ident, quote, ToTokens, TokenStreamExt}; | ||
use std::collections::BTreeSet; | ||
use syn::spanned::Spanned; | ||
use syn::{AttrStyle, Attribute, Lit}; | ||
|
||
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] | ||
pub enum Alignment { | ||
On, | ||
Off, | ||
} | ||
|
||
const INVALID_ATTR_CONTENT: &str = | ||
r#"expected `#[pgrx(alignment = align)]`, where `align` is "on", or "off""#; | ||
|
||
impl ToTokens for Alignment { | ||
fn to_tokens(&self, tokens: &mut TokenStream) { | ||
let value = match self { | ||
Alignment::On => format_ident!("On"), | ||
Alignment::Off => format_ident!("Off"), | ||
}; | ||
let quoted = quote! { | ||
::pgrx::pgrx_sql_entity_graph::Alignment::#value | ||
}; | ||
tokens.append_all(quoted); | ||
} | ||
} | ||
|
||
impl Alignment { | ||
pub fn from_attribute(attr: &Attribute) -> Result<Option<Self>, syn::Error> { | ||
if attr.style != AttrStyle::Outer { | ||
return Err(syn::Error::new( | ||
attr.span(), | ||
"#[pgrx(alignment = ..)] is only valid in an outer context", | ||
)); | ||
} | ||
|
||
let attr = attr.parse_args::<PgrxAttribute>()?; | ||
for arg in attr.args.iter() { | ||
let PgrxArg::NameValue(ref nv) = arg; | ||
if !nv.path.is_ident("alignment") { | ||
continue; | ||
} | ||
|
||
return match nv.value { | ||
ArgValue::Lit(Lit::Str(ref s)) => match s.value().as_ref() { | ||
"on" => Ok(Some(Self::On)), | ||
"off" => Ok(Some(Self::Off)), | ||
_ => Err(syn::Error::new(s.span(), INVALID_ATTR_CONTENT)), | ||
}, | ||
ArgValue::Path(ref p) => Err(syn::Error::new(p.span(), INVALID_ATTR_CONTENT)), | ||
ArgValue::Lit(ref l) => Err(syn::Error::new(l.span(), INVALID_ATTR_CONTENT)), | ||
}; | ||
} | ||
|
||
Ok(None) | ||
} | ||
|
||
pub fn from_attributes(attrs: &[Attribute]) -> Result<Self, syn::Error> { | ||
for attr in attrs { | ||
if attr.path().is_ident("pgrx") { | ||
if let Some(v) = Self::from_attribute(attr)? { | ||
return Ok(v); | ||
} | ||
} | ||
} | ||
Ok(Self::Off) | ||
} | ||
} | ||
|
||
use eyre::eyre; | ||
/// The output of a [`PostgresType`](crate::postgres_type::PostgresTypeDerive) from `quote::ToTokens::to_tokens`. | ||
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] | ||
pub struct PostgresTypeEntity { | ||
|
@@ -37,6 +106,7 @@ pub struct PostgresTypeEntity { | |
pub out_fn: &'static str, | ||
pub out_fn_module_path: String, | ||
pub to_sql_config: ToSqlConfigEntity, | ||
pub alignment: Option<usize>, | ||
} | ||
|
||
impl TypeMatch for PostgresTypeEntity { | ||
|
@@ -82,6 +152,7 @@ impl ToSql for PostgresTypeEntity { | |
out_fn, | ||
out_fn_module_path, | ||
in_fn, | ||
alignment, | ||
.. | ||
}) = item_node | ||
else { | ||
|
@@ -155,6 +226,24 @@ impl ToSql for PostgresTypeEntity { | |
schema = context.schema_prefix_for(&self_index), | ||
); | ||
|
||
let alignment = alignment | ||
.map(|alignment| { | ||
assert!(alignment.is_power_of_two()); | ||
let alignment = match alignment { | ||
1 => "char", | ||
2 => "int2", | ||
4 => "int4", | ||
8 => "double", | ||
_ => panic!("type '{name}' wants unsupported alignment '{alignment}'"), | ||
}; | ||
format!( | ||
",\n\ | ||
\tALIGNMENT = {}", | ||
alignment | ||
) | ||
}) | ||
.unwrap_or_default(); | ||
|
||
let materialized_type = format! { | ||
"\n\ | ||
-- {file}:{line}\n\ | ||
|
@@ -163,7 +252,7 @@ impl ToSql for PostgresTypeEntity { | |
\tINTERNALLENGTH = variable,\n\ | ||
\tINPUT = {schema_prefix_in_fn}{in_fn}, /* {in_fn_path} */\n\ | ||
\tOUTPUT = {schema_prefix_out_fn}{out_fn}, /* {out_fn_path} */\n\ | ||
\tSTORAGE = extended\n\ | ||
\tSTORAGE = extended{alignment}\n\ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is kinda icky, but it works. |
||
);\ | ||
", | ||
schema = context.schema_prefix_for(&self_index), | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure that this is the right way to expose the
Alignment
enum (no other modules do it this way). I didn't want to change the visibility of thepostgres_type
module to global, for fear of leaking other types which we don't want to.