Skip to content

Commit

Permalink
feat: allow a USING clause for alter table column type in postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
jpopesculian committed Dec 20, 2024
1 parent 605ec44 commit 7c861e3
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/backend/postgres/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ impl TableBuilder for PostgresQueryBuilder {
if !first
&& !matches!(
column_spec,
ColumnSpec::AutoIncrement | ColumnSpec::Generated { .. }
ColumnSpec::AutoIncrement
| ColumnSpec::Generated { .. }
| ColumnSpec::Using(_)
)
{
write!(sql, ", ").unwrap();
Expand Down Expand Up @@ -180,6 +182,10 @@ impl TableBuilder for PostgresQueryBuilder {
ColumnSpec::Generated { .. } => {}
ColumnSpec::Extra(string) => write!(sql, "{string}").unwrap(),
ColumnSpec::Comment(_) => {}
ColumnSpec::Using(expr) => {
write!(sql, " USING ").unwrap();
QueryBuilder::prepare_simple_expr(self, expr, sql);
}
}
false
});
Expand Down
1 change: 1 addition & 0 deletions src/backend/table_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ pub trait TableBuilder:
}
ColumnSpec::Extra(string) => write!(sql, "{string}").unwrap(),
ColumnSpec::Comment(comment) => self.column_comment(comment, sql),
ColumnSpec::Using(_) => {}
}
}

Expand Down
29 changes: 29 additions & 0 deletions src/table/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ pub enum ColumnSpec {
Generated { expr: SimpleExpr, stored: bool },
Extra(String),
Comment(String),
Using(SimpleExpr),
}

// All interval fields
Expand Down Expand Up @@ -721,6 +722,34 @@ impl ColumnDef {
self
}

/// Some extra options in custom string
/// ```
/// use sea_query::{tests_cfg::*, *};
/// let table = Table::alter()
/// .table(Char::Table)
/// .modify_column(
/// ColumnDef::new(Char::Id)
/// .integer()
/// .using(Expr::col(Char::Id).cast_as(Alias::new("integer"))),
/// )
/// .to_owned();
/// assert_eq!(
/// table.to_string(PostgresQueryBuilder),
/// [
/// r#"ALTER TABLE "character""#,
/// r#"ALTER COLUMN "id" TYPE integer USING CAST("id" AS integer)"#,
/// ]
/// .join(" ")
/// );
/// ```
pub fn using<T>(&mut self, value: T) -> &mut Self
where
T: Into<SimpleExpr>,
{
self.spec.push(ColumnSpec::Using(value.into()));
self
}

/// MySQL only.
pub fn comment<T>(&mut self, string: T) -> &mut Self
where
Expand Down

0 comments on commit 7c861e3

Please sign in to comment.