All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
- support for extracting underlying db-specific type from AnyValueRef
- Added support for SQL Server named instances with automatic port discovery via SSRP (SQL Server Resolution Protocol). You can now connect using
mssql://user:pass@host/db?instance=SQLEXPRESSand the port will be automatically discovered. - odbc: no warning when statement row count is unavailable
- Added support for ODBC. SQLx-oldapi can now connect to Oracle, Db2, Snowflake, BigQuery, Databricks, and many other databases, using locally installed ODBC drivers.
- Added support for reading and writing
uuiddata (using theuuidfeature) in MsSql and Any.
- Fixed a bug with postgres interval to string conversion.
- MySqlValueRef::format/as_bytes/as_str/as_bytes() are now public (#27)
- allow decoding postgres
intervalvalues as strings. Previously, there was no way to decode an interval without knowing in advance which representation (textual or binary) it had.
- Add support for mssql MONEY and SMALLMONEY types.
- Fix decoding of small negative unsigned integer in Mssql.
- The subdependency on aws-lc-rs (dependency of rustls) is no optional. You can use your own crypto provider (such as ring or openssl) by using the new crate feature
runtime-tokio-rustls-nocryptoinstead ofruntime-tokio-rustls.
- Fix
QueryBuilderfor Microsoft SQL Server: #11 - Add support for Microsoft SQL Server DateTime columns in sqlx macros: macros #16
- updated the dependency to "syn"
- Upgrade rustls to 0.23
- Provide detailed error messages on TLS connection issues
- mssql: Allow decoding various numeric types as i16
- Fix
COPYerror handling in Postgres
- Implement Login packet encryption in mssql:
- SQL Server has three levels of encryption support, which are now all supported by this library:
- No encryption, where all data including the password is sent in plaintext. Used only when either client or server declare missing encryption capabilities. You can enable this mode in this library by setting
encrypt=not_supportedin the connection string. - Encryption is supported on both sides, but disabled on either side. You can enable this mode in this library by setting
encrypt=offin the connection string. In this mode, the login phase will be encrypted, but data packets will be sent in plaintext. - Encryption is supported and enabled on both sides. You can enable this mode in this library by setting
encrypt=strictin the connection string. In this mode, both the login phase and data packets will be encrypted.
- No encryption, where all data including the password is sent in plaintext. Used only when either client or server declare missing encryption capabilities. You can enable this mode in this library by setting
- SQL Server has three levels of encryption support, which are now all supported by this library:
- Much improved logging in the mssql driver login phase
- Fix encoding of
DateTime<FixedOffset>in SQLite. It used to be encoded as an RFC3339 string (with a 'T' between date and time), which is inconsistent with the format used by CURRENT_TIMESTAMP in SQLite. This could easily result in nasty bugs where comparing datetimes generated by SQLite and datetimes generated from rust would return incorrect results.
- Fix decoding of MySQL
BITtype as boolean
- Add support for unsigned integers in the
Anydriver - Add support for unsigned integers in the
postgresdriver - Add a
max_sizemethod toMySqlTypeInfoallowing to retrieve the maximum size of the type (for example,TINYINT(1)has a maximum size of 1)
- Add support for decoding
DateTime<FixedOffset>in theAnydriver
- Add support for decoding all numeric types as either f32 or f64 in mssql.
- Make
AnyTypeInfoKindpublic
- Make the
Encryptenum public in the mssql driver - Further improve mssql character encoding support, thanks to https://github.com/lovasoa/lcid-to-codepage
- Add support for more character encodings and locales in mssql. Previously, only WINDOWS-1252 was supported.
- Add sqlx version information to pre-login message in mssql
- Add support for encrypted Microsoft SQL server connections (using TLS)
- Add support for the
SSLKEYLOGFILEenvironment variable for TLS decryption in Wireshark
- Fix pg i8 decode
- Fix some integer overflow errors that could potentially make app vulnerable when binding very large data.
- Further improved decimal to floating point conversion in Microsoft SQL Server
- Improved decimal to floating point conversion in Postgres and Microsoft SQL Server
- Update bundled sqlite to 3.46.0. See https://www.sqlite.org/releaselog/3_46_0.html
- Add support for decodeing Microsoft SQL Server
DATETIMEtype asDateTime<FixedOffset>. Thanks to @saltymango2619 for the contribution.
- Updated dependencies
- Added support for SSL client certificates in MySQL and Postgres
- SSL client certificates are commonly used to secure connections to databases in cloud environments. To connect to a database that requires a client certificate, you can now use the
ssl_certandssl_keyconnection options in the connection string. For example:postgres://user@host/db?ssl_cert=/path/to/client-cert.pem&ssl_key=/path/to/client-key.pem
- SSL client certificates are commonly used to secure connections to databases in cloud environments. To connect to a database that requires a client certificate, you can now use the
- Migrate to rustls 0.22
- Added support for user-defined sqlite functions
- Upgraded SQLite to 3.45.0
- Avoid systematically attaching a (potentially empty) arguments list to Query objects created with sqlx::query
- This avoids the creation of single-use prepared statements, which should slightly improve performance
- This allows multiple statements in a single call to sqlx::query in MySQL
- In MySQL, fix "zero dates" being recognized as NULL only when transmitted as binary, not as text
- In postgres, randomize the initial prepared statement name to avoid collisions when multiple network connections are initiated in parallel and end up using the same final database tcp connection. This can happen when using a connection pooler in front of the database.
- Update dependencies. The embedded SQLite version is now 3.44.0
- Report line numbers in mssql errors
- update dependencies
- Handle precise syntax error position reporting in sqlite even when executing multiple statements from a single sql string
- Better migration error handling
- Add the ability to retrieve the position of the error in the statement when an error occurs
- mssql: Support server pre-login messages with
INSTANCE,THREAD_ID,TRACE_IDandMARStokens. Mars itself is still not supported.
- More mssql connection string options:
mssql://[username[:password]@]host/database[?instance=instance_name&packet_size=packet_size&client_program_version=client_program_version&client_pid=client_pid&hostname=hostname&app_name=app_name&server_name=server_name&client_interface_name=client_interface_name&language=language]
- remove superfluous dependency to generic-array
- more encode and decode implementations for sqlite (decimal, bigdecimal, date)
- implemented decoding of postgres numeric data type as f64 (with precision loss)
- improved the precision of f64 decimal decoding in mssql
- implemented Encode and Decode on Any for decimal, bigdecimal, and json types
- add support for Json in mssql
- fix decoding MySQL DECIMAL values as f64 (used to provoke a panic)
- add support for MSSQL decimal and numeric types
- mssql: improved chrono date and time support, fix bug with timezeone decoding
- MySQL: add support for DateTime
- mssql: Add support for DATETIME and SMALLDATETIME (in addition to the existing DATETIME2)
- mssql: Add support for NUMERIC and DECIMAL types
- mssql: Avoid crashing the entire program when encountering an unknown type
- Added support for encoding and decoding NaiveTime in mssql
- Update the Any driver to take into account the new fetures of the mssql driver
- Fixed multiple issues with the mssql driver
- Fixed issues with large strings
- Fixed issues with large SQL queries
- Added support for encoding and decoding dates and datetimes
- Added support for encoding and decoding binary data
- Updated more outdated dependencies and legacy code
- Updated outdated dependencies
25 pull requests were merged this release cycle.
- [#1081]: Add
try_fromattribute forFromRowderive [@zzhengzhuo]- Exemplifies "out of sight, out of mind." It's surprisingly easy to forget about PRs when they get pushed onto the second page. We'll be sure to clean out the backlog for 0.7.0.
- [#2014]: Support additional SQLCipher options in SQLite driver. [@szymek156]
- [#2052]: Add issue templates [@abonander]
- [#2053]: Add documentation for
IpAddrsupport in Postgres [@rakshith-ravi] - [#2062]: Add extension support for SQLite [@bradfier]
- [#2063]: customizable db locking during migration [@fuzzbuck]
- [#2025]: Bump sqlformat to 2.0 [@NSMustache]
- [#2056]: chore: Switch to sha1 crate [@stoically]
- [#2071]: Use cargo check consistently in
prepare[@cycraig]
- [#1991]: Ensure migration progress is not lost for Postgres, MySQL and SQLite. [@crepererum]
- [#2023]: Fix expansion of
#[sqlx(flatten)]forFromRowderive [@RustyYato] - [#2028]: Use fully qualified path when forwarding to
#[test]from#[sqlx::test][@alexander-jackson] - [#2040]: Fix typo in
FromRowdocs [@zlidner] - [#2046]: added flag for PIPES_AS_CONCAT connection setting for MySQL to fix #2034 [@marcustut]
- [#2055]: Use unlock notify also on
sqlite3_exec[@madadam] - [#2057]: Make begin,commit,rollback cancel-safe in sqlite [@madadam]
- [#2058]: fix typo in documentation [@lovasoa]
- [#2067]: fix(docs): close code block in query_builder.rs [@abonander]
- [#2069]: Fix
preparerace condition in workspaces [@cycraig] - [#2072]: SqliteConnectOptions typo [@fasterthanlime]
- [#2074]: fix: mssql uses unsigned for tinyint instead of signed [@he4d]
- [#2081]: close unnamed portal after each executed extended query [@DXist]
- [#2086]: PgHasArrayType for transparent types fix. [@Wopple]
- NOTE: this is a breaking change and has been postponed to 0.7.0.
- [#2089]: fix: Remove default chrono dep on time for sqlx-cli [@TravisWhitehead]
- [#2091]: Sqlite explain plan log efficiency [@tyrelr]
33 pull requests were merged this release cycle.
- [#1495]: Add example for manual implementation of the
FromRowtrait [@Erik1000] - [#1822]: (Postgres) Add support for
std::net::IpAddr[@meh]- Decoding returns an error if the
INETvalue in Postgres is a prefix and not a full address (/32for IPv4,/128for IPv6).
- Decoding returns an error if the
- [#1865]: Add SQLite support for the
timecrate [@johnbcodes] - [#1902]: Add an example of how to use
QueryBuilder::separated()[@sbeckeriv] - [#1917]: Added docs for
sqlx::types::Json[@jayy-lmao] - [#1919]: Implement
CloneforPoolOptions[@Thomasdezeeuw] - [#1953]: Support Rust arrays in Postgres [@e00E]
- [#1954]: Add
push_tuplesforQueryBuilder[@0xdeafbeef] - [#1959]: Support
#[sqlx(flatten)]attribute inFromRow[@TheoOiry] - [#1967]: Add example with external query files [@JoeyMckenzie]
- [#1985]: Add
query_builder::Separated::push_bind_unseparated()[@0xdeafbeef] - [#2001]: Implement
#[sqlx::test]for general use- Includes automatic database management, migration and fixture application.
- Drops support for end-of-lifed database versions, see PR for details.
- [#2005]:
QueryBuilderimprovements [@abonander]- Raw SQL getters, new method to build
QueryAsinstead ofQuery.
- Raw SQL getters, new method to build
- [#2013]: (SQLite) Allow VFS to be set as URL query parameter [@liningpan]
- [#1679]: refactor: alias actix-* features to their equivalent tokio-* features [@robjtede]
- [#1906]: replaced all uses of "uri" to "url" [@RomainStorai]
- [#1965]: SQLite improvements [@abonander]
- [#1977]: Docs: clarify relationship between
query_as!()andFromRow[@abonander] - [#2003]: Replace
dotenvwithdotenvy[@abonander]
- [#1802]: Try avoiding a full clean in
cargo sqlx prepare --merged[@LovecraftianHorror] - [#1848]: Fix type info access in
Anydatabase driver [@raviqqe] - [#1910]: Set
CARGO_TARGET_DIRwhen compiling queries [@sedrik] - [#1915]: Pool: fix panic when using callbacks [@abonander]
- [#1930]: Don't cache SQLite connection for macros [@LovecraftianHorror]
- [#1948]: Fix panic in Postgres
BYTEAdecode [@e00E] - [#1955]: Fix typo in FAQ [@kenkoooo]
- [#1968]: (Postgres) don't panic if
SorVnotice fields are not UTF-8 [@abonander] - [#1969]: Fix sqlx-cli build [@ivan]
- [#1974]: Use the
rust-cacheaction for CI [@abonander] - [#1988]: Agree on a single default runtime for the whole workspace [@crepererum]
- [#1989]: Fix panics in
PgListener[@crepererum] - [#1990]: Switch
mastertomainin docs [@crepererum]- The change had already been made in the repo, the docs were out of date.
- [#1993]: Update versions in quickstart examples in README [@UramnOIL]
This release marks the end of the 0.5.x series of releases and contains a number of breaking changes, mainly to do with backwards-incompatible dependency upgrades.
As we foresee many more of these in the future, we surveyed the community on how to handle this; the consensus appears to be "just release breaking changes more often."
As such, we expect the 0.6.x release series to be a shorter one.
39 pull requests(!) (not counting "prepare 0.5.12 release", of course) were merged this release cycle.
- [#1384]: (Postgres) Move
server_version_numfrom trait to inherent impl [@AtkinsChang] - [#1426]: Bump
ipnetworkto 0.19 [@paolobarbolini] - [#1455]: Upgrade
timeto 0.3 [@paolobarbolini] - [#1505]: Upgrade
rustlsto 0.20 [@paolobarbolini]- Fortunately, future upgrades should not be breaking as
webpkiis no longer exposed in the API.
- Fortunately, future upgrades should not be breaking as
- [#1529]: Upgrade
bigdecimalto 0.3 [@e00E] - [#1602]: postgres: use
Oideverywhere instead ofu32[@paolobarbolini]- This drops the
Type,Decode,Encodeimpls foru32for Postgres as it was misleading. Postgres doesn't support unsigned ints without using an extension. These impls were decoding PostgresOIDs as bareu32s without any context (and trying to bind au32to a query would produce anOIDvalue in SQL). This changes that to use a newtype instead, for clarity.
- This drops the
- [#1612]: Make all
ConnectOptionstypes cloneable [@05storm26] - [#1618]: SQLite
chrono::DateTime<FixedOffset>timezone fix [@05storm26]DateTime<FixedOffset>will be stored in SQLite with the correct timezone instead of always in UTC. This was flagged as a "potentially breaking change" since it changes how dates are sent to SQLite.
- [#1733]: Update
git2to 0.14 [@joshtriplett] - [#1734]: Make
PgLTree::push()infallible and takePgLTreeLabeldirectly [@sebpuetz] - [#1785]: Fix Rust type for SQLite
REAL[@pruthvikar]- Makes the macros always map a
REALcolumn tof64instead off32as SQLite uses only 64-bit floats.
- Makes the macros always map a
- [#1816]: Improve SQLite support for sub-queries and CTEs [@tyrelr]
- This likely will change the generated code for some invocations
sqlx::query!()with SQLite.
- This likely will change the generated code for some invocations
- [#1821]: Update
uuidcrate to v1 [@paolobarbolini] - [#1901]: Pool fixes and breaking changes [@abonander]
- Renamed
PoolOptions::connect_timeouttoacquire_timeoutfor clarity. - Changed the expected signatures for
PoolOptions::after_connect,before_acquire,after_release - Changed the signature for
Pool::close()slightly- Now eagerly starts the pool closing,
.awaiting is only necessary if you want to ensure a graceful shutdown.
- Now eagerly starts the pool closing,
- Deleted
PoolConnection::release()which was previously deprecated in favor ofPoolConnection::detach(). - Fixed connections getting leaked even when calling
.close().
- Renamed
- [#1748]: Derive
PgHasArrayTypefor#[sqlx(transparent)]types [@carols10cents]- This change was released with 0.5.12 but we didn't realize it was a breaking change at the time.
It was reverted in 0.5.13 and postponed until this release.
- This change was released with 0.5.12 but we didn't realize it was a breaking change at the time.
- [#1843]: Expose some useful methods on
PgValueRef[@mfreeborn] - [#1889]: SQLx-CLI: add
--connect-timeout[@abonander]- Adds a default 10 second connection timeout to all commands.
- [#1890]: Added test for mssql LoginAck [@walf443]
- [#1891]: Added test for mssql ProtocolInfo [@walf443]
- [#1892]: Added test for mssql ReturnValue [@walf443]
- [#1895]: Add support for
i16toAnydriver [@EthanYuan] - [#1897]: Expose
ConnectOptionsandPoolOptionsonPooland database name onPgConnectOptions[@Nukesor]
- [#1782]: Reuse a cached DB connection instead of always opening a new one for
sqlx-macros[@LovecraftianHorror] - [#1807]: Bump remaining dependencies [@paolobarbolini]
- [#1808]: Update to edition 2021 [@paolobarbolini]
- Note that while SQLx does not officially track an MSRV and only officially supports the latest stable Rust, this effectively places a lower bound of 1.56.0 on the range of versions it may work with.
- [#1823]: (sqlx-macros) Ignore deps when getting metadata for workspace root [@LovecraftianHorror]
- [#1831]: Update
crcto 3.0 [@djc] - [#1887]: query_as: don't stop stream after decoding error [@lovasoa]
- [#1814]: SQLx-cli README: move
Usageto the same level asInstall[@tobymurray] - [#1815]: SQLx-cli README: reword "building in offline mode" [@tobymurray]
- [#1818]: Trim
[]from host string before passing to TcpStream [@smonv]- This fixes handling of database URLs with IPv6 hosts.
- [#1842]: Fix usage of
serde_jsonin macros [@mfreeborn] - [#1855]: Postgres: fix panics on unknown type OID when decoding [@demurgos]
- [#1856]: MySQL: support COLLATE_UTF8MB4_0900_AI_CI [@scottwey]
- Fixes the MySQL driver thinking text columns are bytestring columns when querying against a Planetscale DB.
- [#1861]: MySQL: avoid panic when streaming packets are empty [@e-rhodes]
- [#1863]: Fix nullability check for inner joins in Postgres [@OskarPersson]
- [#1881]: Fix
field is never readwarnings on Postgres test [@walf443] - [#1882]: Fix
unused result must be usedwarnings [@walf443] - [#1888]: Fix migration checksum comparison during
sqlx migrate info[@mdtusz] - [#1894]: Fix typos [@kianmeng]
This is a hotfix that reverts #1748 as that was an accidental breaking change:
the generated PgHasArrayType impl conflicts with manual impls of the trait.
This change will have to wait for 0.6.0.
27 pull requests were merged this release cycle.
- [#1641]: Postgres: Convenient wrapper for advisory locks [@abonander]
- [#1675]: Add function to undo migrations [@jdrouet]
- [#1722]: Postgres: implement
PgHasArrayTypeforserde_json::{Value, RawValue}[@abreis] - [#1736]: Derive
CloneforMySqlArgumentsandMssqlArguments[@0xdeafbeef] - [#1748]: Derive
PgHasArrayTypefor#[sqlx(transparent)]types [@carols10cents] - [#1754]: Include affected rows alongside returned rows in query logging [@david-mcgillicuddy-moixa]
- [#1757]: Implement
TypeforCow<str>for MySQL, MSSQL and SQLite [@ipetkov] - [#1769]: sqlx-cli: add
--sourceto migration subcommands [@pedromfedricci] - [#1774]: Postgres: make
extra_float_digitssettable [@abonander]- Can be set to
Nonefor Postgres or third-party database servers that don't support the option.
- Can be set to
- [#1776]: Implement close-event notification for Pool [@abonander]
- Also fixes
PgListenerpreventingPool::close()from resolving.
- Also fixes
- [#1780]: Implement query builder [@crajcan]
- See also [#1790]: Document and expand query builder [@abonander]
- [#1781]: Postgres: support
NUMERIC[]usingdecimalfeature [@tm-drtina] - [#1784]: SQLite: add
FromStr,Copy,PartialEq,Eqimpls for options enums [@andrewwhitehead]
- [#1625]: Update RustCrypto crates [@paolobarbolini]
- [#1725]: Update
heckto 0.4 [@paolobarbolini] - [#1738]: Update
regex[@Dylan-DPC] - [#1763]: SQLite: update
libsqlite3-sys[@espindola]
- [#1719]: Fix a link in
query!()docs [@vbmade2000] - [#1731]: Postgres: fix option passing logic [@liushuyu]
- [#1735]: sqlx-cli: pass
DATABASE_URLto command spawned inprepare[@LovecraftianHorror] - [#1741]: Postgres: fix typo in
TSTZRANGE[@mgrachev] - [#1761]: Fix link from
QueryAstoquery_as()in docs [@mgrachev] - [#1786]: MySQL: silence compile warnings for unused fields [@andrewwhitehead]
- [#1789]: SQLite: fix left-joins breaking
query!()macros [@tyrelr] - [#1791]: Postgres: fix newline parsing of
.pgpassfiles [@SebastienGllmt] - [#1799]:
PoolConnection: don't leak connection permit if drop task fails to run [@abonander]
20 pull requests were merged this release cycle.
- [#1610]: Allow converting
AnyConnectOptionsto a specificConnectOptions[@05storm26] - [#1652]: Implement
FromforAnyConnection[@genusistimelord] - [#1658]: Handle
SQLITE_LOCKED[@madadam] - [#1665]: Document offline mode usage with feature flags [@sedrik]
- [#1680]: Show checksum mismatches in
sqlx migrate info[@ifn3] - [#1685]: Add tip for setting
opt-levelforsqlx-macros[@LovecraftianHorror] - [#1687]: Docs:
Acquireexamples and alternative [@stoically] - [#1696]: Postgres: support for
ltree[@cemoktra] - [#1710]: Postgres: support for
lquery[@cemoktra]
- [#1605]: Remove unused dependencies [@paolobarbolini]
- [#1606]: Add target context to Postgres
NOTICElogs [@dbeckwith] - [#1684]: Macros: Cache parsed
sqlx-data.jsoninstead of reparsing [@LovecraftianHorror]
- [#1608]: Drop worker shared state in shutdown (SQLite) [@andrewwhitehead]
- [#1619]: Docs(macros): remove sentences banning usage of
as _[@k-jun] - [#1626]: Simplify
cargo-sqlxcommand-line definition [@tranzystorek-io] - [#1636]: Fix and extend Postgres transaction example [@taladar]
- [#1657]: Fix typo in macro docs [@p9s]
- [#1661]: Fix binding
Option<T>forAnydriver [@ArGGu] - [#1667]: MySQL: Avoid panicking if packet is empty [@nappa85]
- [#1692]: Postgres: Fix power calculation when encoding
BigDecimalintoNUMERIC[@VersBinarii]
Additionally, we have introduced two mitigations for the issue of the cyclic dependency on ahash:
- We re-downgraded our version requirement on
indexmapfrom1.7.0back to1.6.2so users can pin it to that version as recommended in aHash#95. - Thanks to the work of @LovecraftianHorror in #1684, we no longer require the
preserve_orderfeature ofserde_jsonwhich gives users another place to break the cycle by simply not enabling that feature.- This may introduce extra churn in Git diffs for
sqlx-data.json, however. If this is an issue for you but the dependency cycle isn't, you can re-enable thepreserve_orderfeature:
[dependencies] serde_json = { version = "1", features = ["preserve_order"] }
- This may introduce extra churn in Git diffs for
A whopping 31 pull requests were merged this release cycle!
According to this changelog, we saw 18 new contributors! However, some of these folks may have missed getting mentioned in previous entries since we only listed highlights. To avoid anyone feeling left out, I put in the effort this time and tried to list every single one here.
- [#1228]: Add
Pool::any_kind()[@nitnelave] - [#1343]: Add
Encode/Decodeimpl forCow<'_, str>[@Drevoed] - [#1474]: Derive
Clone,CopyforAnyKind[@yuyawk] - [#1497]: Update FAQ to explain how to configure docs.rs to build a project using SQLx [@russweas]
- [#1498]: Add description of migration file structure to
migrate!()docs [@zbigniewzolnierowicz] - [#1508]: Add
.persistent(bool)toQueryAs,QueryScalar[@akiradeveloper] - [#1514]: Add support for serialized threading mode to SQLite [@LLBlumire]
- [#1523]: Allow
rust_decimal::DecimalinPgRange[@meh] - [#1539]: Support
PGOPTIONSand adding custom configuration options inPgConnectOptions[@liushuyu] - [#1562]: Re-export
either::Eitherused byExecutor::fetch_many()[@DoumanAsh] - [#1584]: Add feature to use RusTLS instead of
native-tlsforsqlx-cli[@SonicZentropy] - [#1592]: Add
AnyConnection::kind()[@05storm26]
- [#1385]: Rewrite Postgres array handling to reduce boilerplate and allow custom types [@jplatte]
- [#1479]: Remove outdated mention of
runtime-async-std-native-tlsas the default runtime in README.md [@yerke] - [#1526]: Revise
Pooldocs in a couple places [@abonander] - [#1535]: Bump
libsqlite-systo0.23.1[@nitsky] - [#1551]: SQLite: make worker thread responsible for all FFI calls [@abonander]
- If you were encountering segfaults with the SQLite driver, there's a good chance this will fix it!
- [#1557]: CI: test with Postgres 14 [@paolobarbolini]
- [#1571]: Make
whoamidep optional, only pull it in for Postgres [@joshtriplett] - [#1572]: Update
rsacrate to 0.5 [@paolobarbolini] - [#1591]: List SeaORM as an ORM option in the README [@kunjee17]
- [#1601]: Update
itoaanddirs[@paolobarbolini]
- [#1475]: Fix panic when converting a negative
chrono::DurationtoPgInterval[@yuyawk] - [#1483]: Fix error when decoding array of custom types from Postgres [@demurgos
- [#1501]: Reduce
indexmapversion requirement to1.6.2[@dimfeld] - [#1511]: Fix element type given to Postgres for arrays of custom enums [@chesedo]
- [#1517]: Fix mismatched type errors in MySQL type tests [@abonander]
- [#1537]: Fix missing re-export of
PgCopyIn[@akiradeveloper] - [#1566]: Match
~/.pgpasspassword after URL parsing and fix user and database ordering [@D1plo1d] - [#1582]:
cargo sqlx prepare: Append to existingRUSTFLAGSinstead of overwriting [@tkintscher] - [#1587]: SQLite: if set, send
PRAGMA keyon a new connection before anything else. [@parazyd]- This should fix problems with being unable to open databases using SQLCipher.
A hotfix release to address the issue of the sqlx crate itself still depending on older versions of sqlx-core and
sqlx-macros.
No other changes from 0.5.8.
A total of 24 pull requests were merged this release cycle! Some highlights:
- [#1289] Support the
immutableoption on SQLite connections [@djmarcin] - [#1295] Support custom initial options for SQLite [@ghassmo]
- Allows specifying custom
PRAGMAs and overriding those set by SQLx.
- Allows specifying custom
- [#1345] Initial support for Postgres
COPY FROM/TO[@montanalow, @abonander] - [#1439] Handle multiple waiting results correctly in MySQL [@eagletmt]
- [#1392] use
resolve_pathwhen getting path forinclude_str!()[@abonander]- Fixes a regression introduced by [#1332].
- [#1393] avoid recursively spawning tasks in
PgListener::drop()[@abonander]- Fixes a panic that occurs when
PgListeneris dropped inasync fn main().
- Fixes a panic that occurs when
A large bugfix release, including but not limited to:
- [#1329] Implement
MACADDRtype for Postgres [@nomick] - [#1363] Fix
PortalSuspendedfor array of composite types in Postgres [@AtkinsChang] - [#1320] Reimplement
sqlx::Poolinternals usingfutures-intrusive[@abonander]- This addresses a number of deadlocks/stalls on acquiring connections from the pool.
- [#1332] Macros: tell the compiler about external files/env vars to watch [@abonander]
- Includes
sqlx build-scriptto create abuild.rsto watchmigrations/for changes. - Nightly users can try
RUSTFLAGS=--cfg sqlx_macros_unstableto tell the compiler to watchmigrations/for changes instead of using a build script. - See the new section in the docs for
sqlx::migrate!()for details.
- Includes
- [#1351] Fix a few sources of segfaults/errors in SQLite driver [@abonander]
- [#1323] Keep track of column typing in SQLite EXPLAIN parsing [@marshoepial]
- This fixes errors in the macros when using
INSERT/UPDATE/DELETE ... RETURNING ...in SQLite.
- This fixes errors in the macros when using
A total of 25 pull requests were merged this release cycle!
-
[#1211] Even more tweaks and fixes to the Pool internals [@abonander]
-
[#1213] Add support for bytes and
chrono::NaiveDateTimetoAny[@guylapid] -
[#1224] Add support for
chrono::DateTime<Local>toAnywithMySQL[@NatPRoach] -
[#1216] Skip empty lines and comments in pgpass files [@feikesteenbergen]
-
[#1218] Add support for
PgMoneyto the compile-time type-checking [@iamsiddhant05]
-
[#1149] Tweak and optimize Pool internals [@abonander]
-
[#1132] Remove
'staticbound onConnection::transaction[@argv-minus-one] -
[#1099] [#1097] Truncate buffer when
BufStreamis dropped [@Diggsey]
-
[#1170] Remove
Self: Typebounds inEncode/Decodeimplementations for arrays [@jplatte]Enables working around the lack of support for user-defined array types:
#[derive(sqlx::Encode)] struct Foos<'a>(&'a [Foo]); impl sqlx::Type<sqlx::Postgres> for Foos<'_> { fn type_info() -> PgTypeInfo { PgTypeInfo::with_name("_foo") } } query_as!( Whatever, "<QUERY with $1 of type foo[]>", Foos(&foo_vec) as _, )
-
[#1141] Use
u16::MAXinstead ofi16::MAXfor a check against the largest number of parameters in a query [@crajcan] -
[#1100] Explicitly
UNLISTENbefore returning connections to the pool inPgListener[@Diggsey]
-
[#1161] Catch
SQLITE_MISUSEon connection close and panic [@link2xt] -
[#1160] Do not cast pointers to
i32(cast tousize) [@link2xt] -
[#1156] Reset the statement when
fetch_manystream is dropped [@link2xt]
- Update sqlx-rt to 0.3.
-
[#983] [#1022] Upgrade async runtime dependencies [@seryl, @ant32, @jplatte, @robjtede]
- tokio 1.0
- actix-rt 2.0
-
[#854] Allow chaining
mapandtry_map[@jplatte]Additionally enables calling these combinators with the macros:
let ones: Vec<i32> = query!("SELECT 1 as foo") .map(|row| row.foo) .fetch_all(&mut conn).await?;
-
[#940] Rename the
#[sqlx(rename)]attribute used to specify the type name on the database side to#[sqlx(type_name)][@jplatte]. -
[#976] Remove the
Donetrait. The.rows_affected()method is now available as an inherent method onPgQueryResult,MySqlQueryResultand so on. [@jplatte] -
[#1007] Remove
any::AnyType(and replace with directly implementingType<Any>) [@jplatte]
-
[#919] For SQLite, add support for unsigned integers [@dignifiedquire]
-
[#1002] For SQLite,
GROUP BYinquery!caused an infinite loop at compile time. [@pymongo] -
[#979] For MySQL, fix support for non-default authentication. [@sile]
-
[#918] Recover from dropping
wait_for_conninside Pool. [@antialize]
-
[#908] Fix
whoamicrash on FreeBSD platform [@fundon] [@AldaronLau] -
[#895] Decrement pool size when connection is released [@andrewwhitehead]
-
[#878] Fix
conn.transactionwrapper [@hamza1311]conn.transaction(|transaction: &mut Transaction<Database> | { // ... });
-
[#860] Add
rename_alltoFromRowand addcamelCaseandPascalCase[@framp] -
[#839] Add (optional) support for
bstr::BStr,bstr::BString, andgit2::Oid[@joshtriplett]
-
[#852] Fix potential 100% CPU usage in
fetch_one/fetch_optional[@markazmierczak] -
[#850] Add
synchronousoption toSqliteConnectOptions[@markazmierczak]
-
[#876] Add support for
BYTEA[]to compile-time type-checking [@augustocdias]
Fix docs.rs build by enabling a runtime feature in the docs.rs metadata in Cargo.toml.
-
[#774] Fix usage of SQLx derives with other derive crates [@NyxCode]
-
[#762] Fix
migrate!()(with no params) [@esemeniuc] -
[#755] Add
kebab-casetorename_all[@iamsiddhant05] -
[#735] Support
rustls[@jplatte]Adds
-native-tlsor-rustlson each runtime feature:# previous features = [ "runtime-async-std" ] # now features = [ "runtime-async-std-native-tls" ]
-
[#718] Support tuple structs with
#[derive(FromRow)][@dvermd]
-
[#784] Use
futures_channel::oneshotin worker for big perf win [@markazmierczak]
-
[#745] Always prefer parsing of the non-localized notice severity field [@dstoeckel]
-
[#743] Consider
utf8mb4_binas a string [[@digorithm]] -
[#739] Fix minor protocol detail with
iteration-countthat was blocking Vitess [@mcronce]
-
Enable compile-time type checking from cached metadata to enable building in an environment without access to a development database (e.g., Docker, CI).
-
Initial support for Microsoft SQL Server. If there is something missing that you need, open an issue. We are happy to help.
-
SQL migrations, both with a CLI tool and programmatically loading migrations at runtime.
-
Runtime-determined database driver,
Any, to support compile-once and run with a database driver selected at runtime. -
Support for user-defined types and more generally overriding the inferred Rust type from SQL with compile-time SQL verification.
- [#418] Support zero dates and times [@blackwolf12333]
-
[#174] Inroduce a builder to construct connections to bypass the URL parsing
// MSSQL let conn = MssqlConnectOptions::new() .host("localhost") .database("master") .username("sa") .password("Password") .connect().await?; // SQLite let conn = SqliteConnectOptions::from_str("sqlite://a.db")? .foreign_keys(false) .connect().await?;
-
[#127] Get the last ID or Row ID inserted for MySQL or SQLite
// MySQL let id: u64 = query!("INSERT INTO table ( col ) VALUES ( ? )", val) .execute(&mut conn).await? .last_insert_id(); // LAST_INSERT_ID() // SQLite let id: i64 = query!("INSERT INTO table ( col ) VALUES ( ?1 )", val) .execute(&mut conn).await? .last_insert_rowid(); // sqlite3_last_insert_rowid()
-
[#263] Add hooks to the Pool:
after_connect,before_release, andafter_acquire// PostgreSQL let pool = PgPoolOptions::new() .after_connect(|conn| Box::pin(async move { conn.execute("SET application_name = 'your_app';").await?; conn.execute("SET search_path = 'my_schema';").await?; Ok(()) })) .connect("postgres:// …").await?
-
[#308] [#495] Extend
derive(FromRow)with support for#[sqlx(default)]on fields to allow reading in a partial query [@OriolMunoz] -
[#454] [[#456]] Support
rust_decimal::Decimalas an alternative tobigdecimal::BigDecimalforNUMERICcolumns in MySQL and PostgreSQL [@pimeys] -
[#181] Column names and type information is now accessible from
RowviaRow::columns()orRow::column(name)
- [#197] [#271] Add initial support for
INTERVAL(full support pending atime::Periodtype) [@dimtion]
-
Types are now inferred for expressions. This means its now possible to use
query!andquery_as!for:let row = query!("SELECT 10 as _1, x + 5 as _2 FROM table").fetch_one(&mut conn).await?; assert_eq!(row._1, 10); assert_eq!(row._2, 5); // 5 + x?
-
[#167] Support
foreign_keysexplicitly with aforeign_keys(true)method available onSqliteConnectOptionswhich is a builder for new SQLite connections (and can be passed intoPoolOptionsto build a pool).let conn = SqliteConnectOptions::new() .foreign_keys(true) // on by default .connect().await?;
-
[#430] [#438] Add method to get the raw SQLite connection handle [@agentsim]
// conn is `SqliteConnection` // this is not unsafe, but what you do with the handle will be let ptr: *mut libsqlite3::sqlite3 = conn.as_raw_handle();
-
[#164] Support
TIMESTAMP,DATETIME,DATE, andTIMEviachronoin SQLite [@felipesere] [@meteficha]
-
Transactionnow mutably borrows a connection instead of owning it. This enables a new (or nested) transaction to be started from&mut conn. -
[#145] [#444] Use a least-recently-used (LRU) cache to limit the growth of the prepared statement cache for SQLite, MySQL, and PostgreSQL [@pimeys]
- [#499]
INTEGERnow resolves toi64instead ofi32,INT4will still resolve toi32
-
[#281] Deallocate SQLite statements before closing the SQLite connection [@hasali19]
-
[#284] Fix handling of
0forBigDecimalin PostgreSQL and MySQL [@abonander]
-
[#256] Add
query_unchecked!andquery_file_unchecked!with similar semantics toquery_as_unchecked![@meh] -
[#252] [#297] Derive several traits for the
Json<T>wrapper type [@meh] -
[#261] Add support for
#[sqlx(rename_all = "snake_case")]to#[derive(Type)][@shssoichiro] -
[#253] Add support for UNIX domain sockets to PostgreSQL [@Nilix007]
-
[#251] Add support for textual JSON on MySQL [@blackwolf12333]
-
[#275] [#268] Optionally log formatted SQL queries on execution [@shssoichiro]
-
[#267] Support Cargo.toml relative
.envfiles; allows for each crate in a workspace to use their own.envfile and thus their ownDATABASE_URL[@xyzd]
-
[#241] Type name for custom enum is not always attached to TypeInfo in PostgreSQL
-
[#237] [#238] User-defined type name matching is now case-insensitive in PostgreSQL [@qtbeee]
-
[#231] Handle empty queries (and those with comments) in SQLite
-
[#228] Provide
MapRowimplementations for functions (enables.map(|row| ...)over.try_map(|row| ...))
-
[#234] Add support for
NUMERICin MySQL with thebigdecimalcrate [@xiaopengli89] -
[#227] Support
#[sqlx(rename = "new_name")]on struct fields within aFromRowderive [@sidred]
- [#214] Handle percent-encoded usernames in a database URL [@jamwaffles]
-
[#216] Mark
Cursor,Query,QueryAs,query::Map, andTransactionas#[must_use][@Ace4896] -
[#213] Remove matches dependency and use matches macro from std [@nrjais]
- [#212] Removed sneaky
println!inMySqlCursor
-
[#203] Allow an empty password for MySQL
-
[#204] Regression in error reporting for invalid SQL statements on PostgreSQL
-
[#200] Fixes the incorrect handling of raw (
r#...) fields of a struct in theFromRowderive [@sidred]
-
sqlx::Rownow has a lifetime ('c) tied to the database connection. In effect, this means that you cannot storeRows or collect them into a collection.Query(returned fromsqlx::query()) hasmap()which takes a function to map from theRowto another type to make this transition easier.In 0.2.x
let rows = sqlx::query("SELECT 1") .fetch_all(&mut conn).await?;
In 0.3.x
let values: Vec<i32> = sqlx::query("SELECT 1") .map(|row: PgRow| row.get(0)) .fetch_all(&mut conn).await?;
To assist with the above,
sqlx::query_as()now supports querying directly into tuples (up to 9 elements) or struct types with a#[derive(FromRow)].// This extension trait is needed until a rust bug is fixed use sqlx::postgres::PgQueryAs; let values: Vec<(i32, bool)> = sqlx::query_as("SELECT 1, false") .fetch_all(&mut conn).await?;
-
HasSqlType<T>: Databaseis nowT: Type<Database>to mirrorEncodeandDecode -
Query::fetch(returned fromquery()) now returns a newCursortype.Cursoris a Stream-like type where the item type borrows into the stream (which itself borrows from connection). This means that usingquery().fetch()you can now stream directly from the database with zero-copy and zero-allocation. -
Remove
PgTypeInfo::with_oidand replace withPgTypeInfo::with_name
-
Results from the database are now zero-copy and no allocation beyond a shared read buffer for the TCP stream ( in other words, almost no per-query allocation ). Bind arguments still do allocate a buffer per query.
-
[#129] Add support for SQLite. Generated code should be very close to normal use of the C API.
- Adds
Sqlite,SqliteConnection,SqlitePool, and other supporting types
- Adds
-
[#97] [#134] Add support for user-defined types. [@Freax13]
-
Rust-only domain types or transparent wrappers around SQL types. These may be used transparently inplace of the SQL type.
#[derive(sqlx::Type)] #[repr(transparent)] struct Meters(i32);
-
Enumerations may be defined in Rust and can match SQL by integer discriminant or variant name.
#[derive(sqlx::Type)] #[repr(i32)] // Expects a INT in SQL enum Color { Red = 1, Green = 2, Blue = 3 }
#[derive(sqlx::Type)] #[sqlx(rename = "TEXT")] // May also be the name of a user defined enum type #[sqlx(rename_all = "lowercase")] // similar to serde rename_all enum Color { Red, Green, Blue } // expects 'red', 'green', or 'blue'
-
Postgres further supports user-defined composite types.
#[derive(sqlx::Type)] #[sqlx(rename = "interface_type")] struct InterfaceType { name: String, supplier_id: i32, price: f64 }
-
-
[#98] [#131] Add support for asynchronous notifications in Postgres (
LISTEN/NOTIFY). [@thedodd]-
Supports automatic reconnection on connection failure.
-
PgListenerimplementsExecutorand may be used to execute queries. Be careful however as if the intent is to handle and process messages rapidly you don't want to be tying up the connection for too long. Messages received during queries are buffered and will be delivered on the next call torecv().
let mut listener = PgListener::new(DATABASE_URL).await?; listener.listen("topic").await?; loop { let message = listener.recv().await?; println!("payload = {}", message.payload); }
-
-
Add unchecked variants of the query macros. These will still verify the SQL for syntactic and semantic correctness with the current database but they will not check the input or output types.
This is intended as a temporary solution until
query_as!is able to support user defined types.query_as_unchecked!query_file_as_unchecked!
-
Add support for many more types in Postgres
JSON,JSONB[@oeb25]INET,CIDR[@PoiScript]- Arrays [@oeb25]
- Composites ( Rust tuples or structs with a
#[derive(Type)]) NUMERIC[@abonander]OID(u32)"CHAR"(i8)TIMESTAMP,TIMESTAMPTZ, etc. with thetimecrate [@utter-step]- Enumerations ( Rust enums with a
#[derive(Type)]) [@Freax13]
-
Query(andQueryAs; returned fromquery(),query_as(),query!(), andquery_as!()) now will accept both&mut Connectionor&Poolwhere as in 0.2.x they required&mut &Pool. -
Executornow takes any value that implementsExecuteas a query.Executeis implemented forQueryandQueryAsto mean exactly what they've meant so far, a prepared SQL query. However,Executeis also implemented for just&strwhich now performs a raw or unprepared SQL query. You can further use this to fetchRows from the database though it is not as efficient as the prepared API (notably Postgres and MySQL send data back in TEXT mode as opposed to in BINARY mode).use sqlx::Executor; // Set the time zone parameter conn.execute("SET TIME ZONE LOCAL;").await // Demonstrate two queries at once with the raw API let mut cursor = conn.fetch("SELECT 1; SELECT 2"); let row = cursor.next().await?.unwrap(); let value: i32 = row.get(0); // 1 let row = cursor.next().await?.unwrap(); let value: i32 = row.get(0); // 2
-
Query(returned fromquery()) no longer hasfetch_one,fetch_optional, orfetch_all. You must map the row usingmap()and then you will have aquery::Mapvalue that has the former methods available.let values: Vec<i32> = sqlx::query("SELECT 1") .map(|row: PgRow| row.get(0)) .fetch_all(&mut conn).await?;
-
[#62] [#130] [#135] Remove explicit set of
IntervalStyle. Allow usage of SQLx for CockroachDB and potentially PgBouncer. [@bmisiak] -
[#108] Allow nullable and borrowed values to be used as arguments in
query!andquery_as!. For example, where the column would resolve toStringin Rust (TEXT, VARCHAR, etc.), you may now useOption<String>,Option<&str>, or&strinstead. [@abonander] -
[#108] Make unknown type errors far more informative. As an example, trying to
SELECTaDATEcolumn will now try and tell you about thechronofeature. [@abonander]optional feature `chrono` required for type DATE of column #1 ("now")
-
[#125] [#126] Fix statement execution in MySQL if it contains NULL statement values [@repnop]
-
[#105] [#109] Allow trailing commas in query macros [@timmythetiny]
-
Fix decoding of Rows containing NULLs in Postgres #104
-
After a large review and some battle testing by @ianthetechie of the
Pool, a live leaking issue was found. This has now been fixed by @abonander in #84 which included refactoring to make the pool internals less brittle (using RAII instead of manual work is one example) and to help any future contributors when changing the pool internals. -
Passwords are now being percent-decoded before being presented to the server [@repnop]
-
[@100] Fix
FLOATandDOUBLEdecoding in MySQL
-
[#72] Add
PgTypeInfo::with_oidto allow simple construction ofPgTypeInfowhich enablesHasSqlTypeto be implemented by downstream consumers of SQLx [@jplatte] -
[#96] Add support for returning columns from
query!with a name of a rust keyword by using raw identifiers [@yaahc] -
[#71] Implement derives for
EncodeandDecode. This is the first step to supporting custom types in SQLx. [@Freax13]
- Fix decoding of Rows containing NULLs in MySQL (and add an integration test so this doesn't break again)
- Fix
query!when used on a query that does not return results
-
Fix stall when requesting TLS from a Postgres server that explicitly does not support TLS (such as postgres running inside docker) [@abonander]
-
[#66] Declare used features for
tokioinsqlx-macrosexplicitly
- [#64, #65] Fix decoding of Rows containing NULLs in MySQL [@danielakhterov]
- [#55] Use a shared tokio runtime for the
query!macro compile-time execution (under theruntime-tokiofeature) [@udoprog]
-
Support Tokio through an optional
runtime-tokiofeature. -
Support SQL transactions. You may now use the
begin()function onPoolorConnectionto start a new SQL transaction. This returnssqlx::Transactionwhich willROLLBACKonDropor can be explicitlyCOMMITusingcommit(). -
Support TLS connections.
-
Support for
SCRAM-SHA-256authentication in Postgres #37 @danielakhterov -
Implement
Debugfor Pool #42 @prettynatty
-
Support for Authentication in MySQL 5+ including the newer authentication schemes now default in MySQL 8:
mysql_native_password,sha256_password, andcaching_sha2_password. -
Chronosupport for MySQL was only partially implemented (was missingNaiveTimeandDateTime<Utc>). -
Vec<u8>(and[u8]) support for MySQL (BLOB) and Postgres (BYTEA).