diesel-rs/diesel
68.3
Adequate · 28 September 2026
114.5k
lines of production code
Rust
primary language
2
measurements over time
What this system is
Diesel is a type-safe, extensible Object-Related Mapping (ORM) and database query builder for Rust. It provides a comprehensive query DSL and schema inference tools for PostgreSQL, MySQL, MariaDB, and SQLite, supporting complex operations like upserts, window functions, and batch updates. The system includes a CLI for managing migrations and schema introspection, alongside a modular architecture that allows for custom backend implementations and runtime schema handling.
How it got here
2015–2017 — Diesel 2.0 rewrite and multi-backend support
70 changes.
This period was defined by the complete internal rewrite of Diesel to version 2.0, introducing a modular AST-based query builder, a new public API, and a comprehensive instrumentation system. The project significantly expanded database support by adding first-class backends for MySQL and SQLite, while enhancing PostgreSQL with advanced type handling and connection optimizations. Concurrently, the Diesel CLI was rewritten using Clap 4, and the migration system was modernized to support Rust-based migrations and reproducible builds.
2018–2022 — Diesel 2.0 feature expansion and CLI refinement
55 changes.
This period focused on implementing core Diesel 2.0 capabilities, including a rewritten type system, upsert support, and a new migration harness. Significant effort was also directed at enhancing the CLI's schema generation with robust filtering, ordering, and handling of complex database identifiers. The work was heavily supported by extensive test coverage and the introduction of a new benchmark suite to track performance.
2023–2026 — MariaDB support and query builder expansion
58 changes.
This period focused on establishing MariaDB as a distinct backend and refactoring MySQL/MariaDB code into a shared module. It also introduced significant query builder features, including PostgreSQL COPY support, window functions, and RETURNING clause enhancements for both PostgreSQL and MariaDB.
Features
Add --diff-schema flag to generate migrations from schema.rs differences
The \diesel migration generate\ command now supports a \--diff-schema\ flag that allows users to populate generated migration files based on the difference between their existing \schema.rs\ file and the current database state. This feature introduces a new \diff\_schema\ module that compares table structures, primary keys, and foreign keys to produce the necessary SQL changes, while also adding support for generating view definitions and handling enum types in the migration output.
_diesel\cli/src/migrations · high confidence
Add Diesel SQLite-WASM example with persistent OPFS storage
This location introduces a new web-based example demonstrating Diesel ORM with SQLite compiled to WebAssembly. It provides a complete demo application (HTML, JS worker, and Rust source) that allows users to create, view, update, and delete posts. A key feature is the ability to switch between temporary in-memory storage and persistent storage using the OPFS (Origin Private File System) VFS, enabled by the \sqlite-wasm-rs\ crate and supported by a local Python server that serves the necessary Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers.
examples/sqlite/wasm · high confidence
Add Diesel-based PostgreSQL insert examples
The \examples/postgres/all\_about\_inserts\ directory now includes a complete example project demonstrating how to insert data into a PostgreSQL database using the Diesel ORM. This includes SQL migration files to create a \users\ table with automatic \updated\_at\ timestamp handling, a Rust library defining the schema and \UserForm\ struct, and various functions illustrating different insertion patterns such as default values, single/multiple columns, insertable structs, and batch inserts.
_examples/postgres/all\_about\inserts · high confidence
Add MySQL getting-started example for displaying posts
A new example binary \show\_posts.rs\ has been added to the MySQL getting-started tutorial. This example demonstrates how to establish a mutable database connection, query the \posts\ table for published entries, and display their titles and bodies to the user.
_examples/mysql/getting\_started\_step\1/src/bin · high confidence
Add MySQL getting-started example with Selectable and backend checks
A new MySQL getting-started example is provided, demonstrating how to define a \Post\ model using the \Selectable\ derive macro and \check\_for\_backend(diesel::mysql::Mysql)\ to ensure type safety for the MySQL backend. The example includes schema and connection setup, utilizing \dotenvy\ for environment variable loading and exposing the \MYSQL\_DATABASE\_URL\ (falling back to \DATABASE\_URL\) for establishing the database connection.
_examples/mysql/getting\_started\_step\1/src · high confidence
Add MySQL-like date and time type support for chrono and time crates
Users can now map MySQL \DATE\, \DATETIME\, \TIME\, and \TIMESTAMP\ columns to \chrono\ (NaiveDate, NaiveDateTime, NaiveTime) and \time\ (NaiveDate, PrimitiveDateTime, NaiveTime, OffsetDateTime) types when using the \chrono\ or \time\ features. This change introduces the \MysqlTime\ internal representation and implements serialization/deserialization logic for these libraries, enabling seamless integration of standard Rust date/time types with MySQL-like backends.
_diesel/src/mysql\_like/types/date\_and\time · high confidence
Add PostgreSQL composite types example for Diesel
Added a new example in \examples/postgres/composite\_types\ demonstrating how to use PostgreSQL composite types with Diesel. The example includes a README with step-by-step explanations, a \diesel.toml\ configuration, and source files (\lib.rs\, \schema.rs\) that show how to import data from PostgreSQL to Rust both anonymously (using tuples) and with named fields (using custom structs and \FromSql\ implementations).
_examples/postgres/composite\types, examples/postgres/relations · high confidence
Add PostgreSQL date/time type mappings for chrono, time, and std::time
Users can now map Rust date and time types to PostgreSQL \Date\, \Time\, \Timestamp\, \Timestamptz\, and \Interval\ columns. This change introduces serialization and deserialization support for \chrono\ types (\NaiveDateTime\, \DateTime\<Utc\>\, \DateTime\<Local\>\, \NaiveDate\, \NaiveTime\, \Duration\), the \time\ crate types (\PrimitiveDateTime\, \OffsetDateTime\, \NaiveDate\, \NaiveTime\), and the standard library \SystemTime\. It also defines the internal PostgreSQL wrapper types (\PgTimestamp\, \PgDate\, \PgTime\, \PgInterval\) and provides property-based tests for these types via QuickCheck.
_diesel/src/pg/types/date\_and\time · high confidence
Add Postgres COPY FROM/TO support
Diesel now supports the PostgreSQL COPY protocol for high-performance bulk data operations. This change introduces \CopyFrom\ and \CopyTo\ query builders in \diesel/src/pg/query\_builder/copy\, allowing users to efficiently import data into tables via \COPY FROM STDIN\ and export data via \COPY TO STDOUT\. The implementation includes configuration options for format (text, CSV, binary), delimiters, headers, and other standard COPY parameters, exposing these capabilities through new DSL methods on the PostgreSQL backend.
_diesel/src/pg/query\builder/copy · high confidence
Add SQLite 'All About Inserts' example with migration and tests
This change introduces a new code example for SQLite demonstrating various insert operations, including inserting default values, single and multiple columns, insertable structs, and batch inserts. The example includes a database migration to create a \users\ table and comprehensive unit tests that verify the generated SQL queries using \debug\_query\.
_examples/sqlite/all\_about\inserts · high confidence
Add SQLite getting-started example with post management and modern Diesel patterns
The \examples/sqlite/getting\_started\_step\_3\ directory now provides a complete, runnable Diesel example for SQLite, including CLI binaries for writing, publishing, viewing, and deleting posts. The example demonstrates modern Diesel practices by using \Selectable\ and \check\_for\_backend\ derive attributes on the \Post\ model, explicit \insert\_into\ usage, and mutable connection handling. It also switches from \dotenv\ to \dotenvy\ for environment variable loading and includes a \diesel.toml\ configuration for schema generation.
_examples/sqlite/getting\_started\_step\3 · high confidence
Add SQLite relations example using Diesel
A new example located at examples/sqlite/relations demonstrates how to model and query database relationships using Diesel with SQLite. It includes SQL migrations to create tables for authors, books, pages, and a many-to-many join table, along with Rust code that defines models, schema, and functions to perform one-to-many and many-to-many queries, joins, and data setup.
examples/sqlite/relations · high confidence
Add SQLite support for JSON, JSONB, and Enum types
The SQLite backend now supports serializing and deserializing \Json\ and \Jsonb\ types via \serde\_json::Value\ (behind the \serde\json\ feature flag), including a custom binary JSONB format reader/writer that avoids stack overflows on deeply nested structures. Additionally, a new \enum\\ module provides \EnumMapping\ for SQLite using integer discriminants, and basic \Numeric\ support for \BigDecimal\ is added.
diesel/src/sqlite/types · high confidence
Add SQLite/WASM example with posts table migration
The SQLite/WASM example now includes a database migration that creates a 'posts' table (with id, title, body, and published columns) and provides the corresponding down migration to drop it, enabling users to test schema creation and reversal in the WASM environment.
examples/sqlite/wasm/migrations · high confidence
Add SeaORM benchmark suite
The benchmark suite now includes SeaORM, allowing users to compare its performance against existing implementations. This addition introduces entity definitions for users, posts, and comments, along with benchmark functions for trivial queries, medium-complex queries with associations, and bulk inserts. The implementation uses sqlx for database connectivity and dotenvy for environment variable loading.
_diesel\_bench/benches/sea\_orm\benches · high confidence
Add benchmark runner and Diesel CLI wrapper scripts
Users can now run benchmarks and the Diesel CLI directly from the repository root using the new \bin/bench\ and \bin/diesel\ shell scripts. The \bin/bench\ script allows running benchmarks against SQLite, PostgreSQL, or both backends by passing the database name as an argument, while \bin/diesel\ builds and executes the Diesel CLI tool, simplifying local development and testing workflows.
bin · high confidence
Add custom type example for Diesel 2.0
This location introduces a new example demonstrating how to define and use custom PostgreSQL types (specifically an enum) with Diesel 2.0. It includes the necessary migration files to create the database schema, a schema definition generated by Diesel CLI, and Rust code showing how to map the custom type to a Rust enum for serialization and deserialization.
_examples/postgres/custom\types · high confidence
Add numeric expression operators for SQL arithmetic
Diesel now supports standard arithmetic operations (addition, subtraction, multiplication, and division) on numeric SQL expressions. This change introduces new internal types (\Add\, \Sub\, \Mul\, \Div\) that implement Rust's standard operator traits, allowing users to write expressions like \col1 + col2\ directly in their queries. The generated SQL wraps operands in parentheses to ensure correct operator precedence.
diesel/src/expression/ops · high confidence
Add or\_filter method to DeleteStatement
The DeleteStatement now supports an \or\_filter\ method, allowing users to append conditions to the WHERE clause using logical OR. This enables dynamic query construction where multiple alternative filter predicates can be combined, such as deleting rows matching either of several specific criteria.
_diesel/src/query\_builder/delete\statement · high confidence
Add support for PostgreSQL NUMERIC type and improve float error diagnostics
The PostgreSQL backend now includes a new \PgNumeric\ type that implements \FromSql\ and \ToSql\ for the \sql\_types::Numeric\ SQL type, allowing users to map PostgreSQL NUMERIC columns to Rust types. Additionally, the deserialization logic for \f32\ (Float) and \f64\ (Double) has been updated to validate byte lengths, providing clearer error messages when a numeric value is accidentally marked as a float or vice versa.
diesel/src/pg/types/floats · high confidence
Add support for deriving Rust enums mapped to database types
Users can now use the \\#\[derive(Enum)\]\ macro to map Rust enums to database columns. This change introduces the \EnumMapping\ trait and associated strategies (\StringMapping\, \IntMapping\, \EnumTypeMapping\) in \diesel/src/types/enum\_.rs\, allowing enums to be serialized as text strings, integer discriminants, or native database enum types depending on the backend and configuration.
diesel/src/types · high confidence
Add upsert support with ON CONFLICT clauses for PostgreSQL, SQLite, and MySQL
Diesel now supports upsert operations via the \ON CONFLICT\ clause for PostgreSQL (9.5+), SQLite (3.24.0+), and MySQL (5.7+). This change introduces new DSL methods such as \on\_conflict\_do\_nothing()\ and \on\_conflict()\ on \InsertStatement\, allowing users to specify conflict targets (columns or constraints) and actions. The implementation includes backend-specific handling, such as using \VALUES(column)\ for MySQL/MariaDB and requiring a \WHERE\ clause for SQLite when constructing upserts from \SELECT\ statements. New types like \Excluded\, \DecoratableTarget\, and \IncompleteDoUpdate\ are exposed to facilitate these queries.
diesel/src/upsert · high confidence
Added ClusterFuzzLite fuzzing configuration for Rust deserialization
Added configuration files to enable automated fuzzing of the project's Rust deserialization code using ClusterFuzzLite. This includes a Dockerfile based on the OSS-Fuzz Rust base builder, a build script that compiles fuzz targets and packages seed corpora, and a project configuration specifying the Rust language and address sanitizer. This change allows the project to be continuously tested for memory safety issues in its deserialization logic.
.clusterfuzzlite · high confidence
Added MySQL getting-started examples and tests
New MySQL-specific examples and integration tests have been added to the \examples/mysql\ directory, covering the 'getting started' steps (creating posts, writing, publishing, and deleting) as well as an 'all about inserts' example. These additions provide users with ready-to-run code samples and corresponding test suites for MySQL database interactions.
examples/mysql · high confidence
Added PostgreSQL composite type example migrations
The examples/postgres/composite\_types/migrations directory now includes SQL migration files that demonstrate how to define and use PostgreSQL composite types. These migrations set up helper functions for automatic timestamp management and define specific examples: a 'coordinates' table with functions to calculate distances and return composite results, and a 'colors' table with functions to convert RGB values to grey/gray composite types.
_examples/postgres/composite\types/migrations · high confidence
Added SQL collation support for PostgreSQL and SQLite
Users can now apply SQL collations to text expressions using the new \collate\ method on \TextExpressionMethods\. This change introduces a \collation\ module providing built-in collation types: \C\ and \POSIX\ for PostgreSQL, and \BINARY\, \NOCASE\, and \RTRIM\ for SQLite. A \Custom\ collation type is also available for specifying arbitrary collation names not covered by the built-ins.
diesel/src/collation · high confidence
Added SQLite migration for posts table in getting started example
The getting started example now includes a database migration that creates a 'posts' table with columns for id, title, body, and published status, along with a corresponding down migration to drop the table. This allows users to initialize the example's database schema correctly when running the tutorial.
_examples/sqlite/getting\_started\_step\3/migrations · high confidence
Added custom array example with schema migration
The \examples/postgres/custom\_arrays\ directory now includes a complete migration setup demonstrating custom PostgreSQL types and arrays. The \2024-08-15-070500\_services\ migration creates the \smdb\ schema, defines custom enum and composite types (\smdb.protocol\_type\, \smdb.service\_endpoint\), and establishes a \smdb.service\ table that utilizes these types for array columns (\dependencies\ and \endpoints\).
_examples/postgres/custom\arrays/migrations · high confidence
Added example code for dynamic schema queries
New example files have been added to the \diesel\_dynamic\_schema\ crate to demonstrate how to use dynamic tables and columns with Diesel. These examples show how to create in-memory SQLite databases, define dynamic schemas, and perform basic queries including selecting single columns, multiple columns, and filtering rows using a WHERE clause.
_diesel\_dynamic\schema/examples · high confidence
Added migration files for the SQLite getting started examples
The SQLite getting started examples (steps 1 and 2) now include the necessary migration files to create the \posts\ table. These additions provide the database schema setup required for the examples to function correctly, improving the initial user experience by ensuring the data layer is properly initialized.
_examples/sqlite/getting\_started\_step\_1/migrations, examples/sqlite/getting\_started\_step\2/migrations · high confidence
Diesel CLI documentation and license structure update
The diesel\_cli package now includes a dedicated README.md that documents installation requirements (OpenSSL, libpq, sqlite, mysql), usage commands (setup, migration, print-schema), and bash completion generation. Additionally, LICENSE-APACHE and LICENSE-MIT files are added as symlinks to the root license files to ensure proper distribution on crates.io.
_diesel\cli · high confidence
Initial MySQL backend support
Diesel now supports MySQL as a first-class database backend. This change introduces the \Mysql\ backend type, \MysqlConnection\ for establishing connections, and a comprehensive set of SQL dialect features including ON CONFLICT resolution, batch update support, window functions, and specific error number mapping for MySQL/MariaDB. Users can now query and modify MySQL databases using Diesel's standard query DSL.
diesel/src/mysql · high confidence
Initial project scaffolding and configuration
Added foundational repository configuration files including \.editorconfig\ for consistent coding styles, \.env.sample\ for local database connection setup, \.typos.toml\ for spell-checking configuration, and the initial \CHANGELOG.md\ documenting the project's version history and upcoming features.
(repo-wide) · high confidence
Introduce \`\#\[auto\_type\]\` proc-macro for Diesel query fragment type inference
The \dsl\_auto\_type\ crate now provides the \\#\[auto\_type\]\ attribute, which automatically infers the return type of a function based on its body and parameters, eliminating the need for explicit return type annotations in Diesel query builders. This feature supports complex expression types including tuples, blocks, and binary operators, while correctly handling local variable scoping, const generics, and named lifetimes. Users can also configure the naming convention (e.g., PascalCase, snake\_case) for the generated type aliases via the \type\_case\ attribute.
_dsl\_auto\type · high confidence
Introduce diesel\_infer\_query crate for SQL view nullability inference
A new \diesel\_infer\_query\ crate has been added to provide tools for analyzing SQL queries, specifically to infer the nullability of fields within SQL views. The crate exposes a \parse\_view\_def\ function that accepts \CREATE VIEW\ or plain \SELECT\ statements and returns a \ViewData\ structure representing the query's fields. It includes a \SchemaResolver\ trait that allows consumers to supply database schema information (such as which columns are nullable) so that the crate can determine the nullability of expressions in the view's SELECT clause, including literals, field references, binary operations, and functions like \COUNT\.
_diesel\_infer\query · high confidence
MariaDB backend support with RETURNING clause and error mapping
Diesel now supports MariaDB as a distinct database backend (Mariadb), separate from MySQL. This enables users to connect to MariaDB databases using the \mariadb://\ URL scheme and provides specific SQL dialect features, including support for the \RETURNING\ clause in INSERT/UPDATE/DELETE statements. The backend also implements MariaDB-specific error number mapping to correctly identify database errors such as unique violations, foreign key violations, and serialization failures.
diesel/src/mariadb · high confidence
MySQL and MariaDB query builder improvements
This change introduces several query builder enhancements for MySQL and MariaDB backends. It adds support for batch updates using a Common Table Expression (CTE) strategy, allowing efficient multi-row updates. It also introduces \execute\_returning\_id\ for single-row inserts, which retrieves the auto-increment ID directly from the statement without an extra round trip. Additionally, the limit/offset handling is refined to ensure MySQL's requirement of a preceding LIMIT clause is met when only an OFFSET is specified, and locking clauses (FOR UPDATE, FOR SHARE, SKIP LOCKED, NOWAIT) are properly implemented for these backends.
_diesel/src/mysql\_like/query\builder · high confidence
MySQL getting-started examples now support retrieving, publishing, and deleting posts
The MySQL getting-started examples have been expanded to include step 3, adding CLI tools for fetching a single post by ID, marking a post as published, and deleting posts by title pattern. These new binaries (get\_post, publish\_post, delete\_post) complement the existing show\_posts and write\_post examples, demonstrating Diesel's find, update, and delete operations alongside the previously covered insert and select workflows.
_examples/mysql/getting\_started\_step\3 · high confidence
New MySQL insert examples added
Added a new example project at examples/mysql/all\_about\_inserts that demonstrates various ways to insert data into a MySQL database using Diesel, including inserting default values, single and multiple columns, insertable structs, and batch inserts.
_examples/mysql/all\_about\inserts · high confidence
New PostgreSQL expression extensions for intervals, table exclusions, and sampling
This change introduces three new DSL traits in the PostgreSQL backend to enhance query construction. Users can now build interval expressions using the \IntervalDsl\ trait (e.g., \7.days()\) for filtering timestamp columns. The \OnlyDsl\ trait adds a \.only()\ method to tables, generating the \ONLY\ clause to exclude inherited rows in PostgreSQL inheritance hierarchies. Additionally, \TablesampleDsl\ provides \.tablesample\_bernoulli()\ and \.tablesample\_system()\ methods, allowing users to select random subsets of rows with optional seeding for reproducible results.
diesel/src/pg/expression/extensions · high confidence
New PostgreSQL expression methods for arrays, ranges, JSONB, and network types
This change introduces a comprehensive set of new PostgreSQL-specific expression methods in \diesel/src/pg/expression\. Users can now construct array literals with \array()\, perform array indexing and slicing, and use \ANY\/\ALL\ comparisons (with the legacy \any()\/\all()\ functions deprecated in favor of \eq\_any\/\ne\_all\). Range operations are expanded with methods like \is\_contained\_by\_range\, \overlaps\_with\, \contains\, \union\_range\, \difference\_range\, and \intersection\_range\, alongside functions like \lower\, \upper\, and \isempty\. JSONB manipulation is enhanced with key existence checks (\?\, \?\|\, \?&\), path retrieval (\\#\>\, \\#\>\>\), and removal (\-\, \\#-\). Network types (INET/CIDR) gain operators for containment and bitwise operations. Additionally, \IS DISTINCT FROM\ and \IS NOT DISTINCT FROM\ comparisons are now supported, along with \ILIKE\/\NOT ILIKE\ text matching and \AT TIME ZONE\ timestamp conversion.
diesel/src/pg/expression · high confidence
New PostgreSQL getting-started example with modern Diesel patterns
A new 'getting\_started\_step\_1' example for PostgreSQL has been added, demonstrating how to set up a basic Diesel project. The example uses the \Selectable\ derive macro and \check\_for\_backend\ attribute on the \Post\ model, configures schema generation via \diesel.toml\, and establishes database connections using \dotenvy\ instead of \dotenv\. It also shows how to load and display posts using a mutable connection.
_examples/postgres/getting\_started\_step\1 · high confidence
New PostgreSQL type support for arrays, JSON, network addresses, and more
Diesel now supports a wider range of PostgreSQL data types, including JSON and JSONB (via serde\_json), multi-dimensional arrays (NdArray), network addresses (Inet, Cidr via ipnet and ipnetwork features), MAC addresses (MacAddr, MacAddr8), PostgreSQL Money (PgMoney), and Multiranges. These additions allow users to map these specific database types directly to Rust types in their queries and schema definitions.
diesel/src/pg/types · high confidence
New SQL expression support for IN, CASE WHEN, EXISTS, and CAST
Diesel now provides dedicated expression nodes and DSL functions for several SQL constructs. Users can build \IN\ and \NOT IN\ queries using \eq\_any\/\ne\_all\ (which map to the new \In\ and \NotIn\ AST nodes), write conditional logic with the new \case\_when\ function (supporting \.when()\ branches and an \.otherwise()\ default), check for subquery existence with \exists()\, and perform type conversions using the \cast()\ method. These additions are backed by new internal modules (\array\_comparison\, \case\_when\, \exists\, \cast\) and helper types in \expression::helper\_types\ to ensure correct type inference and SQL generation across supported backends.
diesel/src/expression · high confidence
New SQLite connection hooks, authorizer, and security limits
The SQLite backend now exposes a comprehensive set of connection-level callbacks and safety controls. Users can register hooks for transaction lifecycle events (commit, rollback, update), database access authorization, busy handling, progress reporting, WAL checkpointing, and SQL tracing. Additionally, the connection API now includes methods to configure per-connection runtime limits (such as SQL length, column count, and expression depth) with hardened default values to prevent resource exhaustion, and supports custom SQL functions and collations.
diesel/src/sqlite/connection · high confidence
New \`grouped\_by\` API for associating loaded children with parents
The \diesel/src/associations\ module now provides the \GroupedBy\ trait and its \grouped\_by\ method, allowing users to efficiently group loaded child records (e.g., \Vec\<Post\>\) into a structure indexed by their parent records (e.g., \Vec\<User\>\). This enables clean composition of parent-child relationships in memory without requiring SQL joins. The module also introduces \try\_grouped\_by\ for handling cases where foreign keys might be null or parents are missing, and clarifies that Diesel's association model is strictly child-to-parent, removing the previous \has\_many\ concept.
diesel/src/associations · high confidence
New advanced blog CLI example with authentication and migrations
The \examples/postgres/advanced-blog-cli\ directory now contains a complete, runnable example application. It includes database migration scripts to set up \users\, \posts\, and \comments\ tables, along with a \diesel.toml\ configuration and a \.env.sample\ file for environment setup. The application features user registration and login using Argon2 password hashing, a command-line interface built with \clap\ for managing blog posts and comments, and an editor integration for writing content.
examples/postgres/advanced-blog-cli · high confidence
New aggregate and window function support with \`declare\_sql\_function\`
Diesel now provides built-in support for aggregate functions (SUM, AVG, MAX, MIN) and window functions (ROW\_NUMBER, RANK, DENSE\_RANK, PERCENT\_RANK, etc.) using the new \declare\_sql\_function\ macro. These functions can be used in standard aggregate queries or as window functions with partitioning and ordering clauses. The \now\ function now supports coercion to \Timestamptz\ and \Nullable\<Timestamptz\>\ types. Aggregate functions return nullable types and support \DISTINCT\ modifiers and filtering.
diesel/src/expression/functions · high confidence
New connection instrumentation API for monitoring database operations
Diesel now exposes a public instrumentation system that allows users to monitor database connection lifecycle events, including establishing connections, executing queries, and managing transactions (begin, commit, rollback). This is implemented via the new \Instrumentation\ trait and \InstrumentationEvent\ enum in \diesel/src/connection/instrumentation.rs\, with a global default instrumentation hook available when the \std\ feature is enabled. Third-party backend authors can also implement custom instrumentation by enabling the \i-implement-a-third-party-backend-and-opt-into-breaking-changes\ feature, which exposes additional types like \DynInstrumentation\ and \StrQueryHelper\.
diesel/src/connection · high confidence
New custom array and data types example for PostgreSQL
Added a new example in examples/postgres/custom\_arrays demonstrating how to use Diesel with PostgreSQL custom types, including enums, composite types, and arrays of custom types. The example includes a complete project structure with a dedicated 'smdb' schema, custom ProtocolType and ServiceEndpoint types, and service management logic. It also provides embedded migrations, connection handling, and documentation on best practices for working with custom PostgreSQL types in Rust.
_examples/postgres/custom\arrays · high confidence
New diesel\_bench benchmark suite for comparing Rust database crates
A new benchmark suite has been added to evaluate and compare the performance of Diesel against other Rust database connection crates, including SQLx, Rustorm, SeaORM, Quaint, Postgres, Rusqlite, Mysql, diesel-async, and wtx. The suite supports PostgreSQL, MySQL/MariaDB, and SQLite backends, providing standardized benchmarks for trivial queries, medium-complexity joins, insertions, and association loading to help track Diesel's performance and identify regressions.
_diesel\bench · high confidence
New embedded example for running Diesel with SQLite on no\_std targets
Added a new example in \examples/sqlite/embedded\ demonstrating how to run Diesel with SQLite on embedded, no\_std platforms like the ESP32-C6. This example configures the build for the \riscv32imac-unknown-none-elf\ target, sets up a custom SQLite VFS for memory-based storage, and shows how to use both static schema and \diesel-dynamic-schema\ within a constrained environment requiring manual allocator and libc provision.
examples/sqlite/embedded · high confidence
New example demonstrating various PostgreSQL update patterns
Added a new example in \examples/postgres/all\_about\_updates\ that showcases multiple ways to perform UPDATE operations using Diesel, including updating all rows, filtering updates by conditions (such as publish time), updating specific records by ID, incrementing column values, redacting multiple fields simultaneously, and using structs with \AsChangeset\ for partial updates. The example includes tests that verify the generated SQL and bind parameters for each update scenario.
_examples/postgres/all\_about\updates · high confidence
New examples for PostgreSQL composite types and SQL functions
Added two new example programs, \composite2rust\_colors.rs\ and \composite2rust\_coordinates.rs\, demonstrating how to interact with PostgreSQL composite types and custom SQL functions using Diesel. The color example shows how to define SQL functions via the \\#\[declare\_sql\_function\]\ attribute macro, map \Record\ results to Rust structs, and handle type conversions. The coordinates example illustrates reading tuple data, defining reusable type aliases, and executing single-result queries using \get\_result\.
_examples/postgres/composite\types/examples · high confidence
New migration harness with configurable transaction behavior
Diesel introduces a new migration subsystem in \diesel/src/migration\ that allows users to define and run database migrations via a new \Migration\ trait and \MigrationSource\ interface. A key behavioral change is the introduction of the \MigrationMetadata\ trait, which lets users control whether individual migrations run inside a transaction (defaulting to true) or outside of one, enabling complex operations like index creation on existing columns that require non-transactional execution. The system also includes a new SQL file (\setup\_migration\table.sql\) to initialize the \\\_diesel\_schema\_migrations\ tracking table, replacing the previous hardcoded setup logic.
diesel/src/migration · high confidence
New syntax parsing library for table and view declarations
A new \diesel\_table\_macro\_syntax\ crate has been added to provide structured parsing for Diesel table and view macro inputs. This library introduces data structures (\TableDecl\, \ViewDecl\, \ColumnDef\) and \syn\-based parsers that allow code to inspect schema definitions, including column names, types, primary keys, and optional attributes like \max\_length\ and \auto\_increment\. This enables other parts of the Diesel ecosystem to programmatically analyze and manipulate table/view definitions rather than relying solely on string-based macro expansion.
_diesel\_table\_macro\syntax/src · high confidence
New table aliasing system with self-join support
Diesel introduces a new \alias!\ macro and supporting types in \diesel::query\_source::aliasing\ that allow users to create named aliases for tables, enabling self-joins and complex query patterns. This change adds the \Alias\ struct, \AliasedField\ for typed column access, and a \FieldAliasMapper\ to handle column mapping within aliased contexts. It also implements full QueryDsl support (filter, select, find, boxed) and combination operations (union, intersect, except) for aliases, along with join capabilities (\JoinTo\) that allow aliases to join with tables and other aliases, including support for sub-joins.
_diesel/src/query\source/aliasing · high confidence
New xtask subcommands for clippy, semver checks, and test execution
The xtask tool now provides dedicated subcommands to streamline development workflows: \cargo xtask clippy\ runs clippy checks across specific database backends (Postgres, SQLite, MySQL, MariaDB) or all of them; \cargo xtask semver-checks\ validates API stability using cargo-semver-checks with configurable release types and baseline versions; \cargo xtask run-tests\ executes the test suite via cargo-nextest (or wasm-bindgen-test-runner for WebAssembly targets) with support for skipping integration/doc tests and handling backend-specific environment variables; and \cargo xtask tidy\ performs pre-commit checks including code formatting, spelling, and clippy. These commands centralize and standardize quality gates and testing procedures for the Diesel workspace.
xtask · high confidence
PostgreSQL connection rewritten with row-by-row loading and COPY support
The PostgreSQL connection implementation has been completely rewritten to introduce a new \PgRowByRowLoadingMode\ that streams results one row at a time, offering better performance and memory efficiency for large result sets compared to the previous default mode which loaded all rows at once. This change also adds support for PostgreSQL's \COPY FROM\ and \COPY TO\ operations via new \CopyFromSink\ and \CopyToBuffer\ types, and improves connection stability by using \PQsendQueryParams\ for unnamed prepared statements to enhance compatibility with connection poolers like PgBouncer.
diesel/src/pg/connection · high confidence
PostgreSQL-specific query builder implementations
This change introduces new query builder modules for the PostgreSQL backend, adding support for several database-specific features. Users can now use \DISTINCT ON\ clauses with flexible ordering, perform batch updates via a \FROM (VALUES ...)\ pattern, and apply row-level locking modifiers such as \FOR UPDATE\, \FOR SHARE\, \SKIP LOCKED\, and \NOWAIT\. Additionally, the backend now supports the \ONLY\ keyword to query parent tables without inheritance, the \TABLESAMPLE\ clause with \BERNOULLI\ or \SYSTEM\ methods and repeatable seeds, and \ON CONFLICT ON CONSTRAINT\ for upserts targeting specific unique constraints. Array comparisons for \IN\ and \NOT IN\ are also optimized to use \ANY\ and \ALL\ operators when appropriate.
_diesel/src/pg/query\builder · high confidence
Rewritten migration system with combined sources and Rust-based migrations
The \diesel\_migrations\ crate has been completely rewritten to provide a more flexible migration harness. Users can now combine migrations from multiple sources (such as embedded SQL and file-based directories) into a single execution using the new \CombinedMigrationSource\. Additionally, a new \RustMigrationSource\ allows migrations to be defined directly in Rust code via closures, functions, or custom types, rather than relying solely on SQL files. The migration harness now supports per-migration transaction control via \metadata.toml\ and includes improved error handling and documentation.
_diesel\migrations/src · high confidence
SQLite auto-extension support and function behavior flags
Users can now register callbacks that run automatically for every new SQLite connection via \register\_auto\_extension\, \cancel\_auto\_extension\, and \reset\_auto\_extension\, enabling global setup of SQL functions, collations, or aggregates. Additionally, the \SqliteFunctionBehavior\ bitflags (DETERMINISTIC, DIRECTONLY, INNOCUOUS, SUBTYPE) are exposed to control how custom SQL functions behave, with security guidance for untrusted schemas.
diesel/src/sqlite · high confidence
SQLite-specific expression methods and JSON operators
This change introduces SQLite-specific expression methods and operators in \diesel/src/sqlite/expression\. It adds the \IS\ and \IS NOT\ operators for null-safe comparisons, and the \-\>\ JSON operator (exposed via \retrieve\_as\_object\_sqlite\) for extracting values from JSON/JSONB columns. It also defines the underlying operators and helper types required for these expressions.
diesel/src/sqlite/expression · high confidence
Shared MySQL-like type implementations for numeric, JSON, and enum handling
Diesel now includes a shared \mysql\_like\ module that provides unified type mappings for MySQL and MariaDB backends. This change introduces proper support for MySQL unsigned integer types (TinyInt through BigInt), ensuring that unsigned values are correctly deserialized without overflow or sign errors. It also adds JSON serialization/deserialization support for \serde\_json::Value\ and implements enum mapping logic that validates variants against the database schema. These shared implementations replace backend-specific duplicates, ensuring consistent behavior for numeric, text, binary, and JSON columns across both MySQL and MariaDB drivers.
_diesel/src/mysql\like/types · high confidence
Support for MariaDB 13.0+ UPDATE ... RETURNING OLD\_VALUE syntax
Users can now retrieve pre-modification column values in MariaDB 13.0 and later by using the new \old\_value()\ helper within the \RETURNING\ clause of \UPDATE\ statements. This feature maps to the database's \OLD\_VALUE(col)\ syntax, allowing queries to return both the old and new values of updated columns in a single operation.
diesel/src/mariadb/returning · high confidence
Support for ON CONFLICT WHERE predicates in upserts
Diesel now supports the \ON CONFLICT ... WHERE\ clause syntax (primarily for PostgreSQL) via the new \filter\_target\ method on upsert builders. This allows users to specify a predicate that determines which unique index to match against during conflict resolution, enabling more precise control over upsert behavior. The implementation introduces internal query builder modules (\on\_conflict\_clause\, \on\_conflict\_target\, \on\_conflict\_actions\, etc.) to handle the generation of \DO NOTHING\ and \DO UPDATE\ clauses, including support for \excluded\ column references and tuple-based conflict targets.
_diesel/src/query\builder/upsert · high confidence
Support for PostgreSQL 18+ RETURNING old.column syntax
Diesel now supports the PostgreSQL 18 feature that allows referencing pre-modification column values in the RETURNING clause via the \old()\ helper. Users can call \diesel::pg::returning::old(column)\ to retrieve the original value of a column during an UPDATE or an INSERT ... ON CONFLICT ... DO UPDATE statement. For UPDATE statements, the returned type matches the column's type. For INSERT ... ON CONFLICT ... DO UPDATE statements, users must wrap the call in \.nullable()\ (e.g., \old(column).nullable()\) because newly inserted rows do not have a pre-existing value, resulting in NULL. This feature is PostgreSQL-specific and requires PostgreSQL 18 or newer; earlier versions will reject the generated SQL.
diesel/src/pg/returning · high confidence
Support for RETURNING old.column in PostgreSQL and MariaDB
Diesel now supports the \RETURNING old.column\ syntax in PostgreSQL and MariaDB, allowing users to retrieve the previous values of rows affected by \INSERT ... ON CONFLICT ... DO UPDATE\, \UPDATE\, and \DELETE\ statements. This change introduces new internal types (\ReturningClause\, \ReturningQuerySource\) to type-check these clauses, ensuring that \old\ references are only valid in contexts where previous values are available (e.g., rejecting \old\ in plain \INSERT\ or \ON CONFLICT DO NOTHING\).
_diesel/src/query\builder/returning · high confidence
Support for batch updates across multiple rows
Diesel now supports updating multiple rows in a single query. By passing a slice of changesets to \update(...).set(...)\, users can generate a batch update statement that modifies several records at once, provided the underlying database backend (PostgreSQL, MySQL, MariaDB, or SQLite) supports it. This is implemented via the new \BatchUpdate\ struct and \BatchValueHelper\ traits in the \update\_statement\ module, allowing efficient bulk modifications without requiring multiple round-trips to the database.
_diesel/src/query\_builder/update\statement · high confidence
Support for dynamic select clauses and runtime schema definitions
The \diesel\_dynamic\_schema\ crate now allows querying tables with schemas and columns defined at runtime, rather than requiring compile-time schema definitions. This change introduces new types (\Table\, \Schema\, \Column\) and a \DynamicSelectClause\ that lets users construct \SELECT\ statements with a variable number of fields. Users can now load results into a \DynamicRow\ using a custom \FromSql\ implementation to handle the untyped data, enabling flexible queries against databases where the schema is not known until execution.
_diesel\_dynamic\schema/src · high confidence
Support for generating migrations involving database enums
The migration diff tool now handles database enum types. It parses Rust enum definitions (specifically those with \Debug\ and \Enum\ derives) to extract variant names and SQL type information. For PostgreSQL, it generates \CREATE TYPE\ and \DROP TYPE\ statements. For MySQL and MariaDB, it generates the \ENUM(...)\ column definition fragments. SQLite migrations ignore enum-specific DDL as the database does not support native enums.
_diesel\_cli/src/migrations/diff\schema · high confidence
Support for window functions and aggregate expression modifiers
Diesel now supports SQL window functions and enhanced aggregate expressions. Users can define window frames using \RANGE\, \ROWS\, and \GROUPS\ modes with bounds like \UNBOUNDED PRECEDING\, \CURRENT ROW\, and \UNBOUNDED FOLLOWING\, as well as exclusion options (\EXCLUDE CURRENT ROW\, \EXCLUDE GROUP\, \EXCLUDE TIES\). Aggregates can now be filtered using the \FILTER\ clause, ordered via \ORDER BY\ within the aggregate, and scoped to partitions using \PARTITION BY\. Additionally, aggregates support \DISTINCT\ and \ALL\ prefixes. These capabilities are implemented through new DSL methods and internal expression types in the aggregate expressions module.
_diesel/src/expression/functions/aggregate\expressions · high confidence
Unified test macro for cross-platform compatibility
A new \diesel\_test\_helper\ crate provides a \\#\[test\]\ procedural macro that automatically selects the appropriate test runner based on the target environment. In WebAssembly environments (wasm32-unknown-unknown), it applies \wasm\_bindgen\_test\, while on all other platforms, it uses the standard Rust \test\ attribute, allowing developers to write tests that run seamlessly across both native and WASM targets without manual configuration.
_diesel\_test\helper · high confidence
Architecture
Refactor MySQL/MariaDB backend into shared \`mysql\_like\` module
The MySQL and MariaDB backend implementations have been reorganized into a new \diesel/src/mysql\_like\ module to share common types, value handling, and query building logic. This change introduces a \MysqlLikeBackend\ trait and shared \MysqlValue\/\MysqlType\ definitions, allowing both backends to reuse core infrastructure while maintaining their specific connection and error-mapping details. Users benefit from a more maintainable internal structure that reduces code duplication between the MySQL and MariaDB drivers.
_diesel/src/mysql\like · high confidence
Refactored MySQL/MariaDB connection layer into shared \`mysql\_like\` module
The MySQL and MariaDB connection implementations have been reorganized into a shared \mysql\_like\ module to reduce duplication. This change introduces a generic \MysqlLikeConnection\<DB\>\ struct that handles common connection logic, including URL parsing (supporting \ssl\_mode\, \ssl\_ca\, \ssl\_cert\, \ssl\_key\, \unix\_socket\, and \local\_infile\ parameters), raw connection management via \mysqlclient\_sys\, and statement binding. The refactoring ensures that both MySQL and MariaDB backends share the same underlying connection infrastructure while allowing backend-specific behaviors to be handled through the \MysqlLikeBackend\ trait.
_diesel/src/mysql\like/connection · high confidence
Refactored SelectStatement into a modular query builder with boxed and cloneable variants
The \SelectStatement\ type has been restructured into a modular query builder located in \diesel/src/query\_builder/select\_statement\. This change introduces a new \BoxedSelectStatement\ for dynamic, runtime-polymorphic queries (using \Box\<dyn QueryFragment\>\) and a \BoxedCloneSelectStatement\ for thread-safe cloning (using \Arc\<dyn QueryFragment\>\). The core \SelectStatement\ now explicitly tracks clauses (Select, From, Distinct, Where, Order, Limit/Offset, GroupBy, Having, Locking) as generic parameters, enabling compile-time validation of clause combinations. This refactoring provides the foundation for advanced features like conditional async queries, boxed subselects, and custom backend implementations by exposing the internal AST structure through new helper traits and modules.
_diesel/src/query\_builder/select\statement · high confidence
Behavioural changes
Add symlinks for LICENSE and README files in diesel crate
The diesel crate now includes symlinks for LICENSE-APACHE, LICENSE-MIT, and README.md that point to their respective parent directory files. This ensures that these files are correctly included in published crates on crates.io, improving license visibility and documentation access for users.
diesel · high confidence
Benchmark suite restructured with new database drivers and async support
The benchmark suite has been reorganized to include benchmarks for diesel-async, SeaORM, wtx, tokio-postgres, and zero-mysql/zero-postgres, while removing quaint. The refactoring introduces a centralized \consts.rs\ module for shared SQL queries and parameters, switches from \dotenv\ to \dotenvy\ for environment variable loading, and adds support for MariaDB. Benchmarks are now gated by feature flags, allowing users to selectively run specific database driver tests.
_diesel\bench/benches · high confidence
Diesel 2.0: Complete internal rewrite and new public API
Diesel has been rewritten from the ground up, introducing a new \Backend\ trait that cleanly separates database-specific logic (query building, type metadata) from the connection layer. This refactor brings a new \SqlDialect\ trait to configure SQL generation per backend, a rewritten bind serialization layer, and a new \Queryable\ trait that is now fallible. The public API has been reorganized into a new \prelude\ module, and the \table!\ macro has been rewritten as a proc-macro. Additionally, the \r2d2\ connection pooling library has been merged directly into the Diesel crate, and support for SQLite, MySQL, and MariaDB has been significantly expanded or added for the first time.
diesel/src · high confidence
Diesel CLI initial setup now uses explicit migration files for PostgreSQL timestamp helpers
The automatic setup of PostgreSQL timestamp helper functions (diesel\_manage\_updated\_at and diesel\_set\_updated\_at) has been restructured from implicit magic to explicit migration files. Users will now see dedicated up.sql and down.sql files in the initial\_setup directory, allowing them to manage these helper functions through standard migration workflows rather than having them applied automatically without version control visibility.
_diesel\_cli/src/setup\sql · high confidence
Diesel CLI rewritten with Clap 4 and new configuration system
The Diesel CLI has been completely rewritten to use Clap 4 for argument parsing, introducing a structured \diesel.toml\ configuration file (via the \config\ module) to manage settings like migration directories, schema printing filters, and custom type derives. The command structure has been reorganized into distinct subcommands (\Migration\, \Database\, \Setup\, \Completions\, \PrintSchema\) with global flags for \--database-url\, \--config-file\, \--locked-schema\, and \--migration-dir\. This change also introduces shell completion generation via \clap\_complete\, a new \Database\ subcommand group (with \setup\ and \reset\ actions), and a more robust error handling system using \thiserror\ and \tracing\ for better diagnostics and logging.
_diesel\cli/src · high confidence
Diesel Dynamic Schema now includes Apache-2.0 and MIT license files
The diesel\_dynamic\_schema crate now ships with explicit LICENSE-APACHE and LICENSE-MIT files, establishing a dual-license model (Apache-2.0 or MIT) for the project. This change clarifies the legal terms under which users may distribute, modify, and use the crate, aligning it with the broader Diesel ecosystem's licensing standards.
_diesel\_dynamic\schema · high confidence
Diesel derives rewritten in \`diesel\_derives/src\`
The proc-macro implementation for Diesel's derive macros (including \AsChangeset\, \AsExpression\, \Associations\, \Enum\, \FromSqlRow\, and others) has been rewritten in the \diesel\_derives/src\ directory. This change updates the internal code generation logic for these derives, affecting how Diesel generates SQL query and serialization code for user-defined types.
_diesel\derives/src · high confidence
Diesel query DSL traits are reorganized into a modular structure
The \diesel/src/query\_dsl\ module has been refactored to split the monolithic query DSL implementation into distinct, single-responsibility traits. This change introduces dedicated modules for specific query operations, including \belonging\_to\_dsl\ for association queries, \boxed\_dsl\ and \boxed\_clone\_dsl\ for query boxing, \combine\_dsl\ for set operations (UNION, INTERSECT, EXCEPT), \distinct\_dsl\ for DISTINCT and DISTINCT ON, \filter\_dsl\ for WHERE clauses, \group\_by\_dsl\ and \having\_dsl\ for aggregation filtering, \join\_dsl\ for JOIN operations, \limit\_dsl\ and \offset\_dsl\ for pagination, \load\_dsl\ for execution, \locking\_dsl\ for row locking, \order\_dsl\ and \positional\_order\_dsl\ for sorting, \save\_changes\_dsl\ for upserts, \select\_dsl\ for column selection, and \single\_value\_dsl\ for scalar results. This modularization improves code maintainability and allows for more granular trait bounds in generic code.
_diesel/src/query\dsl · high confidence
Extracted attribute parsing logic into diesel\_attribute\_parser with MariaDB support
The attribute parsing code has been extracted from diesel\_derives into the new diesel\_attribute\_parser crate. This change introduces a dedicated parser for the new \\#\[diesel(mariadb\_type(...))\]\ attribute, providing a specific MariaDB type mapping that replaces the previous fallback to \mysql\_type\. The module also includes parsers for existing attributes like \belongs\_to\, \postgres\_type\, and \sqlite\_type\, along with a deprecated module that handles legacy attribute forms and provides migration hints to users.
_diesel\_attribute\parser · high confidence
Include generated migrations in PostgreSQL getting started examples
The PostgreSQL getting started examples (steps 1, 2, and 3) now include the generated Diesel migration files. This ensures that the example projects contain the necessary SQL scripts to set up the database schema, including the initial Diesel helper functions and the \posts\ table creation, allowing users to run the examples without needing to generate migrations locally first.
_examples/postgres/getting\_started\_step\_1/migrations, examples/postgres/getting\_started\_step\_2/migrations, examples/postgres/getting\_started\_step\3/migrations · high confidence
Internal migration directory scanning logic and license symlinks
The \diesel\_migrations/migrations\_internals\ crate now includes internal utilities for scanning migration directories, specifically filtering out empty directories and hidden files during migration discovery. Additionally, license files (LICENSE-APACHE and LICENSE-MIT) are now provided as symlinks in the \diesel\_migrations\ and \diesel\_migrations/migrations\_internals\ directories to point to the root license files.
_diesel\_migrations/migrations\internals · high confidence
Internal module reorganization and feature-gated macro expansion
The \diesel/src/internal\ module has been restructured to consolidate internal implementation details, including new modules for derives, SQL functions, and table macros. This change introduces feature-gated macro expansions (e.g., \expand\_pg\, \expand\_mysql\) to conditionally include backend-specific code, and defines \MAX\_COLUMN\_COUNT\ constants that allow users to configure table column limits via the \custom-count-column-tables\ feature or standard size variants (16, 32, 64, 128 columns).
diesel/src/internal · high confidence
Internal refactoring of query builder AST nodes
The \diesel/src/query\_builder/nodes\ module has been restructured to improve the composability and extensibility of the query builder's abstract syntax tree. This change introduces new internal types such as \StaticQueryFragmentInstance\, \Identifier\, and \InfixNode\, which standardize how SQL fragments are constructed and traversed. These modifications support the broader migration of the query builder to use generic AST passes, making it easier to add new SQL generation capabilities in the future without altering existing public APIs.
_diesel/src/query\builder/nodes · medium confidence
New SQL type traits for aggregation and ordering
Diesel introduces the \Foldable\ and \SqlOrd\ marker traits in the \sql\_types\ module to explicitly define which SQL types support aggregate functions (\SUM\, \AVG\) and ordering operations (\MAX\, \MIN\). \Foldable\ implementations allow numeric and interval types to be used in these aggregates, while \SqlOrd\ enables ordering for standard types and specific backend types like MySQL \Datetime\ and PostgreSQL \Citext\. This change provides a more robust type system for these operations, ensuring compile-time safety for aggregation and sorting logic.
_diesel/src/sql\types · high confidence
PostgreSQL backend restructured with runtime type metadata caching and transaction builder
The PostgreSQL backend has been reorganized to introduce a runtime type metadata caching system and a new transaction builder API. Users can now benefit from automatic caching of custom PostgreSQL type OIDs via the \PgMetadataLookup\ trait and \PgMetadataCache\, which resolves type lookups at runtime and stores them to avoid repeated database queries. Additionally, the \TransactionBuilder\ allows configuring transaction details such as isolation level, read-only mode, and deferrable status before execution. The backend also exposes \PgValue\ for raw value handling and \PgNotification\ for listening to PostgreSQL notifications, while maintaining support for batch updates and distinct-on queries.
diesel/src/pg · high confidence
PostgreSQL prepared statement caching and PgBouncer compatibility
The PostgreSQL backend now supports prepared statement caching, allowing statements to be prepared once and executed multiple times with different parameters for improved performance. For queries that are not cached, the implementation uses \PQsendQueryParams\ to combine preparation and execution into a single transaction, ensuring compatibility with PgBouncer which cannot handle unnamed prepared statements split across separate transactions.
diesel/src/pg/connection/stmt · high confidence
Refactored MySQL/MariaDB statement execution into a shared \`mysql\_like\` module
The MySQL and MariaDB statement handling logic has been consolidated into a new \diesel/src/mysql\_like/connection/stmt\ module. This change introduces a shared \StatementIterator\ and \StatementMetadata\ implementation that both database backends now use, replacing previous separate implementations. The refactoring includes specific handling for MariaDB's behavior where statement metadata may not be available prior to execution, ensuring consistent row iteration and error mapping for both MySQL and MariaDB users.
_diesel/src/mysql\like/connection/stmt · high confidence
Refactored prepared statement caching with pluggable strategies
The internal implementation of Diesel's prepared statement caching has been refactored to use a pluggable strategy pattern. The \StatementCache\ now delegates caching logic to a \StatementCacheStrategy\ trait, allowing for distinct behaviors such as \WithCacheStrategy\ (the default, unbounded caching) and \WithoutCacheStrategy\ (disabling caching). This change introduces new public types like \StatementCacheStrategy\ and \LookupStatementResult\ for backend implementors, while preserving the existing user-facing API for controlling cache size via \set\_prepared\_statement\_cache\_size\.
_diesel/src/connection/statement\cache · high confidence
Refactored query source and join implementation
The \query\_source\ module has been restructured to improve join composition and reduce code generation overhead. A new \Join\ struct and \JoinOn\ type now explicitly represent joins, allowing for manual \ON\ clause specification and chaining. The internal type system uses Peano numbers (\Never\, \Once\, \MoreThanOnce\) to enforce that tables appear exactly once in the \FROM\ clause, preventing ambiguous column references. Additionally, \InnerJoinSource\ and \LeftOuterJoinSource\ are unified, and the \SkipSelectableExpressionBoundCheckWrapper\ is introduced to optimize compile times by skipping expensive selection checks for joins.
_diesel/src/query\source · high confidence
Refactored schema inference internals for improved reliability and clarity
The internal logic for schema inference in \diesel\_cli\ has been reorganized into a dedicated \infer\_schema\_internals\ module, separating concerns for data structures, foreign key handling, and database-specific inference. This change introduces stricter filtering for foreign keys to prevent code generation issues with compound keys and self-referential constraints, and adds support for sorting columns by name or ordinal position. It also improves the handling of SQL comments, allowing them to be displayed as Rust doc comments, and fixes issues with PostgreSQL type naming and duplicate foreign key detection.
_diesel\_cli/src/infer\_schema\internals · high confidence
Restructure internal macro implementation into modular files
The internal macro implementation in \diesel/src/macros\ has been reorganized into separate modules (\internal.rs\, \mod.rs\, \ops.rs\, \static\_cond.rs\) to improve maintainability. This change introduces a vendored \static\_cond\ macro for compile-time conditionals, extracts operator implementation logic (numeric, date/time, network) into \ops.rs\, and refactors the \table!\ and \joinable!\ macro definitions. For users, this is an internal refactoring that preserves existing public API behavior while cleaning up the codebase structure.
diesel/src/macros · high confidence
Restructured expression methods into dedicated traits with improved type inference and new text operations
The expression method traits in \diesel/src/expression\_methods\ have been reorganized into specific modules (\BoolExpressionMethods\, \TextExpressionMethods\, \GlobalExpressionMethods\, etc.) to improve clarity and type inference. Boolean expressions now use a \PreferredBoolSqlType\ trait to allow the compiler to infer the correct SQL type for \AND\/\OR\ operations without explicit type parameters, and \BoolExpressionMethods\ no longer forces nullable results. Text expressions now include a \collate\ method for controlling sort order (e.g., case-insensitive matching via \NoCase\), and \LIKE\/\NOT LIKE\ operations support an \escape\ method to define custom escape characters. Additionally, \eq\_any\ and \ne\_all\ are consolidated into \eq\_all\ and \ne\_all\ for tuple comparisons, and JSON/JSONB methods are exposed via \AnyJsonExpressionMethods\ for PostgreSQL and SQLite.
_diesel/src/expression\methods · high confidence
Restructured insert statement query builder with new batch and upsert support
The insert statement query builder has been refactored into a modular structure under \diesel/src/query\_builder/insert\_statement\, introducing dedicated modules for batch inserts, column lists, and insert-from-select operations. This change adds support for batch insert statements with explicit RETURNING clauses on SQLite, enables INSERT INTO ... SELECT syntax, and provides common upsert functionality (INSERT OR IGNORE, REPLACE) that can be specialized by third-party backends. The \InsertStatement\ struct and its associated traits have been reorganized to support these capabilities while maintaining backward compatibility through feature flags.
_diesel/src/query\_builder/insert\statement · high confidence
Rewrite of \`embed\_migrations!\` macro to ensure reproducible builds
The \embed\_migrations!\ macro in \diesel\_migrations/migrations\_macros\ has been rewritten as a proper procedural macro to guarantee reproducible builds. This change ensures that embedding the same migrations produces identical crate metadata regardless of the build directory or path canonicalization differences. Additionally, the macro now supports running migrations without a \down.sql\ file and includes documentation on how to handle automatic rebuilds when migration files change.
_diesel\_migrations/migrations\macros · high confidence
Rewritten query builder with new AST pass system and bind collection
The query builder module has been completely rewritten to use a new multi-pass AST execution model. The core \AstPass\ struct now drives SQL generation, bind parameter collection, and prepared statement caching through distinct phases, allowing backends to handle these concerns separately. A new \BindCollector\ trait and \RawBytesBindCollector\ implementation manage the serialization of bind parameters, while \MoveableBindCollector\ and \CollectedQuery\ support moving bind data across threads for async contexts. The module also introduces new clause types for \GROUP BY\, \HAVING\, \DISTINCT\, and locking clauses (\FOR UPDATE\, etc.), and exposes public APIs for third-party backends to implement custom query fragments and combination clauses.
_diesel/src/query\builder · high confidence
Rewritten type implementation system with proxy structs and backend-specific mappings
The \diesel/src/type\_impls\ module has been completely rewritten to use a new internal type system based on proxy structs (e.g., \StringProxy\, \NaiveDateTimeProxy\) that derive \AsExpression\ and \FromSqlRow\. This change introduces granular, feature-gated support for various data types across backends: \chrono\ and \time\ crates are now supported for date/time types with specific mappings for PostgreSQL (e.g., \Timestamptz\, \Citext\), MySQL/MariaDB (e.g., \Datetime\), and SQLite. It also adds support for \serde\_json::Value\ (JSON/JSONB), \bigdecimal::BigDecimal\, and standard primitives (including unsigned integers for MySQL). The \Option\<T\>\ handling has been refactored to implement \FromSql\, \ToSql\, and \Queryable\ directly, improving nullability handling. Additionally, tuple support has been expanded and optimized, and backend-specific features like PostgreSQL's \CChar\/\Bpchar\ and MySQL's \TinyInt\ are now correctly mapped.
_diesel/src/type\impls · high confidence
SQLite query builder refactored with batch update and offset fixes
The SQLite query builder has been restructured into dedicated modules, introducing support for batch updates via a Common Table Expression (CTE) strategy and correcting LIMIT/OFFSET handling by injecting a dummy LIMIT -1 when only an offset is specified. Additionally, the builder now implements the SqliteReturningClause for RETURNING statements and adds specific QueryFragment implementations to resolve SQLite UPSERT parsing ambiguities.
_diesel/src/sqlite/query\builder · high confidence
Split SQLite getting-started example into distinct steps
The SQLite getting-started example is now split into separate step directories (step\_1, step\_2, etc.), with each step containing its own Cargo.toml, README, and source files. Step 1 demonstrates reading posts, while step 2 adds the ability to create new posts via a new write\_post binary and NewPost model. Each step includes its own diesel.toml configuration and uses the Selectable derive with check\_for\_backend(diesel::sqlite::Sqlite) for type-safe queries.
_examples/sqlite/getting\_started\_step\2 · high confidence
Unified SQLite date/time serialization and string interoperability
The SQLite backend now provides a consistent, unified implementation for serializing and deserializing date and time types (Date, Time, Timestamp, Timestamptz) for both the \chrono\ and \time\ crates. This change standardizes how these values are encoded as strings in the database, ensuring that subsecond precision is handled uniformly across both libraries. Additionally, it enables direct interoperability between SQLite date/time columns and Rust \String\ types, allowing users to read and write these fields as plain text without requiring specific chrono or time types.
_diesel/src/sqlite/types/date\_and\time · high confidence
Updated getting started example to use modern Diesel patterns
The PostgreSQL getting started example (step 3) has been updated to use \Selectable\ and \check\_for\_backend\ derive attributes on the \Post\ model, replacing older macro-based approaches. The example now uses \dotenvy\ instead of \dotenv\ for environment variable loading, migrates to \insert\_into\ instead of the deprecated \insert\ macro, and adopts \find\ for record retrieval. Additionally, a \diesel.toml\ configuration file is included to specify schema generation output.
_examples/postgres/getting\_started\_step\_2, examples/postgres/getting\_started\_step\3 · high confidence
Fixes
Add database initialization scripts for local Docker testing
Added SQL initialization scripts for MariaDB, MySQL, and PostgreSQL databases to support local Docker-based testing. These scripts create the necessary test databases (diesel\_test and diesel\_unit\_test) and configure user permissions, enabling the test suite to run against these database backends locally.
docker · high confidence
Test coverage
Added MariaDB test fixtures for diesel\_cli print\_schema; Added MySQL snapshot tests for multi-schema print\_schema output; Added MySQL test coverage for compound key schema printing; Added compile-fail tests for aggregate and array expressions; Added compile-time tests for deprecated derive attributes; Added fuzzing harnesses for database deserialization and blob operations; Added integration test for the getting started step 1 example; Added integration tests for SQLite getting-started examples; Added integration tests for date/time expressions and numeric operators; Added integration tests for the PostgreSQL custom arrays example; Added integration tests for the getting started step 3 example; Added migration generation tests for enums, table diffs, and comprehensive type mappings; Added regression test for SQLite print-schema output; Added regression test for compound key schema printing; Added regression test for print-schema issue \#2623 in PostgreSQL; Added schema DSL test utilities for creating tables; Added schema definition tests for all supported database backends; Added snapshot tests for Diesel CLI help output; Added snapshot tests for MySQL print-schema output; Added snapshot tests for MySQL print-schema patch file handling; Added snapshot tests for MySQL print-schema with unmappable names; Added snapshot tests for PostgreSQL print-schema output; Added snapshot tests for PostgreSQL print-schema table ordering; Added snapshot tests for SQLite generated columns in print-schema; Added snapshot tests for SQLite implicit foreign key references in print-schema; Added snapshot tests for SQLite print-schema table ordering; Added snapshot tests for SQLite print\_schema with compound foreign keys; Added snapshot tests for SQLite schema patching in print-schema; Added snapshot tests for SQLite schema printing with unmappable names; Added snapshot tests for compound key schema printing in PostgreSQL; Added snapshot tests for print-schema output without documentation; Added snapshot tests for print-schema patch file handling in PostgreSQL; Added snapshot tests for print-schema with foreign keys in PostgreSQL; Added snapshot tests for print-schema with unmappable names and custom schema; Added test coverage for PostgreSQL enum set type schema printing; Added test coverage for PostgreSQL enum type renaming in print-schema; Added test coverage for SQLite multi-schema print\_schema output; Added test coverage for custom SQL type generation in diesel print-schema; Added test coverage for print-schema type name case handling; Added test coverage for print-schema with custom schema names and foreign keys; Added test coverage for print-schema with reserved names and foreign keys; Added test coverage for print\_schema with multiple schemas in PostgreSQL; Added tests for CLI schema comment display modes; Added tests for MySQL enum and set type introspection; Added tests for PostgreSQL domain type handling in print\_schema; Added tests for SQLite print-schema output with implicit rowid columns; Added tests for SQLite rowid column schema printing; Added tests for compound foreign key schema printing; Added tests for cross-file schema generation with filtered foreign keys; Added tests for custom enum derives and disabling enum type generation; Added tests for custom type imports in print-schema; Added tests for debug\_query SQL output formatting; Added tests for dynamic schema change hooks and value handling; Added tests for handling unmappable PostgreSQL table and column names; Added tests for nullable inference in database views; Added tests for print-schema allow\_tables\_to\_appear\_in\_same\_query\_config option; Added tests for print-schema column sorting and field length introspection; Added tests for print-schema table filtering on MariaDB; Added tests for print-schema table regex filtering; Added tests for print\_schema fk\_related\_tables option; Added tests for quoted schema and table names in print-schema; Added tests for table macro field length introspection; Added tests for unsigned integer schema printing in MySQL and MariaDB; Comprehensive integration tests for Diesel CLI commands; Comprehensive test suite for diesel\_derives; Expanded compile-fail tests for derive macro attributes; Expanded database migration test fixtures for MySQL, PostgreSQL, and SQLite; Expanded integration test coverage for query composition and type handling; Migrate compile tests to ui\_test framework; New test infrastructure for CLI integration tests; Snapshot-based macro expansion tests for diesel\_derives; Updated snapshot tests for diesel\_derives.
Dependencies
Diesel 2.3.13 workspace dependency updates
Diesel 2.3.13 and its associated crates have updated their dependencies to support newer versions of key libraries, including syn 3.0, clap 4.5.56, toml 1.0.0, and libsqlite3-sys (allowing versions up to 0.39.0). The CLI now uses clap\_complete for shell completions, and the benchmark suite has been updated with newer versions of sqlx, sea-orm, and other comparison tools.
(dependencies) · high confidence
Housekeeping
Added license symlinks to diesel\_table\_macro\_syntax; Documentation now includes expanded macro code examples; Removed empty test file.
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
This is the PUBLIC form of this artifact. Findings are listed in full, but the details of SECURITY findings — which rule fired, in which file, on which line, and how to fix it — are deliberately withheld, and any secret-scanner results are excluded entirely. Where detail is absent here it was REMOVED FOR PUBLICATION; it is not missing from the analysis. The complete artifact is available from the repository owner.
Score
- CAI 68 → 68 (+0.6)
- Rubric changed (rubric-2026.09.8 → rubric-2026.09.16) — scores are not directly comparable.
Lenses
- Code Health 89 → 89 (+0.0)
- Architecture 99 → 94 (-5.2)
- Maturity 59 → 59 (+0.1)
- Readiness 59 → 59 (-0.2)
- Security 84 → 87 (+3.5)
- Domain Modelling 100 → 100 (+0.0)
- Performance 100 (new)
Resolved (14)
- Documentation: no architecture or design documentation (README.md)
- Documentation: written for insiders (README.md)
- High: security finding (details withheld)
- Hotspot: diesel/src/mysql_like/connection/bind.rs (diesel/src/mysql_like/connection/bind.rs)
- Hotspot: diesel/src/mysql_like/connection/url.rs (diesel/src/mysql_like/connection/url.rs)
- Hotspot: diesel_cli/src/config.rs (diesel_cli/src/config.rs)
- Hotspot: diesel_cli/src/infer_schema_internals/data_structures.rs (diesel_cli/src/infer_schema_internals/data_structures.rs)
- Hotspot: diesel_cli/src/infer_schema_internals/sqlite.rs (diesel_cli/src/infer_schema_internals/sqlite.rs)
- Hotspot: diesel_derives/src/field.rs (diesel_derives/src/field.rs)
- Hotspot: diesel_derives/src/model.rs (diesel_derives/src/model.rs)
- Hotspot: diesel_derives/src/sql_function.rs (diesel_derives/src/sql_function.rs)
- Off-boarding risk: anonymized user #1
- Off-boarding risk: anonymized user #2
- Off-boarding risk: anonymized user #3
New (18)
- Dependency hygiene PARTLY measured — Cargo dependencies read, no committed lock to grade for currency
- Inconsistent naming for similar database operations across different contexts. execute_returning_id is specific to insert statements, while execute_returning_count is on the generic Connection trait. While domains differ, the naming convention execute_returning_* is not unified (e.g., execute_and_return_id vs execute_returning_count). More critically, execute_returning_id is only available on InsertStatement for MySQL-like connections, whereas generic connections use execute_returning_count. This creates a fragmented API for 'execute and get result' operations.
- Medium IaC: DS-0001 (.clusterfuzzlite/Dockerfile)
- Off the main sequence: diesel_attribute_parser
- Off the main sequence: diesel_infer_query
- Off the main sequence: diesel_table_macro_syntax
- Off the main sequence: dsl_auto_type
- Off the main sequence: migrations_internals
- Off-boarding risk: anonymized user #1
- Off-boarding risk: anonymized user #2
- Off-boarding risk: anonymized user #3
- Redundant methods with identical return types and likely identical implementation logic. cast and fallible_cast appear to be aliases for the same operation, creating confusion about when to use which.
- Repeated repair: diesel/src/doctest_setup.rs (diesel/src/doctest_setup.rs)
- Repeated repair: diesel/src/query_dsl/mod.rs (diesel/src/query_dsl/mod.rs)
- Repeated repair: diesel/src/sqlite/connection/sqlite_blob.rs (diesel/src/sqlite/connection/sqlite_blob.rs)
- Repetitive pattern across multiple statement types (Insert, Update, Delete) for boxing queries. While this is a common Rust pattern for trait object safety, the existence of both into_boxed and into_boxed_clone on every statement type suggests a potential duplication of intent if the clone variant is not strictly necessary for all use cases, or if the API could be unified via a single into_boxed that handles cloning internally if needed. However, the more glaring issue is the duplication of internal_into_boxed and internal_into_boxed_clone in the DSL traits (BoxedDsl and BoxedCloneDsl) which wrap these methods.
- Split diesel
- Two methods on the same trait (IntoSql) with identical signatures and return types. This suggests one is a legacy alias or a mistake in trait design.
Changes since last survey
- 51 commits — 38 feature/other, 13 fixes
By area
- (repo) — 23 commits
- diesel/src — 12 commits
- fuzz/src — 4 commits
- (root) — 3 commits
- .github/workflows — 2 commits
- diesel_migrations/migrations_macros — 2 commits
- .github/codecov.yml — 1 commit
- .github/dependabot.yml — 1 commit
- diesel_compile_tests/tests — 1 commit
- examples/sqlite — 1 commit
- fuzz/corpus — 1 commit
Notable commits
- fix: Cleanup and minor fixes
- fix: Fix jsonb doctests and gate them on SQLite 3.45
- fix: Fix the invalid dependabot config and add a 7 day cooldown
- fix: Merge pull request #5213 from LucaCappelletti94/fix/sqlite-jsonb-group-array-doctests
- fix: Merge pull request #5215 from LucaCappelletti94/fix/unchecked-bind-sql-doc
- fix: Merge pull request #5218 from zommiommy/fix/sqlite-blob-state
- fix: Merge pull request #5234 from LucaCappelletti94/dependabot-config-fix
- fix: Merge pull request #5247 from mgeisler/fix-embed-migrations-not-reproducible
- fix: fix(migrations): make embed_migrations! reproducible
- fix: fix(sqlite): close blob handles exactly once
- fix: fix(sqlite): reject before-start blob seeks
- fix: fix(sqlite): track closed blob handles with Option
- fix: fixed nullable + cleanups
- change: Add a fuzz harness for the sqlite deserialization code
- change: Add code coverage reporting to CI
- change: Apply batched suggestions from code review
- change: Bump sqlite-wasm-rs to 0.6.1
- change: Document the raw SQL appenders and their injection risk
- change: Drop the test-only cfg on set_requires_rollback_maybe_up_to_top_level
- change: Enable serde_json's float_roundtrip for json float round trip tests
- …and 31 more
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
diesel-rs/diesel was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.
About this page
- The score is its most recent published measurement, taken on 28 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit 9cca182377c40918a93120181b54c94317d68359 — the exact code this score is about.
- Scored under rubric-2026.09.16 — the same rubric and the same method as every other entry in this index.
- Measured by watchdog.canine.dev using codehealth-analyzer preprod-d46da229e3fd.