Skip to content

Commit

Permalink
Merge branch 'master' into active-enum-as-primary-key
Browse files Browse the repository at this point in the history
  • Loading branch information
billy1624 committed Jan 30, 2023
2 parents cdffe4e + 1e9eb0f commit 1af5191
Show file tree
Hide file tree
Showing 55 changed files with 688 additions and 520 deletions.
104 changes: 82 additions & 22 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,31 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### New Features

* Simple data loader https://github.com/SeaQL/sea-orm/pull/1238, https://github.com/SeaQL/sea-orm/pull/1368
* Transactions Isolation level and Access mode https://github.com/SeaQL/sea-orm/pull/1230
* [sea-orm-cli] Generate `#[serde(skip_deserializing)]` for primary key columns https://github.com/SeaQL/sea-orm/pull/846, https://github.com/SeaQL/sea-orm/pull/1186, https://github.com/SeaQL/sea-orm/pull/1318
* [sea-orm-cli] Generate `#[serde(skip)]` for hidden columns https://github.com/SeaQL/sea-orm/pull/1171, https://github.com/SeaQL/sea-orm/pull/1320
* [sea-orm-cli] Generate entity with extra derives and attributes for model struct https://github.com/SeaQL/sea-orm/pull/1124, https://github.com/SeaQL/sea-orm/pull/1321
* Added `sea-orm-internal` feature https://github.com/SeaQL/sea-orm/pull/1297
* Added `DatabaseConnection::get_*_connection_pool()` method to borrow the inner SQLx connection pool https://github.com/SeaQL/sea-orm/pull/1297
* Execute unprepared statements https://github.com/SeaQL/sea-orm/pull/1327
* Added `DatabaseConnection::execute_unprepared` method https://github.com/SeaQL/sea-orm/pull/1327
* Added `DatabaseTransaction::execute_unprepared` method https://github.com/SeaQL/sea-orm/pull/1327
* Added `Select::into_tuple` to select rows as tuples instead of having to define a custom Model https://github.com/SeaQL/sea-orm/pull/1311
* Simple data loader https://github.com/SeaQL/sea-orm/pull/1238, https://github.com/SeaQL/sea-orm/pull/1368
* Transactions Isolation level and Access mode https://github.com/SeaQL/sea-orm/pull/1230
* Support various UUID formats that are available in `uuid::fmt` module https://github.com/SeaQL/sea-orm/pull/1325
* Support Vector of enum for Postgres https://github.com/SeaQL/sea-orm/pull/1210
* Casting columns as a different data type on select, insert and update https://github.com/SeaQL/sea-orm/pull/1304
* Methods of `ActiveModelBehavior` receive db connection as the parameter https://github.com/SeaQL/sea-orm/pull/1145, https://github.com/SeaQL/sea-orm/pull/1328
* Methods of `ActiveModelBehavior` receive db connection as a parameter https://github.com/SeaQL/sea-orm/pull/1145, https://github.com/SeaQL/sea-orm/pull/1328
* Added `DatabaseConnection::get_*_connection_pool()` method to access the inner SQLx connection pool https://github.com/SeaQL/sea-orm/pull/1297
* Note: guarded by the `sea-orm-internal` feature flag
* Added `execute_unprepared` method to `DatabaseConnection` and `DatabaseTransaction` https://github.com/SeaQL/sea-orm/pull/1327
* Added `Select::into_tuple` to select rows as tuples (instead of defining a custom Model) https://github.com/SeaQL/sea-orm/pull/1311

### Enhancements

