NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
crates.io
crates.io, #1588 most downloaded on crates.io
A safe, extensible ORM and Query Builder for PostgreSQL, SQLite, and MySQL
Latest stable
2.3.14
Last release 1 months ago
07 Oct 2026
Ships on a steady schedule
a new release about every 5 weeks
Nearly every release is documented
notes for 59 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
11 years old
99 releases · first in 2015
Drag across the ruler to compare, or tap a release to open it.
Workaround a potential future breaking change in rust
COMMIT, such as a deferred foreign key violation on SQLite, leaving the transaction openembed_migrations! making the crate hash depend on the directory the crate is built in, which broke reproducible buildsError::source for our error typesSee here for the full changes:
Full Changelog: v2.3.13...v2.3.14
You can support the development of Diesel by:
Your coding agent can read these notes before it upgrades. Set up the MCP server →
SerializedDatabase::as_slice is deprecated in favor of the new SerializedDatabase::try_as_slice , which reports the allocation failure as an error ins…
then_order_by and distinct_on to reject otherwise broken SQL queriesclippy::redundant_field_names lint warning generated by #[derive(QueryableByName)]SMALLINT UNSIGNED holding 40000 read as Integer returns 40000 rather than -25536SqliteConnection::serialize_database_to_buffer when SQLite returns a null buffer for an empty deserialized database or an allocation failure. SerializedDatabase::as_slice is deprecated in favor of the new SerializedDatabase::try_as_slice, which reports the allocation failure as an error instead of panicking.SqliteValue of the same field had returned. Such a read now works on a copy of the value.PgInterval type from a too short bufferPgInterval type from a too short bufferI would like to thank @LucaCappelletti94 , @Eh2406 (as @rustfoundation AI security engineer) and @weareaisle for reporting issues covered in this release.
Full Changelog: v2.3.12...v2.3.13
You can support the development of Diesel by:
Fixed FromSql/ToSql for chrono::NaiveTime on MySQL dropping the fractional-seconds component of TIME values, so a TIME(N) column now round-trips its m
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.11...v2.3.12
You can support the development of Diesel by:
Fixed several potential panics in PostgreSQL (de)serialization code
.load() batch inserts and returning clauses on the SQLite backendSqliteConnection::deserialize_read_only_database()Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.10...v2.3.11
You can support the development of Diesel by:
Fixed a wrong value of a internal MYSQL flag
diesel print-schemaORDER BY and GROUP BY clausesFull Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.9...v2.3.10
You can support the development of Diesel by:
Removed a dbg! statement from the Mysql backend that caused unwanted output
dbg! statement from the Mysql backend that caused unwanted output#[derive(AsChangeset)] introduced in 2.3.8 where structs with a type or const generic parameter referenced in a field type failed to compile with error[E0425]: cannot find type 'T' in this scope. The diagnostic helper functions added to improve AsChangeset error messages now forward all generic parameters of the input struct, not only lifetimes.You can support the development of Diesel by:
Added support for libsqlite3-sys 0.37.0
ORDER BY clause without a GROUP BY clause.count() or .select(aggregate_expr) on a query that already has a non-aggregate .order_by() clause now raises a compile-time error instead of generating invalid SQL that would be rejected by the database at runtime (fixes #3815)#[derive(AsChangeset)]infix_operator!()SqliteValue::read_text/FromSql<Text, Sqlite> for StringSqliteConnection::register_function for aggregate functionsSqliteConnection::register_functionCOPY FROM/TODebug/Display implementation of batch INSERT statements for SQLiteSqliteValue::read_text/FromSql<Text, Sqlite> for String/SqliteValue::read_blob()/FromSql<Binary, Sqlite> for Vec<u8>FromSql<Binary, _> for Vec<u8> and FromSql<Text, _> for String for third party backends (requires changes to the third party backend as well)You can support the development of Diesel by:
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.7...v2.3.8
Add support for libsqlite3-sys 0.36
You can support the development of Diesel by:
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.6...v2.3.7
Added support for mysqlclient-sys 0.5.0
table#[derive(Insertable)] if the same field type is used with different lifetime valuesYou can support the development of Diesel by:
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.5...v2.3.6
Fix another libmariadb related issue with time types
#[derive(Insertable)]returning_clauses_for_sqlite_3_35 feature enable the sqlite feature by defaultYou can support the development of Diesel by:
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.4...v2.3.5
Fix an issue with breaking changes in libmariadb
#[diesel(embed)] with Option<Inner> typesYou can support the development of Diesel by:
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.3...v2.3.4
Fix displaying binds in instrumentations for #[derive(MultiConnection)]
#[derive(MultiConnection)]Ok in code generated by derives to avoid naming conflictsStarting with Diesel-CLI 2.3.3 you can verify that you downloaded the correct binaries via GitHub's artifact attestation
gh attestation verify diesel_cli-x86_64-unknown-linux-gnu.tar.xz -R diesel-rs/diesel
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.2...v2.3.3
You can support the development of Diesel by:
Fixed an incompatibility with libmariadb versions shipped by debian
(Diesel 2.3.1 did not contain any changes beside the version bump to retrigger the docs.rs build)
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.3.0...v2.3.2
You can support the development of Diesel by:
This version did not contain any changes, but only a version bump to retrigger the docs.rs build
This version did not contain any changes, but only a version bump to retrigger the docs.rs build
This release includes a several large extensions to the query DSL provided by Diesel and also helps increases the number of platforms you can use Dies
This release includes a several large extensions to the query DSL provided by Diesel and also helps increases the number of platforms you can use Diesel on out of the box. Notable changes include:
#[derive(HasQuery)]JSON and JSONB in the SQLite backendSee the release blog for the full announcement
You can support the development of Diesel by:
limit() and offset() DSL to combination clauses such as UNION#[derive(Identifiable)] ignoring attribute #[diesel(serialize_as)] on primary keysAsChangeset via #[diesel(embed)]#[diesel(skip_update)] attribute for the AsChangeset derive to skip updating a field present in the structdiesel::r2d2::TestCustomizer, which allows users to customize their diesel::r2d2::Pools
in a way that makes the pools suitable for use in parallel tests.Json and Jsonb support for the SQLite backend.#[diesel::declare_sql_function] attribute macro to easily define support for
multiple sql functions at once via an extern "SQL" block[print_schema] allow_tables_to_appear_in_same_query_config = "fk_related_tables" to generate separate allow_tables_to_appear_in_same_query! calls containing only tables that are related through foreign keys. (Default: "all_tables".) It is not possible to build queries using two tables that don't appear in the same allow_tables_to_appear_in_same_query! call, but that macro generates O(n²) rust code, so this option may be useful to reduce compilation time. (#4333)wasm32-unknown-unknown target support for sqlite backend.CAST operator[print_schema] allow_tables_to_appear_in_same_query_config = "none" to generate no allow_tables_to_appear_in_same_query! calls. (Default: "all_tables".). (#4333)[print_schema] pg_domains_as_custom_types parameter to generate custom types for PostgreSQL domains that matches any of the regexes in the given list. (Default: [].) This option allows an application to selectively give special meaning for the serialization/deserialization of these types, avoiding the default behavior of treating the domain as the underlying type. (#4592)a.eq_any(b) was non-nullable even if a and b were nullable.InstrumentationEvent::BeginTransaction for immediate and exclusive transactions in SQLiteDELETE FROM.ipnetwork to allow version 0.21.DIESEL_LOG logging filter env variable instead of the default RUST_LOG one (#4575)Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.0...v2.3.0
Added support for libsqlite3-sys 0.35.0
oid[] type in the PostgreSQL backendYou can support the development of Diesel by contributions or by sponsoring the project on GitHub
We are looking for input on a newly designed derive to make constructing queries easier. See here for details.
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.11...v2.2.12
Disallow mixing aggregate and non-aggregate expressions in DISTINCT ON clauses
DISTINCT ON clauses#[derive(MultiConnection)]You can support the development of Diesel by contributions or by sponsoring the project on Github
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.10...v2.2.11
Support for libsqlite3-sys 0.33.0
You can support the development of diesel by contributions or by sponsoring the project on Github
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.9...v2.2.10
Fix an issue where diesel migration generate --diff-schema incorrectly uses the primary key of table B as the referenced column rather than the primar
diesel migration generate --diff-schema incorrectly uses the primary key of table B as the referenced column rather than the primary key of table A when B has a foreign key pointing to table A.uuid and serde_json feature.unanmed prepared statement not found error with pgbouncer.ipnet::Ipnet values with an subnet to SQL valuesYou can support the development of diesel by contributions or by sponsoring the project on Github
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.8...v2.2.9
Allow #[diesel(check_for_backend(_))] to check fields with #[diesel(embed)] annotations
#[diesel(check_for_backend(_))] to check fields with #[diesel(embed)] annotationsCompatibleTypeCOPY FROM statements to 12ASC/DESC, DISTINCT ON, and DELETE FROM clausesYou can support the development of diesel by contributions or by sponsoring the project on Github
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.7...v2.2.8
Fixed diesel thinking a.eq_any(b) was non-nullable even if a and b were nullable.
a.eq_any(b) was non-nullable even if a and b were nullable.InstrumentationEvent::BeginTransaction for immediate and exclusive transactions in SQLitediesel::debug_queryipnetwork to allow version 0.21.libsqlite3-sys to allow version 0.31.0pq-sys to allow version 0.7.0#[diesel::auto_type]You can support the development of diesel by contributions or by sponsoring the project on Github
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.6...v2.2.7
Remove more mentions of gitter from the documentation
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.5...v2.2.6
Officially deprecating the gitter room
Returning and Count so that #[auto_type] works with such queries.and() and .or() which would
result in queries failing at runtimeYou can support the development of diesel by contributions or by sponsoring the project on Github.
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.4...v2.2.5
Returning and Count so that #[auto_type] works with such queries.and() and .or() which would
result in queries failing at runtimeFix an issue where empty queries could trigger undefined behaviour in the sqlite backend
Fixed a possible vulnerability in how Diesel handled protocol level bind parameters. See the SQL Injection isn't Dead: Smuggling Queries at Protocol L…
#[derive(QueryableByName)]You can support the development of diesel by contributions or by sponsoring the project on Github.
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.2...v2.2.3
Support for libsqlite3-sys 0.29.0
NumericSerializedDatabase::new function due to unsoundnessYou can support the development of diesel by contributions or by sponsoring the project on Github.
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.1...v2.2.2
You can support the development of diesel by contributions or by sponsoring the project on Github.
You can support the development of diesel by contributions or by sponsoring the project on Github.
#[dsl::auto_type] with functions that accept reference arguments#[derive(Queryable)] with structs that use a type named Row as field typemysqlclient-sys 0.2.x with diesel 2.2Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.2.0...v2.2.1
Deprecated sql_function! in favour of define_sql_function! which provides compatibility with #[dsl::auto_type]
This release wouldn't be possible without the support of our contributors and sponsors. If you want to support diesels development, consider joining the reviewer team, submitting PR's, help writing documentation or sponsor the maintainers.
[print_schema] exclude_custom_type_definitions = ["Vector"]. If a custom type matches one element on the list it's skipped.rowid aliases when no explicit primary key is defined for print-schema#[dsl::auto_type] attribute macro, allowing to infer type of query fragment functionsSelectable derives, which allows skipping specifying select_expression_type most of the time, in turn enabling most queries to be written using just a Selectable derive.#[diesel(skip_insertion)] field attribute to the Insertable derive macro, allowing fields which map to generated columns to be skipped during insertion.sqlite-integer-primary-key-is-bigint configuration option, usable with SQLite 3.37 or above, allowing to use BigInt for INTEGER PRIMARY KEY columns in SQLite for tables without the WITHOUT ROWID attribute (SQLite doc).print_schema entry in diesel.toml (e.g. [print_schema.user1]), which allows generating multiple schema.rs filesCOPY TO and COPY FROM statementschrono::Duration to postgresql's INTERVAL sql typeserialize_database_to_buffer and deserialize_readonly_database_from_buffer methods in SqliteConnection to support serialization/deserialization of SQLite databases to and from byte buffers.SerializedDatabase wrapper type for a serialized database that is dynamically allocated by calling serialize_database_to_buffer. This RAII wrapper deallocates the memory when it goes out of scope with sqlite3_free.sql_function! in favour of define_sql_function! which provides compatibility with #[dsl::auto_type]Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.1.0...v2.2.0
Fix using BoxableExpression with having clauses
BoxableExpression with having clausesYou can support the development of diesel by contributions or by sponsoring the project on Github.
Full Changelog: https://github.com/diesel-rs/diesel/compare/v2.1.5...v2.1.6
Fix impl SqlOrd postgres > postgres_backend feature flag.
impl SqlOrd postgres > postgres_backend feature flag.Queryable to be used with multiple table names.libsqlite3-sys to allow version 0.28 as wellFull Changelog: https://github.com/diesel-rs/diesel/compare/v2.1.4...v2.1.5
impl SqlOrd postgres > postgres_backend feature flag.Queryable to be used with multiple table names.libsqlite3-sys to allow version 0.28 as wellUpdate libsqlite3-sys to allow version 0.27 as well
libsqlite3-sys to allow version 0.27 as wellYou can support the development of diesel by contributions or by sponsoring the project on Github.
Increased accidentally decreased limit around element count in DISTINCT ON and ORDER BY clauses again as that broke existing code
DISTINCT ON and ORDER BY clauses again as that broke existing codeFixed another potential breaking chaneg around queries containing DISTINCT ON and ORDER BY clauses consisting of custom sql expressions (e.g. .nullabl
DISTINCT ON and ORDER BY clauses consisting of custom sql expressions (e.g. .nullable())#[derive(Selectable)] and #[diesel(check_for_backend)] generates invalid rust code if the struct contains lifetimes/generic typesYou can support the development of diesel by contributions or by sponsoring the project on Github.
Fixed a potential breaking change around queries containing DISTINCT ON and ORDER BY clauses consisting of custom sql expressions (e.g. diesel::sql)
diesel print-schema that lead to generating invalid table! macros if both the #[sql_name] and the #[max_lenght] attribute are presentdiesel print-schema with really old sqlite versions#[diesel(check_for_backend)] ignored #[diesel(deserialize_as)] attributes#[derive(MultiConnection)] featurediesel migration generate --diff-schema now respects table filters as setup for print-schema via diesel.tomlDISTINCT ON and ORDER BY clauses consisting of custom sql expressions (e.g. diesel::dsl::sql)You can support the development of diesel by sponsoring the project on github
Diesel 2.1.0 contains the contributions of 42 people. More than 380 commits were submitted over a span of 9 months.
Diesel 2.1.0 contains the contributions of 42 people. More than 380 commits were submitted over a span of 9 months.
This release contains several new features and improves existing features. It introduces support for generating migrations based on the diff between your schema.rs file and your database via Diesel CLI. Diesel derives now provides a #[derive(MultiConnection)] derive macro that allows to easily combine different database connections into a single enum, which implements Connection on its own. The MySQL backend gets support for upsert queries via the ON DUPLICATE KEYS syntax. Finally we provide new tooling to improve complex error messages generated for common error cases. Check out our changelog for a complete list of changes.
This release wouldn't be possible without the support of our contributors and sponsors. If you want to support diesels development, consider joining the reviewer team, submitting PR's, help writing documentation or sponsor the maintainers.
Diesel CLI now includes support for generating migrations based on the difference of your schema.rs file and your local database.
This works as following:
schema.rs file, for example by adding your first table:diesel::table! {
users {
id -> Integer,
name -> Text,
}
}
diesel migration generate my_first_migration --diff-schema --database-url DATABASE_URL-- Your SQL goes here
CREATE TABLE `users`(
`id` INTEGER NOT NULL PRIMARY KEY,
`name` TEXT NOT NULL
);
diesel migration run --database-url DATABASE_URLIt's important to note that the generated migrations can only contain information that are part of the schema.rs file. This explicitly excludes default value, custom check constraints and similar SQL features. We expect the generated migrations to be a good starting point for writing the actual migration you need, we do not expect them to include all necessary information in all cases or to provide the perfect solution in each scenario.
MultiConnection supportDiesel now includes a #[derive(MultiConnection)] proc macro derive, which allows to easily support more than one database backend in a single application. It can be applied to an enum of different connections:
#[derive(diesel::MultiConnection)]
pub enum AnyConnection {
Postgresql(diesel::PgConnection),
Mysql(diesel::MysqlConnection),
Sqlite(diesel::SqliteConnection),
}
Afterwards the AnyConnection type can be used as ordinary connection:
fn use_multi(conn: &mut AnyConnection) -> QueryResult<()> {
// Use the connection enum as any other connection type
// for inserting/updating/loading/…
diesel::insert_into(users::table)
.values(users::name.eq("Sean"))
.execute(conn)?;
let users = users::table.load::<(i32, String)>(conn)?;
Ok(())
}
By default this connection type will only support a subset of SQL that's supported by all inner connection types. By being an enum it's easy to fallback to backend specific SQL as soon as required. We provide this feature as derive macro so that it is possible to:
MultiConnectionHelper trait in addition to the existing Connection trait.Diesel 2.1 adds support for INSERT INTO … ON DUPLICATE KEYS … queries for the MySQL backend using the existing upsert framework. It's now possible to write such queries using the diesel provided DSL:
diesel::insert_into(users)
.values(&user2)
.on_conflict(diesel::dsl::DuplicatedKeys)
.do_update()
.set(name.eq("I DONT KNOW ANYMORE"))
.execute(conn)?;
We spend some effort to improve error messages generated by rustc for common diesel issues further.
Consider the following example:
table! {
users {
id -> Integer,
name -> Text,
}
}
#[derive(Queryable)]
struct User {
name: String,
id: i32,
}
users::table.load::<User>(&mut conn)
which would generate the following error message:
error[E0277]: the trait bound `(diesel::sql_types::Integer, diesel::sql_types::Text): load_dsl::private::CompatibleType<User, Mysql>` is not satisfied
--> src/main.rs:20:31
|
20 | users::table.load::<User>(&mut conn);
| ---- ^^^^^^^^^ the trait `load_dsl::private::CompatibleType<User, Mysql>` is not implemented for `(diesel::sql_types::Integer, diesel::sql_types::Text)`
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait `load_dsl::private::CompatibleType<U, DB>`:
(ST0, ST1)
(ST0, ST1, ST2)
(ST0, ST1, ST2, ST3)
(ST0, ST1, ST2, ST3, ST4)
(ST0, ST1, ST2, ST3, ST4, ST5)
(ST0, ST1, ST2, ST3, ST4, ST5, ST6)
(ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7)
(ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, ST8)
and 24 others
= note: required for `users::table` to implement `LoadQuery<'_, _, User>`
note: required by a bound in `diesel::RunQueryDsl::load`
--> /home/weiznich/.cargo/git/checkouts/diesel-6e3331fb3b9331ec/ef6252e/diesel/src/query_dsl/mod.rs:1543:15
|
1543 | Self: LoadQuery<'query, Conn, U>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `diesel::RunQueryDsl::load`
This is caused by an field order mismatch between what your query returns and what your struct expects the query to return.
With diesel 2.0 we introduced the Selectable trait and a corresponding derive. That allows to automatically generate a matching select clause to prevent such issues from happening. While this already solved parts of the problem it does not solve the following case:
#[derive(Queryable, Selectable)]
struct User {
name: i32,
id: i32,
}
users::table.select(User::as_select()).load(&mut conn);
which generates the following error message:
error[E0277]: the trait bound `expression::select_by::SelectBy<User, _>: load_dsl::private::CompatibleType<_, _>` is not satisfied
--> src/main.rs:20:49
|
20 | users::table.select(User::as_select()).load(&mut conn);
| ---- ^^^^^^^^^ the trait `load_dsl::private::CompatibleType<_, _>` is not implemented for `expression::select_by::SelectBy<User, _>`
| |
| required by a bound introduced by this call
|
= help: the trait `load_dsl::private::CompatibleType<U, DB>` is implemented for `expression::select_by::SelectBy<U, DB>`
= note: required for `SelectStatement<FromClause<users::table>, query_builder::select_clause::SelectClause<expression::select_by::SelectBy<User, _>>>` to implement `LoadQuery<'_, _, _>`
note: required by a bound in `diesel::RunQueryDsl::load`
--> /home/weiznich/.cargo/git/checkouts/diesel-6e3331fb3b9331ec/ef6252e/diesel/src/query_dsl/mod.rs:1543:15
|
1543 | Self: LoadQuery<'query, Conn, U>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `diesel::RunQueryDsl::load`
This is caused by a type mismatch in the name field. With diesel 2.1 we now introduce an additional #[diesel(check_for_backend(diesel::backend::BackendType))] attribute that greatly improves the error messages generated for these cases. This helps pining down which field exactly causes a type mismatch.
By applying this attribute to our example:
#[derive(Queryable, Selectable)]
#[diesel(check_for_backend(diesel::mysql::Mysql))]
struct User {
name: i32,
id: i32,
}
we get the following error message:
error[E0277]: the trait bound `i32: FromSql<diesel::sql_types::Text, Mysql>` is not satisfied
--> src/main.rs:13:11
|
13 | name: i32,
| ^^^ the trait `FromSql<diesel::sql_types::Text, Mysql>` is not implemented for `i32`
|
= help: the trait `FromSql<diesel::sql_types::Integer, Mysql>` is implemented for `i32`
= note: required for `i32` to implement `diesel::Queryable<diesel::sql_types::Text, Mysql>`
= note: required for `i32` to implement `FromSqlRow<diesel::sql_types::Text, Mysql>`
= help: see issue #48214
This error message now points to the exact cause of the issue: You cannot deserialize an Text value into a i32 field. This attribute accepts one or more diesel backend type to check the struct definition against. It requires that the struct is using either both, #[derive(Queryable)] and #[derive(Selectable)] or #[derive(QueryableByName)].
Changes listed here are relevant for crates using the i-implement-a-third-party-backend-and-opt-into-breaking-changes feature flag.
With Diesel 2.1 we have migrated some traits to use GAT. This affects the following traits:
RowGatWorkaroundConnectionGatWorkaroundHasRawValueHasBindCollectorThese traits are removed in favour of generic associated types on the corresponding child trait.
Additionally we slightly relaxed one trait bound on BindCollector::push_bound_value to allow unsized values there as well.
Thank you to everyone who helped make this release happen through sponsoring, bug reports, and discussion on GitHub and Gitter. While we don't have a way to collect stats on that form of contribution, it's greatly appreciated.
In addition to the Diesel core team, 42 people contributed code to this release. A huge thank you to:
custom_type_derives config option to customize the derives for SQL
type definitions automatically generated by Diesel CLI.#[derive(MultiConnection)] proc-macro that lets you easily implement diesel::Connection
for an enum of connections to different database backends.--diff-schema flag to the diesel migration generate command that generates a migration based
on the difference between your database and the provided schema.rs fileON CONFLICT (...) DO UPDATE ... [WHERE ...] conditional clause support for PostgreSQL.ON DUPLICATE KEY DO UPDATE syntax through the existing upsert functions.distinct_on for PostgreSQL,
like: .distinct_on((column_a, column_b)).schema.rs fileWorkaround the missing name resolution in rust-analyzer. This should fix type inference for some diesel queries. (It remains broken for queries contai
.filter()/.inner_join()/.left_join(). These require fixes in rust-analyzer itself)sql_query in the sqlite backendmysql instead of the mysql_backend feature flaglibsqlite3-sys 0.26Fixed a bug with our transaction manager implementation that caused by marking transactions as broken which could be recovered.
BoxableExpression and order clausesReverted a fix from the 2.0.1 release that breaks valid INSERT … ON CONFLICT queries
INSERT … ON CONFLICT queriesThis is a bugfix release containing the following fixes:
This is a bugfix release containing the following fixes:
diesel_cli generating incompatible type names for the generate_missing_sql_type_definitions feature on PostgreSQLdiesel_cli handles sqlite urls while checking if a given database existsPgConnection becoming unusable after hitting a database error in certain situationsINSERT … ON CONFLICT queriesdiesel_derives generating code that triggers the disabled by default unused_qualifications lintThis release includes updated versions of diesel, diesel_cli and diesel_derives
Check out our changelog for a complete list of changes. As this is a new major Diesel release it contains a number of breaking changes. Checkout our m…
Diesel 2.0.0 contains the contributions of more than 130 people. More than 1700 commits were submitted over a span of 3 years.
As part of this release we introduced numerous new features and rewrote large parts of the internal structure. Check out our changelog for a complete list of changes. As this is a new major Diesel release it contains a number of breaking changes. Checkout our migration guide for details about how to handle those breaking changes.
This release contains the following parts:
This release marks a first prerelease of the upcoming Diesel 2.0 release. We ask you for your help to finalise the release. Checkout the "Timeline for a Diesel 2.0 release" section for details about how you can help us finishing the release.
As a highlight Diesel 2.0.0 adds support for the following features:
GROUP BY supportUNION/INTERSECT queriesGROUP BY clausesDiesel 2.0 adds support for GROUP BY clauses for select queries.
This means queries like the following one will just work.
users::table.inner_join(posts::table)
.group_by(users::id)
.select((users::name, count(posts::id)))
As this is the case for all other Diesel built-in query dsl, this construct is fully checked at compile time. This means Diesel
will ensure that the GROUP BY clause is valid for the current query and it will also ensure that expressions appearing inside
of your SELECT clause will match the aggregation rules provided by the current GROUP BY clause.
Diesel 2.0 adds support for table aliasing. This enables users to write queries, where a table appears more than once in the corresponding
FROM clause. For this Diesel provides a Diesel::alias! macro that allows to define new alias for existing tables.
The following query demonstrates the support for this feature:
// Define new table alias for the existing `users` table
let users1 = diesel::alias!(schema::users as user1);
// Use the corresponding alias inside any existing query
users::table
.inner_join(users1.on(users::id).eq(users1.field(users::id))))
.select((users::id, users::name, users1.field(users::name)))
.order_by(users1.field(users::id))
Again all of this is checked at compile time. So similar to a normal table, columns from aliases are only allowed to appear if the corresponding query actually uses the alias.
Selectable traitDiesel 2.0 features a new Selectable trait and derive that lets users declare that a type expects a certain kind of select clause.
The major use case for this feature is to ensure that columns from a specific query are always requested in the right order
for a corresponding type implementing Queryable. This also works for complex queries involving joins or other kinds of nesting.
#[derive(Queryable, Selectable)]
struct User {
id: i32,
name: String,
}
let first_user = users.select(User::as_select()).first(connection)?;
Diesel enforces at type system level that once you provided such a select clause via User::as_select() you are only allowed
to construct this type from the returned result of the corresponding query. This means there is no need to specify the User type
twice in the query above.
UNION/INTERSECT/EXCEPT queriesDiesel 2.0 extents the query builder to support query combinations via UNION/INTERSECT/EXCEPT. This allows you
to easily chain multiple queries together as long as they return fields of the same type. Queries like the following
one are now supported:
users.select(user_name.nullable())
.union(animals.select(animal_name).filter(animal_name.is_not_null()))
As always this is checked at compile time to reject invalid queries, like for example that ones containing select clauses with different fields.
The release of Diesel 2.0 does not only include the features listed above, but also marks the point where the following things can be provided by third party crates:
QueryDsl extensions to support previously unsupported SQL features. Checkout
diesel_full_text_search for an exampleConnection infrastructureConnection implementations for existing backendsConnection
and Backend implementations for previously unsupported backends. Checkout diesel-oci for an example.We encourage our community to try out those features. Especially we would like to see experimentation around:
Please get in touch with us for pointers, help and details.
With the release of Diesel 2.0 the planing for our next releases start. Hopefully they will not take as long as Diesel 2.0. We are looking for input on which features are wanted by our community. Please open a discussion thread with your idea in our discussion forum.
Weiznich will work on improving error messages for trait heavy crates based on a Rust Foundation Project Grant. This work will hopefully improve error messages for Diesel as well. If you are aware of bad error messages please submit a minimal example here.
As part of this release we would like to welcome @Ten0 as part of the diesel core team.
Thank you to everyone who helped make this release happen through bug reports, and discussion on Gitter. While we don't have a way to collect stats on that form of contribution, it's greatly appreciated.
In addition to the Diesel core team, 141 people contributed code to this release. A huge thank you to:
MysqlConnection::establish is able to initiate an SSL connection while specifying certificate roots. The database URL should contain an ssl_ca parameter with a path pointing to the certificate roots. See docs if desired.
MysqlConnection::establish is able to initiate an SSL connection. The database URL should contain ssl_mode parameter with a value of the MySQL client command option --ssl-mode if desired.
Connection and SimpleConnection traits are implemented for a broader range
of r2d2::PooledConnection<M> types when the r2d2 feature is enabled.
Added DatabaseErrorKind::ReadOnlyTransaction to allow applications to
handle errors caused by writing when only allowed to read.
All expression methods can now be called on expressions of nullable types.
Added BoxedSqlQuery. This allows users to do a variable amount of .sql or
.bind calls without changing the underlying type.
Added .sql to SqlQuery and UncheckedBind to allow appending SQL code to
an existing query.
The MacAddr SQL type can now be used without enabling the network-address
feature.
Added support for SQLite's UPSERT.
You can use this feature above SQLite version 3.24.0.
Added ability to create custom aggregate functions in SQLite.
Multiple aggregate expressions can now appear together in the same select clause. See the upgrade notes for details.
ValidGrouping has been added to represent whether an expression is valid for
a given group by clause, and whether or not it's aggregate. It replaces the
functionality of NonAggregate. See the upgrade
notes for details.
It is now possible to inspect the type of values returned from the database in such a way to support constructing a dynamic value depending on this type.
Added a without-deprecated feature that unconditionally disables deprecated items.
Use this feature flag to verify that none of your dependencies is setting
the with-deprecated flag internally.
Added support for PostgreSQL's SIMILAR TO and NOT SIMILAR TO.
Added #[diesel(serialize_as)] analogous to #[diesel(deserialize_as)]. This allows
customization of the serialization behaviour of Insertable and AsChangeset structs.
Added support for GROUP BY clauses
Added support for UNION, UNION ALL, INTERSECT, INTERSECT ALL, EXCEPT, EXCEPT ALL clauses
Added the error position for PostgreSQL errors
Added ability to create custom collation functions in SQLite.
Added support for SQLite's IS and IS NOT.
Add support for HAVING clauses.
Added support for SQL functions without arguments for SQLite.
Diesel CLI will now generate SQL type definitions for SQL types that are not supported by diesel out of the box. It's possible to disable this behavior via the generate_missing_sql_type_definitions config option.
Added an option to #[derive(Insertable)] that let you insert NULL values instead of DEFAULT values for Option<T>
Added support for all the derive attributes being inside #[diesel(...)]
Added support for RETURNING expressions for Sqlite via the returning_clauses_for_sqlite_3_35 feature
Added support for table aliasing via the alias! macro
Added support for the usage of slices of references with belonging_to from BelongingToDsl
Added support for updating individual array elements UPDATE table SET array_column[1] = true
Adds an ipnet-address feature flag, allowing support (de)serializing IP
values from the database using types provided by ipnet. This feature
may be enabled concurrently with the previously existing network-address
feature.
We've added support for loading values using libpq's row-by-row mode via the new iterator interface
Adds Timestamp, Timestamptz support for appropriate types for time v0.3.9.
This feature enables using the time crate as an alternative to chrono.
uuid version < 0.7.0 has been removed.bigdecimal < 0.0.13 has been removed.pq-sys < 0.4.0 has been removed.mysqlclient-sys < 0.2.5 has been removed.time (0.1) types has been removed.chrono < 0.4.19 has been removed.NonNull trait for sql types has been removed in favour of the new SqlType trait.no_arg_sql_function! has been deprecated without replacement.
[sql_function!][sql-function-2-0-0] can now be used for functions with zero
arguments. See the migration guide for more details.barrel based migrations has been removed for now. We are happy to
add this support back as soon as barrel integrates with our new migration framework.diesel bash-completions) has been removed.
Use diesel completions <shell> instead.The minimal officially supported rustc version is now 1.56.0
Interacting with a database requires a mutable connection.
The way the Backend trait handles its RawValue type has
been changed to allow non-references. Users of this type (e.g. code written
&DB::RawValue or &<DB as Backend>::RawValue>) should use
backend::RawValue<DB> instead. Implementors of Backend
should check the relevant section of the migration guide.
The type metadata for MySQL has been changed to include sign information. If
you are implementing HasSqlType for Mysql manually, you may need to adjust
your implementation to fully use the new unsigned variants in MysqlType
The RawValue types for the Mysql and Postgresql backend where changed
from [u8] to distinct opaque types. If you used the concrete RawValue type
somewhere you need to change it to mysql::MysqlValue or pg::PgValue.
The uuidv07 feature was renamed to uuid, due to the removal of support for older uuid versions
Boxed queries (constructed from .into_boxed()) are now Send.
The handling of mixed aggregate values is more robust. Invalid queries such as
.select(max(id) + other_column) are now correctly rejected, and valid
queries such as .select((count_star(), max(other_column))) are now correctly
accepted. For more details, see the migration guide.
NonAggregate is now a trait alias for ValidGrouping<()> for expressions
that are not aggregate. On stable this is a normal trait with a blanket impl,
but it should never be implemented directly. With the unstable feature, it
will use trait aliases which prevent manual implementations.
Due to language limitations, we cannot make the new trait alias by itself represent everything it used to, so in some rare cases code changes may be required. See the migration guide for details.
Various __NonExhaustive variants in different (error-) enums are replaced with
#[non_exhaustive]. If you matched on one of those variants explicitly you need to
introduce a wild card match instead.
FromSql::from_sql is changed to construct value from non nullable database values.
To construct a rust value for nullable values use the new FromSql::from_nullable_sql
method instead.
Custom sql types are now required to implement the new SqlType trait. Diesel will
automatically create implementations of that trait for all types having a #[derive(SqlType)]
The workflow for manually implementing support custom types has changed. Implementing
FromSqlRow<ST, DB> is not required anymore, as this is now implied by implementing
FromSql<ST, DB>. The requirement of implementing Queryable<ST, DB> remains
unchanged. For types using #[derive(FromSqlRow)] no changes are required as the
derive automatically generates the correct code
The structure of our deserialization trait has changed. Loading values from the database
requires now that the result type implements FromSqlRow<ST, DB>. Diesel provides wild
card implementations for types implementing Queryable<ST, DB> or QueryableByName<DB>
so non generic code does not require any change. For generic code you likely need to
replace a trait bound on Queryable<ST, DB> with a trait bound on FromSqlRow<ST, DB>
and a bound to QueryableByName<DB> with FromSqlRow<Untyped, DB>.
CLI flags of only-tables and except-tables are now interpreted as regular expressions.
Similarly, only_tables and except_tables in diesel.toml are treated as regular expressions.
Now you can sort column fields by name with the column-sorting option.
It can be set to either ordinal_position (default) or name.
This ensures stable sorting even if columns are removed and re-added.
The Queryable<ST,DB> trait was updated to be made faillible, in order to properly handle
cases where you detect a data inconsistency between fields on deserialization
(that e.g. was supposed to be made impossible by DB CHECKs). The build function now
returns a
diesel::deserialize::Result<Self>
instead of a Self.
TypeMetadata::MetadataLookup is now ?Sized.
Multiple implementations of Connection<Backend=Pg> are now possible
because of the new PgMetadataLookup trait.
For the Pg backend, TypeMetadata::MetadataLookup has changed to dyn PgMetadataLookup.
Diesel's migration framework was rewritten from the ground. Existing migrations continue to
be compatible with the rewrite, but code calling into diesel_migrations requires an update.
See the migration guide for details.
eq_any() now emits a = ANY() expression for the postgresql backend instead of IN()
ne_all() now emits a != ALL() expression for the postgresql backend instead of NOT IN()
The sqlite backend now uses a single batch insert statement if there are now default values present in the values clause
The MySQL connection is using the CLIENT_FOUND_ROWS from now on. This means that updating rows without changing any values will return the number of matched rows (like most other SQL servers do), as opposed to the number of changed rows.
The definition of ToSql::to_sql and QueryFragment::walk_ast has changed to allow serializing values without
copying the value itself. This is useful for database backends like sqlite where you can directly share a buffer
with the database. Beside of the changed signature, existing impls of this trait should remain unchanged in almost
all cases.
The PIPES_AS_CONCAT sql_mode is no longer set
by default. This setting requires a modification to MySQL query parsing that is
not supported by certain systems (such as Vitess). If you are using MySQL and
executing raw queries with the || operator, you will need to rewrite your
queries or set PIPES_AS_CONCAT manually.
Many types were incorrectly considered non-aggregate when they should not have been. All types in Diesel are now correctly only considered non-aggregate if their parts are.
Offset clauses without limit clauses resulted into invalid sql using the mysql or
sqlite backend. Both do not support such clauses without a preceding limit clause.
For those backend Diesel does now generate a fake limit clause in case no explicit
limit clause was given. As consequence of this change generic query code may
require additional trait bounds as requested from the compiler. Third party
backends are required to explicitly provide QueryFragment impls for
LimitOffsetClause<L, O> now.
Nullability requirements are now properly enforced for nested joins.
Previously, only the rules for the outer-most join were considered. For
example, users.left_join(posts).left_join(comments) would allow selecting
any columns from posts. That will now fail to compile, and any selections
from posts will need to be made explicitly nullable.
Diesel CLI will now look for diesel.toml to determine the project root
before looking for Cargo.toml.
Any relative paths in diesel.toml will now be treated as relative to the
project root (the directory containing either diesel.toml or Cargo.toml).
They are no longer dependent on the current working directory (for all
directories in the same project)
The SQLite backend is now configured to interpret URIs. See the SQLite URI documentation for additional details.
We've refactored our type translation layer for Mysql to handle more types now.
We've refactored our type level representation of nullable values. This allowed us to fix multiple long standing bugs regarding the correct handling of nullable values in some corner cases (#104, #2274)
Parenthesis are now inserted around all infix operations provided by diesel's ExpressionMethods traits
Queries containing a distinct on clause check now on compile time that a compatible order clause was set.
Implementations of custom SQLite SQL functions now check for panics
diesel print-schema now generates Array<Nullable<ST>> rather than Array<ST> for Postgres Array types. Existence of
NULL values in database arrays would previously result in deserialization errors. Non-nullable arrays are now opt
in (by schema patching).
All the diesel derive attributes that are not inside #[diesel(...)]
diesel_(prefix|postfix|infix)_operator! have been deprecated. These macros
are now available without the diesel_ prefix. With Rust 2018 they can be
invoked as diesel::infix_operator! instead.
diesel::pg::upsert has been deprecated to support upsert queries on more than one backend.
Please use diesel::upsert instead.
diesel::dsl::any and diesel::dsl::all are now deprecated in
favour of ExpressionMethods::eq_any() and ExpressionMethods::ne_all()
Nothing published for this version
Nothing published for this version
This release fixes an incompatibility between features passed to diesel and diesel_migrations while using cargos new resolver feature (resolver = "2")
This release fixes an incompatibility between features passed to diesel and diesel_migrations while using cargos new resolver feature (resolver = "2") which will become the new default with the upcoming Rust 2021 edition
diesel and diesel_migrations when building both crates with cargos new resolver = "2" enabled. This change ensures compatibility with the upcoming 2021 rust edition.Updated libsqlite3-sys to allow version 0.22
libsqlite3-sys to allow version 0.22ipnetwork to allow version 0.18Fixed a use-after-free issue in the QueryableByName implementation of our Sqlite backend
QueryableByName implementation
of our Sqlite backendFixed an issue where transactions that would fail to commit would leave the connection in a broken non-committed non-rolled-back state.
libmysqlclient versionsmem::uninitializedFixed a bug with printing embedded migrations
As part of this release also updated versions of migration_internals and migration_macros are published.
Fixed an issue where the postgresql backend exploits implementation defined behaviour
diesel_derives and diesel_migrations are updated to syn 1.0Parenthesis are now inserted around all mathematical operations. This means that (2.into_sql() + 3) * 4 will correctly evaluate to 20 as expected. Pre
(2.into_sql() + 3) * 4 will correctly evaluate to 20 as expected.
Previously we would generate SQL that evaluated to 14. This could even result
in runtime errors if multiple types were involved (for example, interval * (integer + 1))This release fixes a minor memory safety issue in SQLite. This bug would only occur in an error handling branch that should never occur in practice.
In contrast to the last release most changes in this release are minor or internal. We've added support for newer versions of some dependency crates (
In contrast to the last release most changes in this release are minor or internal. We've added support for newer versions of some dependency crates (libsqlite-sys, uuid, ipnetwork).
Diesel CLI got a command line flag to check if a generated schema matches the already existing one. This is useful for CI setups to check there if the committed generated schema file matches the committed migrations.
We've added support for the diesel_mange_updated_at('table_name') SQL function on SQLite. This function handles the setup of an trigger that automatically updates the updated_at column on update operations.
Additionally several helpers were added to support the deserialisation of tuples and composite types on PostgreSQL.
As always, a full list of changes can be found it in the changelog
Thank you to everyone who helped make this release happen through bug reports, and discussion on Gitter. While we don't have a way to collect stats on that form of contribution, it's greatly appreciated.
In addition to the Diesel core team, 29 people contributed code to this release. A huge thank you to:
embed_migrations! will no longer emit an unused import warninguuidv07Diesel CLI can be configured to error if a command would result in changes
to your schema file by passing --locked-schema. This is intended for use
in CI and production deploys, to ensure that the committed schema file is
up to date.
A helper trait has been added for implementing ToSql for PG composite types.
See WriteTuple for details.
Added support for MySQL's UNSIGNED TINYINT
DatabaseErrorKind::SerializationFailure has been added, corresponding to
SQLSTATE code 40001 (A SERIALIZABLE isolation level transaction failed to
commit due to a read/write dependency on another transaction). This error is
currently only detected on PostgreSQL.
Diesel CLI can now generate completions for zsh and fish. See diesel completions --help for details.
#[belongs_to] can now accept types that are generic over lifetimes (for
example, if one of the fields has the type Cow<'a, str>). To define an
association to such a type, write #[belongs_to(parent = "User<'_>")]
Nullable<Text> now supports ilike expression on in PostgreSQL.
diesel_manage_updated_at('table_name') is now available on SQLite. This
function can be called in your migrations to create a trigger which
automatically sets the updated_at column, unless that column was updated in
the query.
Diesel's derives now require that extern crate diesel; be at your crate root
(e.g. src/lib.rs or src/main.rs)
Tinyint has been renamed to TinyInt and an alias has been created from Tinyint to TinyInt.
The minimal officially supported rustc version is now 1.31.0
This is a small bugfix release, addressing an issue with MySQL 8.0. The behavior of the C API in libmysqlclient changed in this version of MySQL, caus
This is a small bugfix release, addressing an issue with MySQL 8.0. The behavior of the C API in libmysqlclient changed in this version of MySQL, causing problems when a connection pool was used with Diesel.
If you are not using MySQL, or are on a version older than 8.0, this release does not affect you.
.execute or
.batch_execute with a single query that returned a result set (such as our
SELECT 1 health check in r2d2).This release contains two major bugfixes. This release fixes the behavior of unsigned types on MySQL, and a compile time issue caused by the use of #[
This release contains two major bugfixes. This release fixes the behavior of unsigned types on MySQL, and a compile time issue caused by the use of #[sql_name] in sql_function! with no return type. This release only affects users who are using unsigned types on MySQL, or who had code which failed to compile with 1.3.1.
The behavior of unsigned types in MySQL has been corrected to properly set the
is_unsigned flag.
Fixed an issue with sql_function! when #[sql_name] was used on functions
with no return type.
Because of this, we are deprecating diesel_infer_schema. 1.3 will be the final release of that crate. However, diesel_infer_schema 1.3 will continue t…
This release includes a couple of major changes to how Diesel projects are developed. In the past, we've had 2 ways to generate schema.rs. A procedural macro called infer_schema!, and a CLI command diesel print-schema. We've recommended using the CLI command for a long time, but infer_schema! was still useful for early prototypes.
At the beginning of a project, your database schema changes much more frequently. It's extremely annoying to have to remember to run a second command after running your migrations.
Diesel CLI 1.3 now supports a configuration file to customize its behavior. One of the new capabilities this provides is the ability to automatically regenerate schema.rs whenever you run or revert a migration. This means you no longer have to remember to run diesel print-schema when things change.
Because of this, we are deprecating diesel_infer_schema. 1.3 will be the final release of that crate. However, diesel_infer_schema 1.3 will continue to work with diesel until at least Diesel 2.0. You can see all of the capabilities of the new configuration file at http://diesel.rs/guides/configuring-diesel-cli.
This release also includes a complete redesign of the sql_function! macro. The new syntax is significantly closer to normal Rust. For example, what used to be written as:
sql_function! {
lower, lower_t, (x: Text) -> Text,
"Here are the docs for `lower`
It's awkward to make multiline"
}
Can now be written as:
sql_function! {
/// Here are the docs for `lower`
/// It's just a normal doc comment.
fn lower(x: Text) -> Text;
}
The new form also supports much more than the old one, including aggregate functions, function renaming, and generic functions. Things like MAX could previously not be expressed with sql_function!. However, now the definition looks like this:
sql_function! {
#[aggregate]
fn max<ST: SqlOrd + IntoNullable>(expr: ST) -> ST::Nullable;
}
Finally, the redesigned sql_function! supports user defined functions on SQLite. SQLite differs from other databases, in that custom functions aren't defined in SQL. Instead you give it a C function pointer to use for the body. With Diesel, you can just give us any Rust closure that takes appropriate argument types, and we'll handle gluing that to SQLite for you.
You can find examples for all of this in the docs for sql_function!.
In addition to the headline features, this release includes a ton of quality of life changes including expanded support for locking clauses, more global support for mathematic operators, and more. As always, for a full list of changes you can find it in [the changelog].
[the changelog]: https://github.com/diesel-rs/diesel/blob/v1.3.0/CHANGELOG.md
Thank you to everyone who helped make this release happen through bug reports, and discussion on Gitter. While we don't have a way to collect stats on that form of contribution, it's greatly appreciated.
In addition to the Diesel core team, 12 people contributed code to this release. A huge thank you to:
Diesel CLI now supports a configuration file. See diesel.rs/guides/configuring-diesel-cli for details.
sql_function! now supports generic functions. See the documentation for
sql_function! for more details.
sql_function! now supports aggregate functions like sum and max, by
annotating them with #[aggregate]. This skips the implementation of
NonAggregate for your function. See the documentation for
sql_function! for more details.
sql_function! now supports renaming the function by annotating it with
#[sql_name = "SOME_FUNCTION"]. This can be used to support functions with
multiple signatures such as coalesce, by defining multiple rust functions
(with different names) that have the same #[sql_name].
Added sqlite-bundled feature to diesel_cli to make installing on
some platforms easier.
Custom SQL functions can now be used with SQLite. See the docs for details.
All functions and operators provided by Diesel can now be used with numeric operators if the SQL type supports it.
PgInterval can now be used with -, *, and /.
Vec<T> is now Insertable. It is no longer required to always place an &
in front of .values.
Added support for PG tuples. See sql_types::Record for details.
FOR SHARE,
SKIP LOCKED, NO WAIT, and more. See QueryDsl for details.sql_function! has been redesigned. The syntax is now sql_function!(fn lower(x: Text) -> Text);. The output of the new syntax is slightly different
than what was generated in the past. See the documentation for
sql_function! for more details.diesel print-schema and infer_schema! now properly handle unsigned types
in MySQLdiesel_infer_schema has been deprecated. diesel print-schema is now the
only way to generate database schema. Diesel CLI can be configured to
automatically regenerate your schema file when migrations are run. See
diesel.rs/guides/configuring-diesel-cli for details.
Uses of sql_function! in the form sql_function!(foo, foo_t, (x: Integer))
have been deprecated in favor of a new design (listed above). Note: Due to a
bug in Rust, you may not see
a deprecation warning from usage of the old form. As always, if you're
concerned about relying on deprecated code, we recommend attempting to build
your app with default-features turned off (specifically excluding the
with-deprecated feature).
The --whitelist and --blacklist options to diesel print-schema have been
deprecated and renamed --only-tables and --exclude-tables.
Warnings are now allowed inside the crate. The way we had attempted to deprecate old feature names caused builds to break. We are still not happy with…
Renamed x32-column-tables, x64-column-tables, and x128-column-tables to 32-column-tables, 64-column-tables, and 128-column-tables. The leading x was d
x32-column-tables, x64-column-tables, and x128-column-tables to
32-column-tables, 64-column-tables, and 128-column-tables. The leading
x was due to a bug in crates.io discovered while publishing 1.2.0. The bug
has since been fixed.This release contains several long awaited features.
This release contains several long awaited features.
We've re-introduced the ability to use bind params with the sql function, in a way which is harder to mis-use. This functionality was present prior to 1.0, but was removed when sql_function was added over concerns about its use with the rest of the query builder. Recent developments have proved those concerns to be valid, but this new API fills that niche. Thanks to @notryanb for taking the lead on this feature.
We've also added the ability to insert from a select statement (e.g. queries in the form of INSERT INTO table (...) SELECT .... This is a feature request that has come up repeatedly since release, and we're happy to finally bring it to you. We've also added alternate forms of our insert API which feel better when used with select statements. You can find the full details in the CHANGELOG.
Finally, we've rewritten our custom dervies from scratch to take advantage of new diagnostic tools in recent versions of nightly Rust. If you turn on the unstable feature of Diesel on a nightly compiler, you'll find that you get dramatically improved error messages from our derives. For the best error messages, you should also set RUSTFLAGS="--cfg procmacro2_semver_exempt".
Additionally, as of this release, Diesel is now powered by the blockchain. Because it's 2018 and that's how it works now I guess. See the CHANGELOG for full details.
In addition to the headline features, there were a ton of features that we don't have time to mention here. As always, for a full list of changes you can find a full list in the CHANGELOG.
Thank you to everyone who helped make this release happen through bug reports, and discussion on Gitter. While we don't have a way to collect stats on that form of contribution...
In addition to the Diesel core team, 14 people contributed code to this release. A huge thank you to:
Added SqlLiteral::bind().
This is intended to be used for binding values to small SQL fragments.
Use sql_query if you are writing full queries.
Added support for INSERT INTO table (...) SELECT ... queries. Tables, select
select statements, and boxed select statements can now be used just like any
other Insertable value.
Any insert query written as insert_into(table).values(values) can now be
written as values.insert_into(table). This is particularly useful when
inserting from a select statement, as select statements tend to span multiple
lines.
Diesel's derives can now produce improved error messages if you are using a
nightly compiler, and enable the unstable feature. For the best errors, you
should also set RUSTFLAGS="--cfg procmacro2_semver_exempt".
Added support for specifying ISOLATION LEVEL, DEFERRABLE, and READ ONLY
on PG transactions. See PgConnection::build_transaction for details.
BEGIN IMMEDIATE and BEGIN EXCLUSIVE on SQLite.
See SqliteConnection::immediate_transaction and
SqliteConnection::exclusive_transaction for detailsTables with more than 56 columns are now supported by enabling the
128-column-tables feature.
Delete statements can now be boxed. This is useful for conditionally modifying
the where clause of a delete statement. See DeleteStatement::into_boxed
for details.
UpdateStatement::into_boxed
for details.Added order_by as an alias for order.
Added then_order_by, which appends to an ORDER BY clause rather than
replacing it. This is useful with boxed queries to dynamically construct an
order by clause containing an unknown number of columns.
#[derive(Insertable)] can now work on structs with fields that implement
Insertable (meaning one field can map to more than one column). Add
#[diesel(embed)] to the field to enable this behavior.
Queries that treat a subselect as a single value (e.g. foo = (subselect))
are now supported by calling .single_value().
#[derive(Insertable)] implements now Insertable also on the struct itself,
not only on references to the struct
ConnectionError now implements PartialEq.
Columns generated by table! now implement Default
#[derive(AsChangeset)] now implements AsChangeset on the struct itself,
and not only on a reference to the struct
Added support for deserializing Numeric into BigDecimal on SQLite. SQLite
has no arbitrary precision type, so the result will still have floating point
rounding issues. This is primarily to support things like avg(int_col),
which we define as returning Numeric
The bounds on impl ToSql for Cow<'a, T> have been loosened to no longer
require that T::Owned: ToSql.
32-column-tables are now enabled by default.
ne_any has been renamed to ne_all.
The large-tables feature has been has been renamed to 32-column-tables.
The huge-tables feature has been renamed to 64-column-tables.
IncompleteUpdateStatement has been removed. Use UpdateStatement instead.
diesel database setup now correctly handles database URLs containing query
strings
diesel migration list shows the proper migration order when mixing
old and new timestamp formats. (The migrations were always run in the correct
order, this only affects the display logic of migration list)
#[derive(Identifiable)] now correctly associates #[primary_key] with the
column name, not field name.
Select statements can no longer incorrectly appear in an expression context.
exists can no longer incorrectly receive values other than select
statements.
MysqlConnection::establish can now properly handle IPv6 addresses wrapped in
square brackets.
* No changes
This release fixes a minor issue with our r2d2 support. In 1.1 we recommend that people access r2d2 via diesel::r2d2. However, r2d2 has a type called
This release fixes a minor issue with our r2d2 support. In 1.1 we recommend that people access r2d2 via diesel::r2d2. However, r2d2 has a type called Error, which was shadowed by our own type called Error in that same module, making it inaccessible. This release adds an alias PoolError to point at r2d2::Error.
Thanks to YetAnotherMinion for working on this release.
diesel::r2d2::PoolError as an alias for r2d2::Error. Previously this
type was inaccessible due to diesel::r2d2::Error.Due to the design of FromSql, we can't provide impls for &str and &[u8] without a breaking change. However many impls just need to parse a string or s…
The primary focus of this release was improving the ergonomics of adding support for new types in Diesel.
For implementing new SQL types, we've added #[derive(SqlType)] which implements many traits that you need to implement for every SQL type. See the documentation for HasSqlType for details on this derive.
For implementing new mappings, we've added #[derive(FromSqlRow)] and #[derive(AsExpression)]. These derives will replace the majority of the boilerplate that was previously required when supporting new types. Adding support for new types in Diesel 1.1 should only require implementing FromSql and ToSql. The derives will handle the rest.
We've also provided FromSql impls for *const str and *const [u8]. Due to the design of FromSql, we can't provide impls for &str and &[u8] without a breaking change. However many impls just need to parse a string or some bytes, and don't need the allocation that would come from String or Vec<u8>. This will require unsafe code to use, but should make certain implementations more efficient.
Finally, we've restructured how our serialize/deserialize modules are structured, and provided type aliases to make implementations of FromSql and ToSql more consise.
r2d2_diesel is Now Part of DieselFinally, this release merges r2d2_diesel into Diesel itself. The main benefit of doing this is that we can implement Connection for PooledConnection, removing the need for explicit &* when using r2d2. This should also help to prevent version mismatches when changing Diesel versions.
To use the new r2d2 support, remove r2d2 and r2d2_diesel from your Cargo.toml. Add the r2d2 to your enabled features on diesel. Replace extern crate r2d2 with pub use diesel::r2d2. Replace any r2d2_diesel:: with diesel::r2d2::.
In addition to the headline features, there were dozens of smaller additions which should make using Diesel even better! As always, you can check the CHANGELOG for a full list of changes in this release.
In addition to the Diesel core team, 8 people contributed to this release. A huge thank you to:
r2d2-diesel has been merged into Diesel proper. You should no longer rely
directly on r2d2-diesel or r2d2. The functionality of both is exposed from
diesel::r2d2.
r2d2::PooledConnection now implements Connection. This means that you
should no longer need to write &*connection when using r2d2.
The BINARY column type name is now supported for SQLite.
The QueryId trait can now be derived.
FromSqlRow can now be derived for types which implement FromSql.
AsExpression can now be derived for types which implement ToSql.
HasSqlType, NotNull, and SingleValue can now be derived with
#[derive(SqlType)]. See the docs for those traits for more information.
The return type of FromSql, FromSqlRow, and QueryableByName can now be
written as deserialize::Result<Self>.
The return type of ToSql can now be written as serialize::Result.
Added support for SQLite's INSERT OR IGNORE and MySQL's INSERT IGNORE
via the insert_or_ignore function.
min and max can now be used with array expressions.
Added diesel::dsl::array, which corresponds to a PG ARRAY[] literal.
Added the not_none! macro, used by implementations of FromSql which do not
expect NULL.
Added result::UnexpectedNullError, an Error type indicating that an
unexpected NULL was received during deserialization.
Added .or_filter, which behaves identically to .filter, but using OR
instead of AND.
helper_types now contains a type for every method defined in
expression_methods, and every function in dsl.
Added FromSql impls for *const str and *const [u8] everywhere that
String and Vec are supported. These impls do not allocate, and are
intended for use by other impls which need to parse a string or bytes, and
don't want to allocate. These impls should never be used outside of another
FromSql impl.
with-deprecated feature by adding default-features = false to
Cargo.toml.Deprecated impl_query_id! in favor of #[derive(QueryId)]
Deprecated specifying a column name as #[column_name(foo)]. #[column_name = "foo"] should be used instead.
The types module has been deprecated. It has been split into sql_types,
serialize, and deserialize.
query_source::Queryable and query_source::QueryableByName have been
deprecated. These traits have been moved to deserialize.
backend::TypeMetadata has been deprecated. It has been moved to sql_types.
types::ToSqlOutput has been deprecated. It has been renamed to
serialize::Output.
helper_types::Not is now helper_types::not
infer_schema! generates valid code when run against a database with no
tables.One column per quarter.