* Support Vector of enum for Postgres https://github.com/SeaQL/sea-orm/pull/1210
* Added `DatabaseConnection::close` https://github.com/SeaQL/sea-orm/pull/1236
* Refactor schema module to expose functions for database alteration https://github.com/SeaQL/sea-orm/pull/1256
* Added `is_null` getter for `ColumnDef` struct https://github.com/SeaQL/sea-orm/pull/1381
* Generate compact entity with `#[sea_orm(column_type = "JsonBinary")]` macro attribute https://github.com/SeaQL/sea-orm/pull/1346
* `MockDatabase::append_exec_results()`, `MockDatabase::append_query_results()`, `MockDatabase::append_exec_errors()` and `MockDatabase::append_query_errors()` take any types implemented `IntoIterator` trait https://github.com/SeaQL/sea-orm/pull/1367
* `find_by_id` and `delete_by_id` take any Into primary key value https://github.com/SeaQL/sea-orm/pull/1362
* `find_by_id` and `delete_by_id` take any `Into` primary key value https://github.com/SeaQL/sea-orm/pull/1362
* `QuerySelect::offset` and `QuerySelect::limit` takes in `Into<Option<u64>>` where `None` would reset them https://github.com/SeaQL/sea-orm/pull/1410
* Added `DatabaseConnection::close` https://github.com/SeaQL/sea-orm/pull/1236
* Added `is_null` getter for `ColumnDef` https://github.com/SeaQL/sea-orm/pull/1381
* Added `ActiveValue::reset` to convert `Unchanged` into `Set` https://github.com/SeaQL/sea-orm/pull/1177
* Generate compact entity with `#[sea_orm(column_type = "JsonBinary")]` macro attribute https://github.com/SeaQL/sea-orm/pull/1346
* Added `QueryTrait::apply_if` to optionally apply a filter https://github.com/SeaQL/sea-orm/pull/1415

### Upgrades

Expand All @@ -48,20 +48,26 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
* Changed all version = "^x.y.z" into version = "x.y.z" and disabled default features and enable only the needed ones https://github.com/SeaQL/sea-orm/pull/1300
* Cleanup the use of `vec!` macros https://github.com/SeaQL/sea-orm/pull/1367
* Fixed a small typo https://github.com/SeaQL/sea-orm/pull/1391
* `axum` example should use tokio runtime https://github.com/SeaQL/sea-orm/pull/1428
* Fixed all clippy warnings as of `1.67.0` https://github.com/SeaQL/sea-orm/pull/1426

### Bug Fixes

* [sea-orm-cli] Propagate error on the spawned child processes https://github.com/SeaQL/sea-orm/pull/1402
* Fixes sea-orm-cli errors exit with error code 0 https://github.com/SeaQL/sea-orm/issues/1342
* Fixes `DeriveColumn` (by qualifying `IdenStatic::as_str`) https://github.com/SeaQL/sea-orm/pull/1280
* Prevent returning connections to pool with a positive transaction depth https://github.com/SeaQL/sea-orm/pull/1283
* Postgres insert many will throw `RecordNotInserted` error if non of them are being inserted https://github.com/SeaQL/sea-orm/pull/1021
* Fixes inserting active models by `insert_many` with `on_conflict` and `do_nothing` panics if no rows are inserted on Postgres https://github.com/SeaQL/sea-orm/issues/899
* Don't call `last_insert_id` if not needed https://github.com/SeaQL/sea-orm/pull/1403
* Fixes hitting 'negative last_insert_rowid' panic with Sqlite https://github.com/SeaQL/sea-orm/issues/1357
* [sea-orm-cli] Propagate error on the spawned child processes https://github.com/SeaQL/sea-orm/pull/1402
* Fixes sea-orm-cli errors exit with error code 0 https://github.com/SeaQL/sea-orm/issues/1342
* Noop when update without providing any values https://github.com/SeaQL/sea-orm/pull/1384
* Fixes Syntax Error when saving active model that sets nothing https://github.com/SeaQL/sea-orm/pull/1376

### Breaking changes

* [sea-orm-cli] Enable --universal-time by default https://github.com/SeaQL/sea-orm/pull/1420
* Added `RecordNotInserted` and `RecordNotUpdated` to `DbErr`
* Added `ConnectionTrait::execute_unprepared` method https://github.com/SeaQL/sea-orm/pull/1327
* As part of https://github.com/SeaQL/sea-orm/pull/1311, the required method of `TryGetable` changed:
```rust
Expand All @@ -70,13 +76,20 @@ fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TryGetError>
// now; ColIdx can be `&str` or `usize`
fn try_get_by<I: ColIdx>(res: &QueryResult, index: I) -> Result<Self, TryGetError>;
```
* The `ActiveModelBehaviour` trait becomes async trait https://github.com/SeaQL/sea-orm/pull/1328
So if you implemented it yourself:
```patch
impl TryGetable for XXX {
- fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TryGetError> {
+ fn try_get_by<I: sea_orm::ColIdx>(res: &QueryResult, idx: I) -> Result<Self, TryGetError> {
- let value: YYY = res.try_get(pre, col).map_err(TryGetError::DbErr)?;
+ let value: YYY = res.try_get_by(idx).map_err(TryGetError::DbErr)?;
..
}
}
```
* The `ActiveModelBehaviour` trait becomes async trait https://github.com/SeaQL/sea-orm/pull/1328.
If you overridden the default `ActiveModelBehaviour` implementation:
```rust
// For anyone who implement the `ActiveModelBehaviour` with default implementation (no*op).
// No code changes is required.
impl ActiveModelBehavior for ActiveModel {}

// However, if you overridden the default implementation:
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(self, db: &C, insert: bool) -> Result<Self, DbErr>
Expand All @@ -89,6 +102,53 @@ impl ActiveModelBehavior for ActiveModel {
// ...
}
```
* `DbErr::RecordNotFound("None of the database rows are affected")` is moved to a dedicated error variant `DbErr::RecordNotUpdated` https://github.com/SeaQL/sea-orm/pull/1425
```rust
let res = Update::one(cake::ActiveModel {
name: Set("Cheese Cake".to_owned()),
..model.into_active_model()
})
.exec(&db)
.await;

// then
assert_eq!(
res,
Err(DbErr::RecordNotFound(
"None of the database rows are affected".to_owned()
))
);

// now
assert_eq!(res, Err(DbErr::RecordNotUpdated));
```
* `sea_orm::ColumnType` was replaced by `sea_query::ColumnType` https://github.com/SeaQL/sea-orm/pull/1395
* Method `ColumnType::def` was moved to `ColumnTypeTrait`
* `ColumnType::Binary` becomes a tuple variant which takes in additional option `sea_query::BlobSize`
* `ColumnType::Custom` takes a `sea_query::DynIden` instead of `String` and thus a new method `custom` is added (note the lowercase)
```diff
// Compact Entity
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "fruit")]
pub struct Model {
- #[sea_orm(column_type = r#"Custom("citext".to_owned())"#)]
+ #[sea_orm(column_type = r#"custom("citext")"#)]
pub column: String,
}
```
```diff
// Expanded Entity
impl ColumnTrait for Column {
type EntityName = Entity;

fn def(&self) -> ColumnDef {
match self {
- Self::Column => ColumnType::Custom("citext".to_owned()).def(),
+ Self::Column => ColumnType::custom("citext").def(),
}
}
}
```

## 0.10.7 - 2023-01-19

Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ tracing = { version = "0.1", default-features = false, features = ["attributes",
rust_decimal = { version = "1", default-features = false, optional = true }
bigdecimal = { version = "0.3", default-features = false, optional = true }
sea-orm-macros = { version = "0.10.3", path = "sea-orm-macros", default-features = false, optional = true }
sea-query = { version = "0.28", features = ["thread-safe"] }
sea-query = { version = "0.28.3", features = ["thread-safe"] }
sea-query-binder = { version = "0.3", default-features = false, optional = true }
sea-strum = { version = "0.23", default-features = false, features = ["derive", "sea-orm"] }
serde = { version = "1.0", default-features = false }
Expand Down
2 changes: 1 addition & 1 deletion examples/axum_example/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ path = "../../../" # remove this line in your own project
version = "0.10.3" # sea-orm version
features = [
"debug-print",
"runtime-async-std-native-tls",
"runtime-tokio-native-tls",
"sqlx-postgres",
# "sqlx-mysql",
# "sqlx-sqlite",
Expand Down
10 changes: 9 additions & 1 deletion examples/basic/src/example_cake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,12 @@ impl Related<super::filling::Entity> for Entity {
}
}

impl ActiveModelBehavior for ActiveModel {}
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
Ok(self)
}
}
5 changes: 4 additions & 1 deletion sea-orm-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
[package]
name = "sea-orm-cli"
version = "0.10.3"
authors = ["Billy Chan <[email protected]>"]
authors = [
"Chris Tsang <[email protected]>",
"Billy Chan <[email protected]>",
]
edition = "2021"
description = "Command line utility for SeaORM"
license = "MIT OR Apache-2.0"
Expand Down
88 changes: 74 additions & 14 deletions sea-orm-cli/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,41 @@
use clap::{ArgEnum, ArgGroup, Parser, Subcommand};

#[derive(Parser, Debug)]
#[clap(version)]
#[clap(
version,
author,
help_template = r#"{before-help}{name} {version}
{about-with-newline}
{usage-heading} {usage}
{all-args}{after-help}
AUTHORS:
{author}
"#,
about = r#"
____ ___ ____ __ __ /\
/ ___| ___ __ _ / _ \ | _ \ | \/ | {.-}
\___ \ / _ \ / _` || | | || |_) || |\/| | ;_.-'\
___) || __/| (_| || |_| || _ < | | | | { _.}_
|____/ \___| \__,_| \___/ |_| \_\|_| |_| \.-' / `,
\ | /
An async & dynamic ORM for Rust \ | ,/
=============================== \|_/
Getting Started!
- documentation: https://www.sea-ql.org/SeaORM
- step-by-step tutorials: https://www.sea-ql.org/sea-orm-tutorial
- integration examples: https://github.com/SeaQL/sea-orm/tree/master/examples
- cookbook: https://www.sea-ql.org/sea-orm-cookbook
Join our Discord server to chat with others in the SeaQL community!
- invitation link: https://discord.com/invite/uCPdDXzbdv
If you like what we do, consider starring, commenting, sharing and contributing!
"#
)]
pub struct Cli {
#[clap(action, global = true, short, long, help = "Show debug messages")]
pub verbose: bool,
Expand All @@ -12,13 +46,16 @@ pub struct Cli {

#[derive(Subcommand, PartialEq, Eq, Debug)]
pub enum Commands {
#[clap(about = "Codegen related commands")]
#[clap(arg_required_else_help = true)]
#[clap(
about = "Codegen related commands",
arg_required_else_help = true,
display_order = 10
)]
Generate {
#[clap(subcommand)]
command: GenerateSubcommands,
},
#[clap(about = "Migration related commands")]
#[clap(about = "Migration related commands", display_order = 20)]
Migrate {
#[clap(
value_parser,
Expand Down Expand Up @@ -63,9 +100,9 @@ you should provide the directory of that submodule.",

#[derive(Subcommand, PartialEq, Eq, Debug)]
pub enum MigrateSubcommands {
#[clap(about = "Initialize migration directory")]
#[clap(about = "Initialize migration directory", display_order = 10)]
Init,
#[clap(about = "Generate a new, empty migration")]
#[clap(about = "Generate a new, empty migration", display_order = 20)]
Generate {
#[clap(
value_parser,
Expand All @@ -78,19 +115,37 @@ pub enum MigrateSubcommands {
#[clap(
action,
long,
help = "Generate migration file based on Utc time instead of Local time"
default_value = "true",
help = "Generate migration file based on Utc time",
conflicts_with = "local-time",
display_order = 1001
)]
universal_time: bool,

#[clap(
action,
long,
help = "Generate migration file based on Local time",
conflicts_with = "universal-time",
display_order = 1002
)]
local_time: bool,
},
#[clap(about = "Drop all tables from the database, then reapply all migrations")]
#[clap(
about = "Drop all tables from the database, then reapply all migrations",
display_order = 30
)]
Fresh,
#[clap(about = "Rollback all applied migrations, then reapply all migrations")]
#[clap(
about = "Rollback all applied migrations, then reapply all migrations",
display_order = 40
)]
Refresh,
#[clap(about = "Rollback all applied migrations")]
#[clap(about = "Rollback all applied migrations", display_order = 50)]
Reset,
#[clap(about = "Check the status of all migrations")]
#[clap(about = "Check the status of all migrations", display_order = 60)]
Status,
#[clap(about = "Apply pending migrations")]
#[clap(about = "Apply pending migrations", display_order = 70)]
Up {
#[clap(
value_parser,
Expand All @@ -100,14 +155,19 @@ pub enum MigrateSubcommands {
)]
num: Option<u32>,
},
#[clap(value_parser, about = "Rollback applied migrations")]
#[clap(
value_parser,
about = "Rollback applied migrations",
display_order = 80
)]
Down {
#[clap(
value_parser,
short,
long,
default_value = "1",
help = "Number of applied migrations to be rolled back"
help = "Number of applied migrations to be rolled back",
display_order = 90
)]
num: u32,
},
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-cli/src/commands/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ where
// Set search_path for Postgres, E.g. Some("public") by default
// MySQL & SQLite connection initialize with schema `None`
if let Some(schema) = schema {
let sql = format!("SET search_path = '{}'", schema);
let sql = format!("SET search_path = '{schema}'");
pool_options = pool_options.after_connect(move |conn, _| {
let sql = sql.clone();
Box::pin(async move {
Expand Down
Loading

0 comments on commit 1af5191

Please sign in to comment.