25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sqlserver): tolerate malformed UTF-16 row values
t8y26aee39e884bc
diff --git a/Cargo.lock b/Cargo.lockindex 18d8f518aa..3f976828ad 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8957,8 +8957,6 @@ dependencies = [[[package]]name = "tiberius"version = "0.12.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1446cb4198848d1562301a3340424b4f425ef79f35ef9ee034769a9dd92c10d"dependencies = ["async-trait","asynchronous-codec",diff --git a/Cargo.toml b/Cargo.tomlindex a33efa9671..eb1b6cff0c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,7 +1,7 @@[workspace]resolver = "2"members = ["src-tauri", "crates/dbx-core", "crates/dbx-web", "crates/dbx-mcp", "crates/dbx-cli"]-exclude = ["vendor/ctor", "vendor/dirs-sys", "vendor/pageant", "vendor/rumqttc", "vendor/wry"]+exclude = ["vendor/ctor", "vendor/dirs-sys", "vendor/pageant", "vendor/rumqttc", "vendor/tiberius", "vendor/wry"][patch.crates-io]# Tauri 2.11 uses ctor 0.8, which excludes Rust's win7 vendor. This vendors@@ -30,6 +30,9 @@ postgres-protocol = { git = "https://github.com/t8y2/tokio-postgres-gaussdb.git"# Temporary compatibility patch for MySQL accounts using the deprecated# sha256_password auth plugin. Remove after upstream support lands.mysql_async = { git = "https://github.com/t8y2/mysql_async.git", rev = "b615bb0b10b5975182a4aa069cabc3d09021f6ab" }+# Preserve readable SQL Server result sets when a row contains an unpaired+# UTF-16 surrogate. Remove after the behavior is available in upstream tiberius.+tiberius = { path = "vendor/tiberius" }[profile.release]panic = "abort"diff --git a/vendor/tiberius/Cargo.toml b/vendor/tiberius/Cargo.tomlnew file mode 100644index 0000000000..56734780f2--- /dev/null+++ b/vendor/tiberius/Cargo.toml@@ -0,0 +1,270 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+autotests = false+edition = "2021"+name = "tiberius"+version = "0.12.3"+authors = [+ "Steffen Butzer <[email protected]>",+ "Julius de Bruijn <[email protected]>",+ "Eric Sheppard <[email protected]>",+ "Yoshua Wuyts <[email protected]>",+]+description = "A TDS (MSSQL) driver"+documentation = "https://docs.rs/tiberius/"+readme = "README.md"+keywords = [+ "tds",+ "mssql",+ "sql",+]+license = "MIT/Apache-2.0"+repository = "https://github.com/prisma/tiberius"++[package.metadata.docs.rs]+features = [+ "all",+ "docs",+]++[dependencies.async-io]+version = "1.8"+optional = true++[dependencies.async-native-tls]+version = "0.4"+features = ["runtime-async-std"]+optional = true++[dependencies.async-net]+version = "1.7"+optional = true++[dependencies.async-std]+version = "1"+features = ["attributes"]+optional = true++[dependencies.async-trait]+version = "0.1"++[dependencies.asynchronous-codec]+version = "0.6"++[dependencies.bigdecimal_]+version = "0.3"+optional = true+package = "bigdecimal"++[dependencies.byteorder]+version = "1.0"++[dependencies.bytes]+version = "1.0"++[dependencies.chrono]+version = "0.4"+optional = true+default-features = false++[dependencies.connection-string]+version = "0.2"++[dependencies.encoding_rs]+version = "0.8"++[dependencies.enumflags2]+version = "0.7"++[dependencies.futures-lite]+version = "1.12.0"+optional = true++[dependencies.futures-util]+version = "0.3"+features = [+ "io",+ "sink",+]+default-features = false++[dependencies.num-traits]+version = "0.2"++[dependencies.once_cell]+version = "1.3"++[dependencies.opentls]+version = "0.2.1"+features = [+ "io-async-std",+ "vendored",+]+optional = true++[dependencies.pin-project-lite]+version = "0.2"++[dependencies.pretty-hex]+version = "0.3"++[dependencies.rust_decimal]+version = "1.6"+optional = true++[dependencies.rustls-native-certs]+version = "0.6"+optional = true++[dependencies.rustls-pemfile]+version = "1"+optional = true++[dependencies.thiserror]+version = "1.0"++[dependencies.time]+version = "0.3"+optional = true++[dependencies.tokio]+version = "1.0"+features = [+ "net",+ "time",+]+optional = true++[dependencies.tokio-rustls]+version = "0.24.0"+features = ["dangerous_configuration"]+optional = true++[dependencies.tokio-util]+version = "0.7"+features = ["compat"]+optional = true++[dependencies.tracing]+version = "0.1"+features = ["log"]++[dependencies.uuid]+version = "1.0"++[dev-dependencies.anyhow]+version = "1"++[dev-dependencies.async-std]+version = "1"+features = ["attributes"]++[dev-dependencies.azure_identity]+version = "0.5.0"++[dev-dependencies.chrono]+version = "0.4.38"++[dev-dependencies.env_logger]+version = "0.9"++[dev-dependencies.indicatif]+version = "0.17"++[dev-dependencies.indoc]+version = "1.0.7"++[dev-dependencies.names]+version = "0.14"++[dev-dependencies.oauth2]+version = "4.2.3"++[dev-dependencies.paste]+version = "1.0"++[dev-dependencies.reqwest]+version = "0.11.10"++[dev-dependencies.tokio]+version = "1.0"+features = [+ "macros",+ "sync",+ "io-std",+ "time",+ "io-util",+ "net",+ "rt-multi-thread",+]++[dev-dependencies.tokio-util]+version = "0.7"+features = ["compat"]++[dev-dependencies.url]+version = "2.2.2"++[dev-dependencies.uuid]+version = "1.0"+features = ["v4"]++[features]+all = [+ "chrono",+ "time",+ "tds73",+ "sql-browser-async-std",+ "sql-browser-tokio",+ "sql-browser-smol",+ "integrated-auth-gssapi",+ "rust_decimal",+ "bigdecimal",+ "native-tls",+]+bigdecimal = ["bigdecimal_"]+default = [+ "tds73",+ "winauth",+ "native-tls",+]+docs = []+integrated-auth-gssapi = ["libgssapi"]+native-tls = ["async-native-tls"]+rustls = [+ "tokio-rustls",+ "tokio-util",+ "rustls-pemfile",+ "rustls-native-certs",+]+sql-browser-async-std = ["async-std"]+sql-browser-smol = [+ "async-io",+ "async-net",+ "futures-lite",+]+sql-browser-tokio = [+ "tokio",+ "tokio-util",+]+tds73 = []+vendored-openssl = ["opentls"]++[target."cfg(unix)".dependencies.libgssapi]+version = "0.4.5"+optional = true+default-features = false++[target."cfg(windows)".dependencies.winauth]+version = "0.0.4"+optional = truediff --git a/vendor/tiberius/DBX-PATCH.md b/vendor/tiberius/DBX-PATCH.mdnew file mode 100644index 0000000000..b169911d81--- /dev/null+++ b/vendor/tiberius/DBX-PATCH.md@@ -0,0 +1,24 @@+# DBX tiberius patch++This directory vendors `tiberius` 0.12.3 from crates.io. The source package is+identified by the checksum+`a1446cb4198848d1562301a3340424b4f425ef79f35ef9ee034769a9dd92c10d` and the+upstream release tag points to commit+`0e2897a276166503ba78fe3e1cee501e9a034021`.++DBX changes only SQL Server Unicode column-data decoding:++- NCHAR, NVARCHAR, and NTEXT row values replace unpaired UTF-16 surrogates with+ U+FFFD, matching the Microsoft JDBC driver's observable behavior.+- Odd byte lengths remain protocol errors, including an explicit NTEXT guard+ that prevents truncating a trailing byte and desynchronizing the TDS stream.+- Metadata, environment tokens, other protocol strings, and non-Unicode+ codepage decoding retain upstream's strict behavior.++The regression tests in `src/tds/codec/column_data.rs` exercise the decoder+with raw TDS value frames. The upstream integration fixtures are omitted from+this minimal vendor copy because the crates.io manifest does not include their+repository-only `runtimes-macro` dependency; library unit tests remain enabled.+Upstream tracks the same failure in+<https://github.com/prisma/tiberius/issues/325>. Remove this patch after an+equivalent fix is released upstream.diff --git a/vendor/tiberius/LICENSE-APACHE.txt b/vendor/tiberius/LICENSE-APACHE.txtnew file mode 100644index 0000000000..22a15a5956--- /dev/null+++ b/vendor/tiberius/LICENSE-APACHE.txt@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++Copyright 2021 Tiberius Contributors++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.diff --git a/vendor/tiberius/LICENSE-MIT.txt b/vendor/tiberius/LICENSE-MIT.txtnew file mode 100644index 0000000000..976e54d6c5--- /dev/null+++ b/vendor/tiberius/LICENSE-MIT.txt@@ -0,0 +1,25 @@+Copyright (c) 2021 Tiberius Contributors++Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/vendor/tiberius/README.md b/vendor/tiberius/README.mdnew file mode 100644index 0000000000..44398dc55b--- /dev/null+++ b/vendor/tiberius/README.md@@ -0,0 +1,144 @@+# Tiberius+[](https://crates.io/crates/tiberius)+[](https://docs.rs/tiberius)+[](https://github.com/prisma/tiberius/actions/workflows/test.yml)+[](https://discord.gg/xX4xp9x)++A native Microsoft SQL Server (TDS) client for Rust.++### Goals++- A perfect implementation of the TDS protocol.+- Asynchronous network IO.+- Independent of the network protocol.+- Support for latest versions of Linux, Windows and macOS.++### Non-goals++- Connection pooling (use [bb8](https://crates.io/crates/bb8), [mobc](https://crates.io/crates/mobc), [deadpool](https://crates.io/crates/deadpool) or any of the other asynchronous connection pools)+- Query building+- Object-relational mapping++### Supported SQL Server versions++| Version | Support level | Notes |+|---------|---------------|-------------------------------------|+| 2022 | Tested on CI | |+| 2019 | Tested on CI | |+| 2017 | Tested on CI | |+| 2016 | Should work | |+| 2014 | Should work | |+| 2012 | Should work | |+| 2008 | Should work | |+| 2005 | Should work | With feature flag `tds73` disabled. |++### Feature flags++| Flag | Description | Default |+|--------------------------|----------------------------------------------------------------------------------------------------------------------------------|------------|+| `tds73` | Support for new date and time types in TDS version 7.3. Disable if using version 7.2. | `enabled` |+| `native-tls` | Use operating system's TLS libraries for traffic encryption. | `enabled` |+| `rustls` | Use the builtin TLS implementation from rustls instead of linking to the operating system implementation for traffic encryption. | `disabled` |+| `vendored-openssl` | Statically link against OpenSSL instead of dynamically linking to the operating system implementation for traffic encryption. | `disabled` |+| `chrono` | Read and write date and time values using `chrono`'s types. (for greenfield, using time instead of chrono is recommended) | `disabled` |+| `time` | Read and write date and time values using `time` crate types. | `disabled` |+| `rust_decimal` | Read and write `numeric`/`decimal` values using `rust_decimal`'s `Decimal`. | `disabled` |+| `bigdecimal` | Read and write `numeric`/`decimal` values using `bigdecimal`'s `BigDecimal`. | `disabled` |+| `sql-browser-async-std` | SQL Browser implementation for the `TcpStream` of async-std. | `disabled` |+| `sql-browser-tokio` | SQL Browser implementation for the `TcpStream` of Tokio. | `disabled` |+| `sql-browser-smol` | SQL Browser implementation for the `TcpStream` of smol. | `disabled` |+| `integrated-auth-gssapi` | Support for using Integrated Auth via GSSAPI | `disabled` |++### Supported protocols++Tiberius does not rely on any protocol when connecting to an SQL Server instance. Instead the `Client` takes a socket that implements the `AsyncRead` and `AsyncWrite` traits from the [futures-rs](https://crates.io/crates/futures) crate.++Currently there are good async implementations for TCP in the [async-std](https://crates.io/crates/async-std), [Tokio](https://crates.io/crates/tokio) and [Smol](https://crates.io/crates/smol) projects.++To be able to use them together with Tiberius on Windows platforms with SQL Server, you should make sure that the TCP protocol is enabled, as depending on the edition, this may not be the case. Standard and Enterprise editions will have the setting enabled by default, whereas Developer, Express editions and the Windows Internal Database feature of the Windows Server OS don't.+To enable the TCP/IP protocol you may want to use the [server settings](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/enable-or-disable-a-server-network-protocol) the [command line](https://docs.microsoft.com/en-us/sql/powershell/how-to-enable-tcp-sqlps).+In the official [Docker image](https://hub.docker.com/_/microsoft-mssql-server) TCP is is enabled by default.++Named pipes should work by using the [NamedPipeClient](https://docs.rs/tokio/1.9.0/tokio/net/windows/named_pipe/struct.NamedPipeClient.html) from the latest Tokio versions.++The shared memory protocol is not documented and seems there are no Rust crates implementing it.++### Encryption (TLS/SSL)++Tiberius can be set to use two different implementations of TLS connection encryption. By default it uses `native-tls`, linking to the TLS library provided by the operating system. This is a good practice and in case of security vulnerabilities, upgrading the system libraries fixes the vulnerability in Tiberius without a recompilation. On Linux we link against OpenSSL, on Windows against schannel and on macOS against Security Framework.++Alternatively one can use the `rustls` feature flag to use the Rust native TLS implementation. This way there are no dynamic dependencies to the system. This might be useful in certain installations, but requires a rebuild to update to a new TLS version. For some reasons the Security Framework on macOS does not work with SQL Server TLS settings, and on Apple platforms if needing TLS it is recommended to use `rustls` instead of `native-tls`. The other option is to use the `vendored-openssl` feature flag, that statically links against the latest OpenSSL implementation.++The crate can also be compiled without TLS support, but not with both features enabled at the same time.++Tiberius has three runtime encryption settings:++| Encryption level | Description |+|------------------|--------------------------------------------------|+| `Required` | All traffic is encrypted. (default) |+| `Off` | Only the login procedure is encrypted. |+| `NotSupported` | None of the traffic is encrypted. |++The encryption levels can be set when connecting to the database.++### Integrated Authentication (TrustedConnection) on \*nix++With the `integrated-auth-gssapi` feature enabled, the crate requires the GSSAPI/Kerberos libraries/headers installed:+ * [CentOS](https://pkgs.org/download/krb5-devel)+ * [Arch](https://www.archlinux.org/packages/core/x86_64/krb5/)+ * [Debian](https://tracker.debian.org/pkg/krb5) (you need the -dev packages to build)+ * [Ubuntu](https://packages.ubuntu.com/bionic-updates/libkrb5-dev)+ * NixOS: Run `nix-shell shell.nix` on the repository root.+ * Mac: as of version `0.4.2` the [libgssapi](https://crates.io/crates/libgssapi) crate used for this feature now uses Apple's [GSS Framework](https://developer.apple.com/documentation/gss?language=objc) which ships with MacOS 10.14+.++Additionally, your runtime system will need to be trusted by and configured for the Active Directory domain your SQL Server is part of. In particular, you'll need to be able to get a valid TGT for your identity, via `kinit` or a keytab. This setup varies by environment and OS, but your friendly network/system administrator should be able to help figure out the specifics.++## Redirects++With certain Azure firewall settings, a login might return `Error::Routing { host, port }`. This means the user must create a new `TcpStream` to the given address, and connect again.++A simple connection procedure would then be:++```rust+use tiberius::{Client, Config, AuthMethod, error::Error};+use tokio_util::compat::TokioAsyncWriteCompatExt;+use tokio::net::TcpStream;++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let mut config = Config::new();++ config.host("0.0.0.0");+ config.port(1433);+ config.authentication(AuthMethod::sql_server("SA", "<Mys3cureP4ssW0rD>"));++ let tcp = TcpStream::connect(config.get_addr()).await?;+ tcp.set_nodelay(true)?;++ let client = match Client::connect(config, tcp.compat_write()).await {+ // Connection successful.+ Ok(client) => client,+ // The server wants us to redirect to a different address+ Err(Error::Routing { host, port }) => {+ let mut config = Config::new();++ config.host(&host);+ config.port(port);+ config.authentication(AuthMethod::sql_server("SA", "<Mys3cureP4ssW0rD>"));++ let tcp = TcpStream::connect(config.get_addr()).await?;+ tcp.set_nodelay(true)?;++ // we should not have more than one redirect, so we'll short-circuit here.+ Client::connect(config, tcp.compat_write()).await?+ }+ Err(e) => Err(e)?,+ };++ Ok(())+}+```++## Security++If you have a security issue to report, please contact us at [[email protected]](mailto:[email protected]?subject=[GitHub]%20Prisma%202%20Security%20Report%20Tiberius)diff --git a/vendor/tiberius/src/client.rs b/vendor/tiberius/src/client.rsnew file mode 100644index 0000000000..688721d10c--- /dev/null+++ b/vendor/tiberius/src/client.rs@@ -0,0 +1,410 @@+mod auth;+mod config;+mod connection;++mod tls;+#[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+))]+mod tls_stream;++pub use auth::*;+pub use config::*;+pub(crate) use connection::*;++use crate::tds::stream::ReceivedToken;+use crate::{+ result::ExecuteResult,+ tds::{+ codec::{self, IteratorJoin},+ stream::{QueryStream, TokenStream},+ },+ BulkLoadRequest, ColumnFlag, SqlReadBytes, ToSql,+};+use codec::{BatchRequest, ColumnData, PacketHeader, RpcParam, RpcProcId, TokenRpcRequest};+use enumflags2::BitFlags;+use futures_util::io::{AsyncRead, AsyncWrite};+use futures_util::stream::TryStreamExt;+use std::{borrow::Cow, fmt::Debug};++/// `Client` is the main entry point to the SQL Server, providing query+/// execution capabilities.+///+/// A `Client` is created using the [`Config`], defining the needed+/// connection options and capabilities.+///+/// # Example+///+/// ```no_run+/// # use tiberius::{Config, AuthMethod};+/// use tokio_util::compat::TokioAsyncWriteCompatExt;+///+/// # #[tokio::main]+/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+/// let mut config = Config::new();+///+/// config.host("0.0.0.0");+/// config.port(1433);+/// config.authentication(AuthMethod::sql_server("SA", "<Mys3cureP4ssW0rD>"));+///+/// let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+/// tcp.set_nodelay(true)?;+/// // Client is ready to use.+/// let client = tiberius::Client::connect(config, tcp.compat_write()).await?;+/// # Ok(())+/// # }+/// ```+///+/// [`Config`]: struct.Config.html+#[derive(Debug)]+pub struct Client<S: AsyncRead + AsyncWrite + Unpin + Send> {+ pub(crate) connection: Connection<S>,+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> Client<S> {+ /// Uses an instance of [`Config`] to specify the connection+ /// options required to connect to the database using an established+ /// tcp connection+ ///+ /// [`Config`]: struct.Config.html+ pub async fn connect(config: Config, tcp_stream: S) -> crate::Result<Client<S>> {+ Ok(Client {+ connection: Connection::connect(config, tcp_stream).await?,+ })+ }++ /// Executes SQL statements in the SQL Server, returning the number rows+ /// affected. Useful for `INSERT`, `UPDATE` and `DELETE` statements. The+ /// `query` can define the parameter placement by annotating them with+ /// `@PN`, where N is the index of the parameter, starting from `1`. If+ /// executing multiple queries at a time, delimit them with `;` and refer to+ /// [`ExecuteResult`] how to get results for the separate queries.+ ///+ /// For mapping of Rust types when writing, see the documentation for+ /// [`ToSql`]. For reading data from the database, see the documentation for+ /// [`FromSql`].+ ///+ /// This API is not quite suitable for dynamic query parameters. In these+ /// cases using a [`Query`] object might be easier.+ ///+ /// # Example+ ///+ /// ```no_run+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let results = client+ /// .execute(+ /// "INSERT INTO ##Test (id) VALUES (@P1), (@P2), (@P3)",+ /// &[&1i32, &2i32, &3i32],+ /// )+ /// .await?;+ /// # Ok(())+ /// # }+ /// ```+ ///+ /// [`ExecuteResult`]: struct.ExecuteResult.html+ /// [`ToSql`]: trait.ToSql.html+ /// [`FromSql`]: trait.FromSql.html+ /// [`Query`]: struct.Query.html+ pub async fn execute<'a>(+ &mut self,+ query: impl Into<Cow<'a, str>>,+ params: &[&dyn ToSql],+ ) -> crate::Result<ExecuteResult> {+ self.connection.flush_stream().await?;+ let rpc_params = Self::rpc_params(query);++ let params = params.iter().map(|s| s.to_sql());+ self.rpc_perform_query(RpcProcId::ExecuteSQL, rpc_params, params)+ .await?;++ ExecuteResult::new(&mut self.connection).await+ }++ /// Executes SQL statements in the SQL Server, returning resulting rows.+ /// Useful for `SELECT` statements. The `query` can define the parameter+ /// placement by annotating them with `@PN`, where N is the index of the+ /// parameter, starting from `1`. If executing multiple queries at a time,+ /// delimit them with `;` and refer to [`QueryStream`] on proper stream+ /// handling.+ ///+ /// For mapping of Rust types when writing, see the documentation for+ /// [`ToSql`]. For reading data from the database, see the documentation for+ /// [`FromSql`].+ ///+ /// This API can be cumbersome for dynamic query parameters. In these cases,+ /// if fighting too much with the compiler, using a [`Query`] object might be+ /// easier.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let stream = client+ /// .query(+ /// "SELECT @P1, @P2, @P3",+ /// &[&1i32, &2i32, &3i32],+ /// )+ /// .await?;+ /// # Ok(())+ /// # }+ /// ```+ ///+ /// [`QueryStream`]: struct.QueryStream.html+ /// [`Query`]: struct.Query.html+ /// [`ToSql`]: trait.ToSql.html+ /// [`FromSql`]: trait.FromSql.html+ pub async fn query<'a, 'b>(+ &'a mut self,+ query: impl Into<Cow<'b, str>>,+ params: &'b [&'b dyn ToSql],+ ) -> crate::Result<QueryStream<'a>>+ where+ 'a: 'b,+ {+ self.connection.flush_stream().await?;+ let rpc_params = Self::rpc_params(query);++ let params = params.iter().map(|p| p.to_sql());+ self.rpc_perform_query(RpcProcId::ExecuteSQL, rpc_params, params)+ .await?;++ let ts = TokenStream::new(&mut self.connection);+ let mut result = QueryStream::new(ts.try_unfold());+ result.forward_to_metadata().await?;++ Ok(result)+ }++ /// Execute multiple queries, delimited with `;` and return multiple result+ /// sets; one for each query.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let row = client.simple_query("SELECT 1 AS col").await?.into_row().await?.unwrap();+ /// assert_eq!(Some(1i32), row.get("col"));+ /// # Ok(())+ /// # }+ /// ```+ ///+ /// # Warning+ ///+ /// Do not use this with any user specified input. Please resort to prepared+ /// statements using the [`query`] method.+ ///+ /// [`query`]: #method.query+ pub async fn simple_query<'a, 'b>(+ &'a mut self,+ query: impl Into<Cow<'b, str>>,+ ) -> crate::Result<QueryStream<'a>>+ where+ 'a: 'b,+ {+ self.connection.flush_stream().await?;++ let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());++ let id = self.connection.context_mut().next_packet_id();+ self.connection.send(PacketHeader::batch(id), req).await?;++ let ts = TokenStream::new(&mut self.connection);++ let mut result = QueryStream::new(ts.try_unfold());+ result.forward_to_metadata().await?;++ Ok(result)+ }++ /// Execute a `BULK INSERT` statement, efficiantly storing a large number of+ /// rows to a specified table. Note: make sure the input row follows the same+ /// schema as the table, otherwise calling `send()` will return an error.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::{Config, IntoRow};+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let create_table = r#"+ /// CREATE TABLE ##bulk_test (+ /// id INT IDENTITY PRIMARY KEY,+ /// val INT NOT NULL+ /// )+ /// "#;+ ///+ /// client.simple_query(create_table).await?;+ ///+ /// // Start the bulk insert with the client.+ /// let mut req = client.bulk_insert("##bulk_test").await?;+ ///+ /// for i in [0i32, 1i32, 2i32] {+ /// let row = (i).into_row();+ ///+ /// // The request will handle flushing to the wire in an optimal way,+ /// // balancing between memory usage and IO performance.+ /// req.send(row).await?;+ /// }+ ///+ /// // The request must be finalized.+ /// let res = req.finalize().await?;+ /// assert_eq!(3, res.total());+ /// # Ok(())+ /// # }+ /// ```+ pub async fn bulk_insert<'a>(+ &'a mut self,+ table: &'a str,+ ) -> crate::Result<BulkLoadRequest<'a, S>> {+ // Start the bulk request+ self.connection.flush_stream().await?;++ // retrieve column metadata from server+ let query = format!("SELECT TOP 0 * FROM {}", table);++ let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());++ let id = self.connection.context_mut().next_packet_id();+ self.connection.send(PacketHeader::batch(id), req).await?;++ let token_stream = TokenStream::new(&mut self.connection).try_unfold();++ let columns = token_stream+ .try_fold(None, |mut columns, token| async move {+ if let ReceivedToken::NewResultset(metadata) = token {+ columns = Some(metadata.columns.clone());+ };++ Ok(columns)+ })+ .await?;++ // now start bulk upload+ let columns: Vec<_> = columns+ .ok_or_else(|| {+ crate::Error::Protocol("expecting column metadata from query but not found".into())+ })?+ .into_iter()+ .filter(|column| column.base.flags.contains(ColumnFlag::Updateable))+ .collect();++ self.connection.flush_stream().await?;+ let col_data = columns.iter().map(|c| format!("{}", c)).join(", ");+ let query = format!("INSERT BULK {} ({})", table, col_data);++ let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());+ let id = self.connection.context_mut().next_packet_id();++ self.connection.send(PacketHeader::batch(id), req).await?;++ let ts = TokenStream::new(&mut self.connection);+ ts.flush_done().await?;++ BulkLoadRequest::new(&mut self.connection, columns)+ }++ /// Closes this database connection explicitly.+ pub async fn close(self) -> crate::Result<()> {+ self.connection.close().await+ }++ pub(crate) fn rpc_params<'a>(query: impl Into<Cow<'a, str>>) -> Vec<RpcParam<'a>> {+ vec![+ RpcParam {+ name: Cow::Borrowed("stmt"),+ flags: BitFlags::empty(),+ value: ColumnData::String(Some(query.into())),+ },+ RpcParam {+ name: Cow::Borrowed("params"),+ flags: BitFlags::empty(),+ value: ColumnData::I32(Some(0)),+ },+ ]+ }++ pub(crate) async fn rpc_perform_query<'a, 'b>(+ &'a mut self,+ proc_id: RpcProcId,+ mut rpc_params: Vec<RpcParam<'b>>,+ params: impl Iterator<Item = ColumnData<'b>>,+ ) -> crate::Result<()>+ where+ 'a: 'b,+ {+ let mut param_str = String::new();++ for (i, param) in params.enumerate() {+ if i > 0 {+ param_str.push(',')+ }+ param_str.push_str(&format!("@P{} ", i + 1));+ param_str.push_str(¶m.type_name());++ rpc_params.push(RpcParam {+ name: Cow::Owned(format!("@P{}", i + 1)),+ flags: BitFlags::empty(),+ value: param,+ });+ }++ if let Some(params) = rpc_params.iter_mut().find(|x| x.name == "params") {+ params.value = ColumnData::String(Some(param_str.into()));+ }++ let req = TokenRpcRequest::new(+ proc_id,+ rpc_params,+ self.connection.context().transaction_descriptor(),+ );++ let id = self.connection.context_mut().next_packet_id();+ self.connection.send(PacketHeader::rpc(id), req).await?;++ Ok(())+ }+}diff --git a/vendor/tiberius/src/client/auth.rs b/vendor/tiberius/src/client/auth.rsnew file mode 100644index 0000000000..208d8d0603--- /dev/null+++ b/vendor/tiberius/src/client/auth.rs@@ -0,0 +1,106 @@+use std::fmt::Debug;++#[derive(Clone, PartialEq, Eq)]+pub struct SqlServerAuth {+ user: String,+ password: String,+}++impl SqlServerAuth {+ pub(crate) fn user(&self) -> &str {+ &self.user+ }++ pub(crate) fn password(&self) -> &str {+ &self.password+ }+}++impl Debug for SqlServerAuth {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("SqlServerAuth")+ .field("user", &self.user)+ .field("password", &"<HIDDEN>")+ .finish()+ }+}++#[derive(Clone, PartialEq, Eq)]+#[cfg(any(all(windows, feature = "winauth"), doc))]+#[cfg_attr(feature = "docs", doc(all(windows, feature = "winauth")))]+pub struct WindowsAuth {+ pub(crate) user: String,+ pub(crate) password: String,+ pub(crate) domain: Option<String>,+}++#[cfg(any(all(windows, feature = "winauth"), doc))]+#[cfg_attr(feature = "docs", doc(all(windows, feature = "winauth")))]+impl Debug for WindowsAuth {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("WindowsAuth")+ .field("user", &self.user)+ .field("password", &"<HIDDEN>")+ .field("domain", &self.domain)+ .finish()+ }+}++/// Defines the method of authentication to the server.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum AuthMethod {+ /// Authenticate directly with SQL Server.+ SqlServer(SqlServerAuth),+ /// Authenticate with Windows credentials.+ #[cfg(any(all(windows, feature = "winauth"), doc))]+ #[cfg_attr(feature = "docs", doc(cfg(all(windows, feature = "winauth"))))]+ Windows(WindowsAuth),+ /// Authenticate as the currently logged in user. On Windows uses SSPI and+ /// Kerberos on Unix platforms.+ #[cfg(any(+ all(windows, feature = "winauth"),+ all(unix, feature = "integrated-auth-gssapi"),+ doc+ ))]+ #[cfg_attr(+ feature = "docs",+ doc(cfg(any(windows, all(unix, feature = "integrated-auth-gssapi"))))+ )]+ Integrated,+ /// Authenticate with an AAD token. The token should encode an AAD user/service principal+ /// which has access to SQL Server.+ AADToken(String),+ #[doc(hidden)]+ None,+}++impl AuthMethod {+ /// Construct a new SQL Server authentication configuration.+ pub fn sql_server(user: impl ToString, password: impl ToString) -> Self {+ Self::SqlServer(SqlServerAuth {+ user: user.to_string(),+ password: password.to_string(),+ })+ }++ /// Construct a new Windows authentication configuration.+ #[cfg(any(all(windows, feature = "winauth"), doc))]+ #[cfg_attr(feature = "docs", doc(cfg(all(windows, feature = "winauth"))))]+ pub fn windows(user: impl AsRef<str>, password: impl ToString) -> Self {+ let (domain, user) = match user.as_ref().find('\\') {+ Some(idx) => (Some(&user.as_ref()[..idx]), &user.as_ref()[idx + 1..]),+ _ => (None, user.as_ref()),+ };++ Self::Windows(WindowsAuth {+ user: user.to_string(),+ password: password.to_string(),+ domain: domain.map(|s| s.to_string()),+ })+ }++ /// Construct a new configuration with AAD auth token.+ pub fn aad_token(token: impl ToString) -> Self {+ Self::AADToken(token.to_string())+ }+}diff --git a/vendor/tiberius/src/client/config.rs b/vendor/tiberius/src/client/config.rsnew file mode 100644index 0000000000..fff68bc157--- /dev/null+++ b/vendor/tiberius/src/client/config.rs@@ -0,0 +1,391 @@+mod ado_net;+mod jdbc;++use std::collections::HashMap;+use std::path::PathBuf;++use super::AuthMethod;+use crate::EncryptionLevel;+use ado_net::*;+use jdbc::*;++#[derive(Clone, Debug)]+/// The `Config` struct contains all configuration information+/// required for connecting to the database with a [`Client`]. It also provides+/// the server address when connecting to a `TcpStream` via the+/// [`get_addr`] method.+///+/// When using an [ADO.NET connection string], it can be+/// constructed using the [`from_ado_string`] function.+///+/// [`Client`]: struct.Client.html+/// [ADO.NET connection string]: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings+/// [`from_ado_string`]: struct.Config.html#method.from_ado_string+/// [`get_addr`]: struct.Config.html#method.get_addr+pub struct Config {+ pub(crate) host: Option<String>,+ pub(crate) port: Option<u16>,+ pub(crate) database: Option<String>,+ pub(crate) instance_name: Option<String>,+ pub(crate) application_name: Option<String>,+ pub(crate) encryption: EncryptionLevel,+ pub(crate) trust: TrustConfig,+ pub(crate) auth: AuthMethod,+ pub(crate) readonly: bool,+}++#[derive(Clone, Debug)]+pub(crate) enum TrustConfig {+ #[allow(dead_code)]+ CaCertificateLocation(PathBuf),+ TrustAll,+ Default,+}++impl Default for Config {+ fn default() -> Self {+ Self {+ host: None,+ port: None,+ database: None,+ instance_name: None,+ application_name: None,+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ encryption: EncryptionLevel::Required,+ #[cfg(not(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ )))]+ encryption: EncryptionLevel::NotSupported,+ trust: TrustConfig::Default,+ auth: AuthMethod::None,+ readonly: false,+ }+ }+}++impl Config {+ /// Create a new `Config` with the default settings.+ pub fn new() -> Self {+ Self::default()+ }++ /// A host or ip address to connect to.+ ///+ /// - Defaults to `localhost`.+ pub fn host(&mut self, host: impl ToString) {+ self.host = Some(host.to_string());+ }++ /// The server port.+ ///+ /// - Defaults to `1433`.+ pub fn port(&mut self, port: u16) {+ self.port = Some(port);+ }++ /// The database to connect to.+ ///+ /// - Defaults to `master`.+ pub fn database(&mut self, database: impl ToString) {+ self.database = Some(database.to_string())+ }++ /// The instance name as defined in the SQL Browser. Only available on+ /// Windows platforms.+ ///+ /// If specified, the port is replaced with the value returned from the+ /// browser.+ ///+ /// - Defaults to no name specified.+ pub fn instance_name(&mut self, name: impl ToString) {+ self.instance_name = Some(name.to_string());+ }++ /// Sets the application name to the connection, queryable with the+ /// `APP_NAME()` command.+ ///+ /// - Defaults to no name specified.+ pub fn application_name(&mut self, name: impl ToString) {+ self.application_name = Some(name.to_string());+ }++ /// Set the preferred encryption level.+ ///+ /// - With `tls` feature, defaults to `Required`.+ /// - Without `tls` feature, defaults to `NotSupported`.+ pub fn encryption(&mut self, encryption: EncryptionLevel) {+ self.encryption = encryption;+ }++ /// If set, the server certificate will not be validated and it is accepted+ /// as-is.+ ///+ /// On production setting, the certificate should be added to the local key+ /// storage (or use `trust_cert_ca` instead), using this setting is potentially dangerous.+ ///+ /// # Panics+ /// Will panic in case `trust_cert_ca` was called before.+ ///+ /// - Defaults to `default`, meaning server certificate is validated against system-truststore.+ pub fn trust_cert(&mut self) {+ if let TrustConfig::CaCertificateLocation(_) = &self.trust {+ panic!("'trust_cert' and 'trust_cert_ca' are mutual exclusive! Only use one.")+ }+ self.trust = TrustConfig::TrustAll;+ }++ /// If set, the server certificate will be validated against the given CA certificate in+ /// in addition to the system-truststore.+ /// Useful when using self-signed certificates on the server without having to disable the+ /// trust-chain.+ ///+ /// # Panics+ /// Will panic in case `trust_cert` was called before.+ ///+ /// - Defaults to validating the server certificate is validated against system's certificate storage.+ pub fn trust_cert_ca(&mut self, path: impl ToString) {+ if let TrustConfig::TrustAll = &self.trust {+ panic!("'trust_cert' and 'trust_cert_ca' are mutual exclusive! Only use one.")+ } else {+ self.trust = TrustConfig::CaCertificateLocation(PathBuf::from(path.to_string()))+ }+ }++ /// Sets the authentication method.+ ///+ /// - Defaults to `None`.+ pub fn authentication(&mut self, auth: AuthMethod) {+ self.auth = auth;+ }++ /// Sets ApplicationIntent readonly.+ ///+ /// - Defaults to `false`.+ pub fn readonly(&mut self, readnoly: bool) {+ self.readonly = readnoly;+ }++ pub(crate) fn get_host(&self) -> &str {+ self.host+ .as_deref()+ .filter(|v| v != &".")+ .unwrap_or("localhost")+ }++ pub(crate) fn get_port(&self) -> u16 {+ match (self.port, self.instance_name.as_ref()) {+ // A user-defined port, we must use that.+ (Some(port), _) => port,+ // If using a named instance, we'll give the default port of SQL+ // Browser.+ (None, Some(_)) => 1434,+ // Otherwise the defaulting to the default SQL Server port.+ (None, None) => 1433,+ }+ }++ /// Get the host address including port+ pub fn get_addr(&self) -> String {+ format!("{}:{}", self.get_host(), self.get_port())+ }++ /// Creates a new `Config` from an [ADO.NET connection string].+ ///+ /// # Supported parameters+ ///+ /// All parameter keys are handled case-insensitive.+ ///+ /// |Parameter|Allowed values|Description|+ /// |--------|--------|--------|+ /// |`server`|`<string>`|The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name. The correct form of this parameter is either `tcp:host,port` or `tcp:host\\instance`|+ /// |`IntegratedSecurity`|`true`,`false`,`yes`,`no`|Toggle between Windows/Kerberos authentication and SQL authentication.|+ /// |`uid`,`username`,`user`,`user id`|`<string>`|The SQL Server login account.|+ /// |`password`,`pwd`|`<string>`|The password for the SQL Server account logging on.|+ /// |`database`|`<string>`|The name of the database.|+ /// |`TrustServerCertificate`|`true`,`false`,`yes`,`no`|Specifies whether the driver trusts the server certificate when connecting using TLS. Cannot be used toghether with `TrustServerCertificateCA`|+ /// |`TrustServerCertificateCA`|`<path>`|Path to a `pem`, `crt` or `der` certificate file. Cannot be used together with `TrustServerCertificate`|+ /// |`encrypt`|`true`,`false`,`yes`,`no`,`DANGER_PLAINTEXT`|Specifies whether the driver uses TLS to encrypt communication.|+ /// |`Application Name`, `ApplicationName`|`<string>`|Sets the application name for the connection.|+ ///+ /// [ADO.NET connection string]: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings+ pub fn from_ado_string(s: &str) -> crate::Result<Self> {+ let ado: AdoNetConfig = s.parse()?;+ Self::from_config_string(ado)+ }++ /// Creates a new `Config` from a [JDBC connection string].+ ///+ /// See [`from_ado_string`] method for supported parameters.+ ///+ /// [JDBC connection string]: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15+ /// [`from_ado_string`]: #method.from_ado_string+ pub fn from_jdbc_string(s: &str) -> crate::Result<Self> {+ let jdbc: JdbcConfig = s.parse()?;+ Self::from_config_string(jdbc)+ }++ fn from_config_string(s: impl ConfigString) -> crate::Result<Self> {+ let mut builder = Self::new();++ let server = s.server()?;++ if let Some(host) = server.host {+ builder.host(host);+ }++ if let Some(port) = server.port {+ builder.port(port);+ }++ if let Some(instance) = server.instance {+ builder.instance_name(instance);+ }++ builder.authentication(s.authentication()?);++ if let Some(database) = s.database() {+ builder.database(database);+ }++ if let Some(name) = s.application_name() {+ builder.application_name(name);+ }++ if s.trust_cert()? {+ builder.trust_cert();+ }++ if let Some(ca) = s.trust_cert_ca() {+ builder.trust_cert_ca(ca);+ }++ builder.encryption(s.encrypt()?);++ builder.readonly(s.readonly());++ Ok(builder)+ }+}++pub(crate) struct ServerDefinition {+ host: Option<String>,+ port: Option<u16>,+ instance: Option<String>,+}++pub(crate) trait ConfigString {+ fn dict(&self) -> &HashMap<String, String>;++ fn server(&self) -> crate::Result<ServerDefinition>;++ fn authentication(&self) -> crate::Result<AuthMethod> {+ let user = self+ .dict()+ .get("uid")+ .or_else(|| self.dict().get("username"))+ .or_else(|| self.dict().get("user"))+ .or_else(|| self.dict().get("user id"))+ .map(|s| s.as_str());++ let pw = self+ .dict()+ .get("password")+ .or_else(|| self.dict().get("pwd"))+ .map(|s| s.as_str());++ match self+ .dict()+ .get("integratedsecurity")+ .or_else(|| self.dict().get("integrated security"))+ {+ #[cfg(all(windows, feature = "winauth"))]+ Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => match (user, pw)+ {+ (None, None) => Ok(AuthMethod::Integrated),+ _ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),+ },+ #[cfg(feature = "integrated-auth-gssapi")]+ Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => {+ Ok(AuthMethod::Integrated)+ }+ _ => Ok(AuthMethod::sql_server(user.unwrap_or(""), pw.unwrap_or(""))),+ }+ }++ fn database(&self) -> Option<String> {+ self.dict()+ .get("database")+ .or_else(|| self.dict().get("initial catalog"))+ .or_else(|| self.dict().get("databasename"))+ .map(|db| db.to_string())+ }++ fn application_name(&self) -> Option<String> {+ self.dict()+ .get("application name")+ .or_else(|| self.dict().get("applicationname"))+ .map(|name| name.to_string())+ }++ fn trust_cert(&self) -> crate::Result<bool> {+ self.dict()+ .get("trustservercertificate")+ .map(Self::parse_bool)+ .unwrap_or(Ok(false))+ }++ fn trust_cert_ca(&self) -> Option<String> {+ self.dict()+ .get("trustservercertificateca")+ .map(|ca| ca.to_string())+ }++ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encrypt(&self) -> crate::Result<EncryptionLevel> {+ self.dict()+ .get("encrypt")+ .map(|val| match Self::parse_bool(val) {+ Ok(true) => Ok(EncryptionLevel::Required),+ Ok(false) => Ok(EncryptionLevel::Off),+ Err(_) if val == "DANGER_PLAINTEXT" => Ok(EncryptionLevel::NotSupported),+ Err(e) => Err(e),+ })+ .unwrap_or(Ok(EncryptionLevel::Off))+ }++ #[cfg(not(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ )))]+ fn encrypt(&self) -> crate::Result<EncryptionLevel> {+ Ok(EncryptionLevel::NotSupported)+ }++ fn parse_bool<T: AsRef<str>>(v: T) -> crate::Result<bool> {+ match v.as_ref().trim().to_lowercase().as_str() {+ "true" | "yes" => Ok(true),+ "false" | "no" => Ok(false),+ _ => Err(crate::Error::Conversion(+ "Connection string: Not a valid boolean".into(),+ )),+ }+ }++ fn readonly(&self) -> bool {+ self.dict()+ .get("applicationintent")+ .filter(|val| *val == "ReadOnly")+ .is_some()+ }+}diff --git a/vendor/tiberius/src/client/config/ado_net.rs b/vendor/tiberius/src/client/config/ado_net.rsnew file mode 100644index 0000000000..94df9ca382--- /dev/null+++ b/vendor/tiberius/src/client/config/ado_net.rs@@ -0,0 +1,487 @@+use super::{ConfigString, ServerDefinition};+use std::str::FromStr;++pub(crate) struct AdoNetConfig {+ dict: connection_string::AdoNetString,+}++impl FromStr for AdoNetConfig {+ type Err = crate::error::Error;++ fn from_str(s: &str) -> crate::Result<Self> {+ let dict = s.parse()?;+ Ok(Self { dict })+ }+}++impl ConfigString for AdoNetConfig {+ fn dict(&self) -> &std::collections::HashMap<String, String> {+ &self.dict+ }++ fn server(&self) -> crate::Result<ServerDefinition> {+ fn parse_port(parts: &[&str]) -> crate::Result<Option<u16>> {+ Ok(match parts.first() {+ Some(s) => Some(s.parse()?),+ None => None,+ })+ }++ fn parse_server(parts: Vec<&str>) -> crate::Result<ServerDefinition> {+ if parts.is_empty() || parts.len() >= 3 {+ return Err(crate::Error::Conversion("Server value faulty.".into()));+ }++ let definition = if parts[0].contains('\\') {+ let port = parse_port(&parts[1..])?;+ let parts: Vec<&str> = parts[0].split('\\').collect();++ ServerDefinition {+ host: Some(parts[0].replace("(local)", "localhost")),+ port,+ instance: Some(parts[1].into()),+ }+ } else {+ // Connect using a TCP target+ ServerDefinition {+ host: Some(parts[0].replace("(local)", "localhost")),+ port: parse_port(&parts[1..])?,+ instance: None,+ }+ };++ Ok(definition)+ }++ match self+ .dict+ .get("server")+ .or_else(|| self.dict.get("data source"))+ {+ Some(value) if value.starts_with("tcp:") => {+ parse_server(value[4..].split(',').collect())+ }+ Some(value) => parse_server(value.split(',').collect()),+ None => Ok(ServerDefinition {+ host: None,+ port: None,+ instance: None,+ }),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::client::AuthMethod;++ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ use crate::EncryptionLevel;++ #[test]+ fn server_parsing_no_browser() -> crate::Result<()> {+ let test_str = "server=tcp:my-server.com,4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ let test_str = "data source=tcp:my-server.com,4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_no_tcp() -> crate::Result<()> {+ let test_str = "server=my-server.com,4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ let test_str = "data source=my-server.com,4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_local() -> crate::Result<()> {+ let test_str = "server=tcp:(local),4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("localhost".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ let test_str = "data source=tcp:(local),4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("localhost".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_local_no_tcp() -> crate::Result<()> {+ let test_str = "server=(local),4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("localhost".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ let test_str = "data source=(local),4200";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("localhost".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_no_port() -> crate::Result<()> {+ let test_str = "server=tcp:my-server.com";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(None, server.port);+ assert_eq!(None, server.instance);++ let test_str = "server=my-server.com";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(None, server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_with_browser() -> crate::Result<()> {+ let test_str = "server=tcp:my-server.com\\TIBERIUS";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(None, server.port);+ assert_eq!(Some("TIBERIUS".to_string()), server.instance);++ let test_str = "data source=tcp:my-server.com\\TIBERIUS";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(None, server.port);+ assert_eq!(Some("TIBERIUS".to_string()), server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_with_browser_and_port() -> crate::Result<()> {+ let test_str = "server=tcp:my-server.com\\TIBERIUS,666";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(666), server.port);+ assert_eq!(Some("TIBERIUS".to_string()), server.instance);++ let test_str = "data source=tcp:my-server.com\\TIBERIUS,666";+ let ado: AdoNetConfig = test_str.parse()?;+ let server = ado.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(666), server.port);+ assert_eq!(Some("TIBERIUS".to_string()), server.instance);++ Ok(())+ }++ #[test]+ fn database_parsing() -> crate::Result<()> {+ let test_str = "database=Foo";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("Foo".to_string()), ado.database());++ let test_str = "databaseName=Foo";+ let jdbc: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("Foo".to_string()), jdbc.database());++ let test_str = "Initial Catalog=Foo";+ let jdbc: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("Foo".to_string()), jdbc.database());++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_true() -> crate::Result<()> {+ let test_str = "TrustServerCertificate=true";+ let ado: AdoNetConfig = test_str.parse()?;++ assert!(ado.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_false() -> crate::Result<()> {+ let test_str = "TrustServerCertificate=false";+ let ado: AdoNetConfig = test_str.parse()?;++ assert!(!ado.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_yes() -> crate::Result<()> {+ let test_str = "TrustServerCertificate=yes";+ let ado: AdoNetConfig = test_str.parse()?;++ assert!(ado.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_no() -> crate::Result<()> {+ let test_str = "TrustServerCertificate=no";+ let ado: AdoNetConfig = test_str.parse()?;++ assert!(!ado.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_missing() -> crate::Result<()> {+ let test_str = "Something=foo;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert!(!ado.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_faulty() -> crate::Result<()> {+ let test_str = "TrustServerCertificate=musti;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert!(ado.trust_cert().is_err());++ Ok(())+ }++ #[test]+ fn trust_cert_ca_parsing_ok() -> crate::Result<()> {+ let test_str = "TrustServerCertificateCA=someca.crt;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("someca.crt".to_string()), ado.trust_cert_ca());++ Ok(())+ }++ #[test]+ fn parsing_sql_server_authentication() -> crate::Result<()> {+ let test_str = "uid=Musti; pwd=Naukio;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::sql_server("Musti", "Naukio"),+ ado.authentication()?+ );++ Ok(())+ }++ #[test]+ #[cfg(windows)]+ fn parsing_sspi_authentication() -> crate::Result<()> {+ let test_str = "IntegratedSecurity=SSPI;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(AuthMethod::Integrated, ado.authentication()?);++ let test_str = "Integrated Security=SSPI;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(AuthMethod::Integrated, ado.authentication()?);++ Ok(())+ }++ #[test]+ #[cfg(all(feature = "integrated-auth-gssapi", unix))]+ fn parsing_sspi_authentication() -> crate::Result<()> {+ let test_str = "IntegratedSecurity=true;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(AuthMethod::Integrated, ado.authentication()?);++ let test_str = "Integrated Security=true;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(AuthMethod::Integrated, ado.authentication()?);++ Ok(())+ }++ #[test]+ #[cfg(windows)]+ fn parsing_windows_authentication() -> crate::Result<()> {+ let test_str = "uid=Musti;pwd=Naukio; IntegratedSecurity=SSPI;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::windows("Musti", "Naukio"),+ ado.authentication()?+ );++ let test_str = "uid=Musti;pwd=Naukio; Integrated Security=SSPI;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::windows("Musti", "Naukio"),+ ado.authentication()?+ );++ Ok(())+ }++ #[test]+ fn parsing_database() -> crate::Result<()> {+ let test_str = "database=Cats;";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("Cats".to_string()), ado.database());++ Ok(())+ }++ #[test]+ fn parsing_login_credentials_escaping() -> crate::Result<()> {+ let test_str = "User ID=musti; Password='abc;}45';";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::sql_server("musti", "abc;}45"),+ ado.authentication()?+ );++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_on() -> crate::Result<()> {+ let test_str = "encrypt=true";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::Required, ado.encrypt()?);++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_off() -> crate::Result<()> {+ let test_str = "encrypt=false";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::Off, ado.encrypt()?);++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_plaintext() -> crate::Result<()> {+ let test_str = "encrypt=DANGER_PLAINTEXT";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::NotSupported, ado.encrypt()?);++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_missing() -> crate::Result<()> {+ let test_str = "";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::Off, ado.encrypt()?);++ Ok(())+ }++ #[test]+ fn application_name_parsing() -> crate::Result<()> {+ let test_str = "Application Name=meow";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("meow".into()), ado.application_name());++ let test_str = "ApplicationName=meow";+ let ado: AdoNetConfig = test_str.parse()?;++ assert_eq!(Some("meow".into()), ado.application_name());++ Ok(())+ }+}diff --git a/vendor/tiberius/src/client/config/jdbc.rs b/vendor/tiberius/src/client/config/jdbc.rsnew file mode 100644index 0000000000..4168cf975c--- /dev/null+++ b/vendor/tiberius/src/client/config/jdbc.rs@@ -0,0 +1,336 @@+use super::{ConfigString, ServerDefinition};+use crate::error::Error;+use connection_string::JdbcString;+use std::str::FromStr;++pub(crate) struct JdbcConfig {+ config: JdbcString,+}++impl FromStr for JdbcConfig {+ type Err = Error;++ fn from_str(s: &str) -> crate::Result<Self> {+ let config = s.parse()?;+ Ok(Self { config })+ }+}++impl ConfigString for JdbcConfig {+ fn dict(&self) -> &std::collections::HashMap<String, String> {+ self.config.properties()+ }++ fn server(&self) -> crate::Result<ServerDefinition> {+ let def = ServerDefinition {+ host: self.config.server_name().map(|s| s.to_string()),+ port: self.config.port(),+ instance: self.config.instance_name().map(|s| s.to_string()),+ };++ Ok(def)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::client::AuthMethod;++ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ use crate::EncryptionLevel;++ #[test]+ fn server_parsing_no_browser() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200";+ let jdbc: JdbcConfig = test_str.parse()?;+ let server = jdbc.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_no_jdbc_no_browser() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200";+ let jdbc: JdbcConfig = test_str.parse()?;+ let server = jdbc.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(4200), server.port);+ assert_eq!(None, server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_with_browser() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com\\TIBERIUS";+ let jdbc: JdbcConfig = test_str.parse()?;+ let server = jdbc.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(None, server.port);+ assert_eq!(Some("TIBERIUS".to_string()), server.instance);++ Ok(())+ }++ #[test]+ fn server_parsing_with_browser_and_port() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com\\TIBERIUS:666";+ let jdbc: JdbcConfig = test_str.parse()?;+ let server = jdbc.server()?;++ assert_eq!(Some("my-server.com".to_string()), server.host);+ assert_eq!(Some(666), server.port);+ assert_eq!(Some("TIBERIUS".to_string()), server.instance);++ Ok(())+ }++ #[test]+ fn database_parsing() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://myserver.com:4200;database=Foo";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("Foo".to_string()), jdbc.database());++ let test_str = "jdbc:sqlserver://myserver.com:4200;databaseName=Foo";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("Foo".to_string()), jdbc.database());++ let test_str = "jdbc:sqlserver://myserver.com:4200;Initial Catalog=Foo";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("Foo".to_string()), jdbc.database());++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_true() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=true;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert!(jdbc.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_false() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=false;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert!(!jdbc.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_yes() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=yes;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert!(jdbc.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_no() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=no;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert!(!jdbc.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_missing() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert!(!jdbc.trust_cert()?);++ Ok(())+ }++ #[test]+ fn trust_cert_parsing_faulty() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificate=musti;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert!(jdbc.trust_cert().is_err());++ Ok(())+ }++ #[test]+ fn trust_cert_ca_parsing_ok() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;TrustServerCertificateCA=someca.crt;";+ let ado: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("someca.crt".to_string()), ado.trust_cert_ca());++ Ok(())+ }++ #[test]+ fn parsing_sql_server_authentication() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;User ID=Musti;pwd=Naukio;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::sql_server("Musti", "Naukio"),+ jdbc.authentication()?+ );++ Ok(())+ }++ #[test]+ #[cfg(windows)]+ fn parsing_sspi_authentication() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;IntegratedSecurity=SSPI;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(AuthMethod::Integrated, jdbc.authentication()?);++ Ok(())+ }++ #[test]+ #[cfg(all(feature = "integrated-auth-gssapi", unix))]+ fn parsing_sspi_authentication() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;IntegratedSecurity=true;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(AuthMethod::Integrated, jdbc.authentication()?);++ Ok(())+ }++ #[test]+ #[cfg(windows)]+ fn parsing_windows_authentication() -> crate::Result<()> {+ let test_str =+ "jdbc:sqlserver://my-server.com:4200;uid=Musti;pwd=Naukio;IntegratedSecurity=SSPI;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::windows("Musti", "Naukio"),+ jdbc.authentication()?+ );++ Ok(())+ }++ #[test]+ fn parsing_database() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;database=Cats;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("Cats".to_string()), jdbc.database());++ Ok(())+ }++ #[test]+ fn parsing_login_credentials_escaping() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;User ID=musti;Password={abc;}}45}";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(+ AuthMethod::sql_server("musti", "abc;}45}"),+ jdbc.authentication()?+ );++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_on() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;encrypt=true;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::Required, jdbc.encrypt()?);++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_off() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;encrypt=false;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::Off, jdbc.encrypt()?);++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_plaintext() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;encrypt=DANGER_PLAINTEXT;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::NotSupported, jdbc.encrypt()?);++ Ok(())+ }++ #[test]+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn encryption_parsing_missing() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(EncryptionLevel::Off, jdbc.encrypt()?);++ Ok(())+ }++ #[test]+ fn application_name_parsing() -> crate::Result<()> {+ let test_str = "jdbc:sqlserver://my-server.com:4200;Application Name=meow";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("meow".into()), jdbc.application_name());++ let test_str = "jdbc:sqlserver://my-server.com:4200;ApplicationName=meow";+ let jdbc: JdbcConfig = test_str.parse()?;++ assert_eq!(Some("meow".into()), jdbc.application_name());++ Ok(())+ }+}diff --git a/vendor/tiberius/src/client/connection.rs b/vendor/tiberius/src/client/connection.rsnew file mode 100644index 0000000000..c6ce1d66eb--- /dev/null+++ b/vendor/tiberius/src/client/connection.rs@@ -0,0 +1,576 @@+#[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+))]+use crate::client::{tls::TlsPreloginWrapper, tls_stream::create_tls_stream};+use crate::{+ client::{tls::MaybeTlsStream, AuthMethod, Config},+ tds::{+ codec::{+ self, Encode, LoginMessage, Packet, PacketCodec, PacketHeader, PacketStatus,+ PreloginMessage, TokenDone,+ },+ stream::TokenStream,+ Context, HEADER_BYTES,+ },+ EncryptionLevel, SqlReadBytes,+};+use asynchronous_codec::Framed;+use bytes::BytesMut;+#[cfg(any(windows, feature = "integrated-auth-gssapi"))]+use codec::TokenSspi;+use futures_util::io::{AsyncRead, AsyncWrite};+use futures_util::ready;+use futures_util::sink::SinkExt;+use futures_util::stream::{Stream, TryStream, TryStreamExt};+#[cfg(all(unix, feature = "integrated-auth-gssapi"))]+use libgssapi::{+ context::{ClientCtx, CtxFlags},+ credential::{Cred, CredUsage},+ name::Name,+ oid::{OidSet, GSS_MECH_KRB5, GSS_NT_KRB5_PRINCIPAL},+};+use pretty_hex::*;+#[cfg(all(unix, feature = "integrated-auth-gssapi"))]+use std::ops::Deref;+use std::{cmp, fmt::Debug, io, pin::Pin, task};+use task::Poll;+use tracing::{event, Level};+#[cfg(all(windows, feature = "winauth"))]+use winauth::{windows::NtlmSspiBuilder, NextBytes};++/// A `Connection` is an abstraction between the [`Client`] and the server. It+/// can be used as a `Stream` to fetch [`Packet`]s from and to `send` packets+/// splitting them to the negotiated limit automatically.+///+/// `Connection` is not meant to use directly, but as an abstraction layer for+/// the numerous `Stream`s for easy packet handling.+///+/// [`Client`]: struct.Encode.html+/// [`Packet`]: ../protocol/codec/struct.Packet.html+pub(crate) struct Connection<S>+where+ S: AsyncRead + AsyncWrite + Unpin + Send,+{+ transport: Framed<MaybeTlsStream<S>, PacketCodec>,+ flushed: bool,+ context: Context,+ buf: BytesMut,+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> Debug for Connection<S> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Connection")+ .field("transport", &"Framed<..>")+ .field("flushed", &self.flushed)+ .field("context", &self.context)+ .field("buf", &self.buf.as_ref().hex_dump())+ .finish()+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> Connection<S> {+ /// Creates a new connection+ pub(crate) async fn connect(config: Config, tcp_stream: S) -> crate::Result<Connection<S>> {+ let context = {+ let mut context = Context::new();+ context.set_spn(config.get_host(), config.get_port());+ context+ };++ let transport = Framed::new(MaybeTlsStream::Raw(tcp_stream), PacketCodec);++ let mut connection = Self {+ transport,+ context,+ flushed: false,+ buf: BytesMut::new(),+ };++ let fed_auth_required = matches!(config.auth, AuthMethod::AADToken(_));++ let prelogin = connection+ .prelogin(config.encryption, fed_auth_required)+ .await?;++ let encryption = prelogin.negotiated_encryption(config.encryption);++ let connection = connection.tls_handshake(&config, encryption).await?;++ let mut connection = connection+ .login(+ config.auth,+ encryption,+ config.database,+ config.host,+ config.application_name,+ config.readonly,+ prelogin,+ )+ .await?;++ connection.flush_done().await?;++ Ok(connection)+ }++ /// Flush the incoming token stream until receiving `DONE` token.+ async fn flush_done(&mut self) -> crate::Result<TokenDone> {+ TokenStream::new(self).flush_done().await+ }++ #[cfg(any(windows, feature = "integrated-auth-gssapi"))]+ /// Flush the incoming token stream until receiving `SSPI` token.+ async fn flush_sspi(&mut self) -> crate::Result<TokenSspi> {+ TokenStream::new(self).flush_sspi().await+ }++ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ fn post_login_encryption(mut self, encryption: EncryptionLevel) -> Self {+ if let EncryptionLevel::Off = encryption {+ event!(+ Level::WARN,+ "Turning TLS off after a login. All traffic from here on is not encrypted.",+ );++ let Self { transport, .. } = self;+ let tcp = transport.into_inner().into_inner();+ self.transport = Framed::new(MaybeTlsStream::Raw(tcp), PacketCodec);+ }++ self+ }++ #[cfg(not(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ )))]+ fn post_login_encryption(self, _: EncryptionLevel) -> Self {+ self+ }++ /// Send an item to the wire. Header should define the item type and item should implement+ /// [`Encode`], defining the byte structure for the wire.+ ///+ /// The `send` will split the packet into multiple packets if bigger than+ /// the negotiated packet size, and handle flushing to the wire in an optimal way.+ ///+ /// [`Encode`]: ../protocol/codec/trait.Encode.html+ pub async fn send<E>(&mut self, mut header: PacketHeader, item: E) -> crate::Result<()>+ where+ E: Sized + Encode<BytesMut>,+ {+ self.flushed = false;+ let packet_size = (self.context.packet_size() as usize) - HEADER_BYTES;++ let mut payload = BytesMut::new();+ item.encode(&mut payload)?;++ while !payload.is_empty() {+ let writable = cmp::min(payload.len(), packet_size);+ let split_payload = payload.split_to(writable);++ if payload.is_empty() {+ header.set_status(PacketStatus::EndOfMessage);+ } else {+ header.set_status(PacketStatus::NormalMessage);+ }++ event!(+ Level::TRACE,+ "Sending a packet ({} bytes)",+ split_payload.len() + HEADER_BYTES,+ );++ self.write_to_wire(header, split_payload).await?;+ }++ self.flush_sink().await?;++ Ok(())+ }++ /// Sends a packet of data to the database.+ ///+ /// # Warning+ ///+ /// Please be sure the packet size doesn't exceed the largest allowed size+ /// dictaded by the server.+ pub(crate) async fn write_to_wire(+ &mut self,+ header: PacketHeader,+ data: BytesMut,+ ) -> crate::Result<()> {+ self.flushed = false;++ let packet = Packet::new(header, data);+ self.transport.send(packet).await?;++ Ok(())+ }++ /// Sends all pending packages to the wire.+ pub(crate) async fn flush_sink(&mut self) -> crate::Result<()> {+ self.transport.flush().await+ }++ /// Cleans the packet stream from previous use. It is important to use the+ /// whole stream before using the connection again. Flushing the stream+ /// makes sure we don't have any old data causing undefined behaviour after+ /// previous queries.+ ///+ /// Calling this will slow down the queries if stream is still dirty if all+ /// results are not handled.+ pub async fn flush_stream(&mut self) -> crate::Result<()> {+ self.buf.truncate(0);++ if self.flushed {+ return Ok(());+ }++ while let Some(packet) = self.try_next().await? {+ event!(+ Level::WARN,+ "Flushing unhandled packet from the wire. Please consume your streams!",+ );++ let is_last = packet.is_last();++ if is_last {+ break;+ }+ }++ Ok(())+ }++ /// True if the underlying stream has no more data and is consumed+ /// completely.+ pub fn is_eof(&self) -> bool {+ self.flushed && self.buf.is_empty()+ }++ /// A message sent by the client to set up context for login. The server+ /// responds to a client PRELOGIN message with a message of packet header+ /// type 0x04 and with the packet data containing a PRELOGIN structure.+ ///+ /// This message stream is also used to wrap the TLS handshake payload if+ /// encryption is needed. In this scenario, where PRELOGIN message is+ /// transporting the TLS handshake payload, the packet data is simply the+ /// raw bytes of the TLS handshake payload.+ async fn prelogin(+ &mut self,+ encryption: EncryptionLevel,+ fed_auth_required: bool,+ ) -> crate::Result<PreloginMessage> {+ let mut msg = PreloginMessage::new();+ msg.encryption = encryption;+ msg.fed_auth_required = fed_auth_required;++ let id = self.context.next_packet_id();+ self.send(PacketHeader::pre_login(id), msg).await?;++ let response: PreloginMessage = codec::collect_from(self).await?;+ // threadid (should be empty when sent from server to client)+ debug_assert_eq!(response.thread_id, 0);+ Ok(response)+ }++ /// Defines the login record rules with SQL Server. Authentication with+ /// connection options.+ #[allow(clippy::too_many_arguments)]+ async fn login<'a>(+ mut self,+ auth: AuthMethod,+ encryption: EncryptionLevel,+ db: Option<String>,+ server_name: Option<String>,+ application_name: Option<String>,+ readonly: bool,+ prelogin: PreloginMessage,+ ) -> crate::Result<Self> {+ let mut login_message = LoginMessage::new();++ if let Some(db) = db {+ login_message.db_name(db);+ }++ if let Some(server_name) = server_name {+ login_message.server_name(server_name);+ }++ if let Some(app_name) = application_name {+ login_message.app_name(app_name);+ }++ login_message.readonly(readonly);++ match auth {+ #[cfg(all(windows, feature = "winauth"))]+ AuthMethod::Integrated => {+ let mut client = NtlmSspiBuilder::new()+ .target_spn(self.context.spn())+ .build()?;++ login_message.integrated_security(client.next_bytes(None)?);++ let id = self.context.next_packet_id();+ self.send(PacketHeader::login(id), login_message).await?;++ self = self.post_login_encryption(encryption);++ let sspi_bytes = self.flush_sspi().await?;++ match client.next_bytes(Some(sspi_bytes.as_ref()))? {+ Some(sspi_response) => {+ event!(Level::TRACE, sspi_response_len = sspi_response.len());++ let id = self.context.next_packet_id();+ let header = PacketHeader::login(id);++ let token = TokenSspi::new(sspi_response);+ self.send(header, token).await?;+ }+ None => unreachable!(),+ }+ }+ #[cfg(all(unix, feature = "integrated-auth-gssapi"))]+ AuthMethod::Integrated => {+ let mut s = OidSet::new()?;+ s.add(&GSS_MECH_KRB5)?;++ let client_cred = Cred::acquire(None, None, CredUsage::Initiate, Some(&s))?;++ let ctx = ClientCtx::new(+ client_cred,+ Name::new(self.context.spn().as_bytes(), Some(&GSS_NT_KRB5_PRINCIPAL))?,+ CtxFlags::GSS_C_MUTUAL_FLAG | CtxFlags::GSS_C_SEQUENCE_FLAG,+ None,+ );++ let init_token = ctx.step(None)?;++ login_message.integrated_security(Some(Vec::from(init_token.unwrap().deref())));++ let id = self.context.next_packet_id();+ self.send(PacketHeader::login(id), login_message).await?;++ self = self.post_login_encryption(encryption);++ let auth_bytes = self.flush_sspi().await?;++ let next_token = match ctx.step(Some(auth_bytes.as_ref()))? {+ Some(response) => {+ event!(Level::TRACE, response_len = response.len());+ TokenSspi::new(Vec::from(response.deref()))+ }+ None => {+ event!(Level::TRACE, response_len = 0);+ TokenSspi::new(Vec::new())+ }+ };++ let id = self.context.next_packet_id();+ let header = PacketHeader::login(id);++ self.send(header, next_token).await?;+ }+ #[cfg(all(windows, feature = "winauth"))]+ AuthMethod::Windows(auth) => {+ let spn = self.context.spn().to_string();+ let builder = winauth::NtlmV2ClientBuilder::new().target_spn(spn);+ let mut client = builder.build(auth.domain, auth.user, auth.password);++ login_message.integrated_security(client.next_bytes(None)?);++ let id = self.context.next_packet_id();+ self.send(PacketHeader::login(id), login_message).await?;++ self = self.post_login_encryption(encryption);++ let sspi_bytes = self.flush_sspi().await?;++ match client.next_bytes(Some(sspi_bytes.as_ref()))? {+ Some(sspi_response) => {+ event!(Level::TRACE, sspi_response_len = sspi_response.len());++ let id = self.context.next_packet_id();+ let header = PacketHeader::login(id);++ let token = TokenSspi::new(sspi_response);+ self.send(header, token).await?;+ }+ None => unreachable!(),+ }+ }+ AuthMethod::None => {+ let id = self.context.next_packet_id();+ self.send(PacketHeader::login(id), login_message).await?;+ self = self.post_login_encryption(encryption);+ }+ AuthMethod::SqlServer(auth) => {+ login_message.user_name(auth.user());+ login_message.password(auth.password());++ let id = self.context.next_packet_id();+ self.send(PacketHeader::login(id), login_message).await?;+ self = self.post_login_encryption(encryption);+ }+ AuthMethod::AADToken(token) => {+ login_message.aad_token(token, prelogin.fed_auth_required, prelogin.nonce);+ let id = self.context.next_packet_id();+ self.send(PacketHeader::login(id), login_message).await?;+ self = self.post_login_encryption(encryption);+ }+ }++ Ok(self)+ }++ /// Implements the TLS handshake with the SQL Server.+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ async fn tls_handshake(+ self,+ config: &Config,+ encryption: EncryptionLevel,+ ) -> crate::Result<Self> {+ if encryption != EncryptionLevel::NotSupported {+ event!(Level::INFO, "Performing a TLS handshake");++ let Self {+ transport, context, ..+ } = self;+ let mut stream = match transport.into_inner() {+ MaybeTlsStream::Raw(tcp) => {+ create_tls_stream(config, TlsPreloginWrapper::new(tcp)).await?+ }+ _ => unreachable!(),+ };++ stream.get_mut().handshake_complete();+ event!(Level::INFO, "TLS handshake successful");++ let transport = Framed::new(MaybeTlsStream::Tls(stream), PacketCodec);++ Ok(Self {+ transport,+ context,+ flushed: false,+ buf: BytesMut::new(),+ })+ } else {+ event!(+ Level::WARN,+ "TLS encryption is not enabled. All traffic including the login credentials are not encrypted."+ );++ Ok(self)+ }+ }++ /// Implements the TLS handshake with the SQL Server.+ #[cfg(not(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ )))]+ async fn tls_handshake(self, _: &Config, _: EncryptionLevel) -> crate::Result<Self> {+ event!(+ Level::WARN,+ "TLS encryption is not enabled. All traffic including the login credentials are not encrypted."+ );++ Ok(self)+ }++ pub(crate) async fn close(mut self) -> crate::Result<()> {+ self.transport.close().await+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> Stream for Connection<S> {+ type Item = crate::Result<Packet>;++ fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {+ let this = self.get_mut();++ match ready!(this.transport.try_poll_next_unpin(cx)) {+ Some(Ok(packet)) => {+ this.flushed = packet.is_last();+ Poll::Ready(Some(Ok(packet)))+ }+ Some(Err(e)) => Poll::Ready(Some(Err(e))),+ None => Poll::Ready(None),+ }+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> futures_util::io::AsyncRead for Connection<S> {+ fn poll_read(+ self: Pin<&mut Self>,+ cx: &mut task::Context<'_>,+ buf: &mut [u8],+ ) -> Poll<io::Result<usize>> {+ let mut this = self.get_mut();+ let size = buf.len();++ if this.buf.len() < size {+ while let Some(item) = ready!(Pin::new(&mut this).try_poll_next(cx)) {+ match item {+ Ok(packet) => {+ let (_, payload) = packet.into_parts();+ this.buf.extend(payload);++ if this.buf.len() >= size {+ break;+ }+ }+ Err(e) => {+ return Poll::Ready(Err(io::Error::new(+ io::ErrorKind::BrokenPipe,+ e.to_string(),+ )))+ }+ }+ }++ // Got EOF before having all the data.+ if this.buf.len() < size {+ return Poll::Ready(Err(io::Error::new(+ io::ErrorKind::UnexpectedEof,+ "No more packets in the wire",+ )));+ }+ }++ buf.copy_from_slice(this.buf.split_to(size).as_ref());+ Poll::Ready(Ok(size))+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> SqlReadBytes for Connection<S> {+ /// Hex dump of the current buffer.+ fn debug_buffer(&self) {+ dbg!(self.buf.as_ref().hex_dump());+ }++ /// The current execution context.+ fn context(&self) -> &Context {+ &self.context+ }++ /// A mutable reference to the current execution context.+ fn context_mut(&mut self) -> &mut Context {+ &mut self.context+ }+}diff --git a/vendor/tiberius/src/client/tls.rs b/vendor/tiberius/src/client/tls.rsnew file mode 100644index 0000000000..7a22d43330--- /dev/null+++ b/vendor/tiberius/src/client/tls.rs@@ -0,0 +1,277 @@+#[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+))]+use super::tls_stream::TlsStream;+use crate::tds::{+ codec::{Decode, Encode, PacketHeader, PacketStatus, PacketType},+ HEADER_BYTES,+};+use bytes::BytesMut;+use futures_util::io::{AsyncRead, AsyncWrite};+use futures_util::ready;+use std::{+ cmp, io,+ pin::Pin,+ task::{self, Poll},+};+use tracing::{event, Level};++/// A wrapper to handle either TLS or bare connections.+pub(crate) enum MaybeTlsStream<S: AsyncRead + AsyncWrite + Unpin + Send> {+ Raw(S),+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ Tls(TlsStream<TlsPreloginWrapper<S>>),+}++#[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+))]+impl<S: AsyncRead + AsyncWrite + Unpin + Send> MaybeTlsStream<S> {+ pub fn into_inner(self) -> S {+ match self {+ Self::Raw(s) => s,+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ Self::Tls(mut tls) => tls.get_mut().stream.take().unwrap(),+ }+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncRead for MaybeTlsStream<S> {+ fn poll_read(+ self: Pin<&mut Self>,+ cx: &mut task::Context<'_>,+ buf: &mut [u8],+ ) -> Poll<io::Result<usize>> {+ match self.get_mut() {+ MaybeTlsStream::Raw(s) => Pin::new(s).poll_read(cx, buf),+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ MaybeTlsStream::Tls(s) => Pin::new(s).poll_read(cx, buf),+ }+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncWrite for MaybeTlsStream<S> {+ fn poll_write(+ self: Pin<&mut Self>,+ cx: &mut task::Context<'_>,+ buf: &[u8],+ ) -> Poll<io::Result<usize>> {+ match self.get_mut() {+ MaybeTlsStream::Raw(s) => Pin::new(s).poll_write(cx, buf),+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ MaybeTlsStream::Tls(s) => Pin::new(s).poll_write(cx, buf),+ }+ }++ fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {+ match self.get_mut() {+ MaybeTlsStream::Raw(s) => Pin::new(s).poll_flush(cx),+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ MaybeTlsStream::Tls(s) => Pin::new(s).poll_flush(cx),+ }+ }++ fn poll_close(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {+ match self.get_mut() {+ MaybeTlsStream::Raw(s) => Pin::new(s).poll_close(cx),+ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ MaybeTlsStream::Tls(s) => Pin::new(s).poll_close(cx),+ }+ }+}++/// On TLS handshake, the server expects to get and sends back normal TDS+/// packets. To use a common TLS library, we must implement a wrapper for+/// packet handling on this stage.+///+/// What it does is it interferes on handshake for TDS packet handling,+/// and when complete, just passes the calls to the underlying connection.+pub(crate) struct TlsPreloginWrapper<S> {+ stream: Option<S>,+ pending_handshake: bool,++ header_buf: [u8; HEADER_BYTES],+ header_pos: usize,+ read_remaining: usize,++ wr_buf: Vec<u8>,+ header_written: bool,+}++#[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+))]+impl<S> TlsPreloginWrapper<S> {+ pub fn new(stream: S) -> Self {+ TlsPreloginWrapper {+ stream: Some(stream),+ pending_handshake: true,++ header_buf: [0u8; HEADER_BYTES],+ header_pos: 0,+ read_remaining: 0,+ wr_buf: vec![0u8; HEADER_BYTES],+ header_written: false,+ }+ }++ pub fn handshake_complete(&mut self) {+ self.pending_handshake = false;+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncRead for TlsPreloginWrapper<S> {+ fn poll_read(+ mut self: Pin<&mut Self>,+ cx: &mut task::Context<'_>,+ buf: &mut [u8],+ ) -> Poll<io::Result<usize>> {+ // Normal operation does not need any extra treatment, we handle packets+ // in the codec.+ if !self.pending_handshake {+ return Pin::new(&mut self.stream.as_mut().unwrap()).poll_read(cx, buf);+ }++ let inner = self.get_mut();++ // Read the headers separately and do not send them to the Tls+ // connection handling.+ if !inner.header_buf[inner.header_pos..].is_empty() {+ while !inner.header_buf[inner.header_pos..].is_empty() {+ let read = ready!(Pin::new(inner.stream.as_mut().unwrap())+ .poll_read(cx, &mut inner.header_buf[inner.header_pos..]))?;++ if read == 0 {+ return Poll::Ready(Ok(0));+ }++ inner.header_pos += read;+ }++ let header = PacketHeader::decode(&mut BytesMut::from(&inner.header_buf[..]))+ .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;++ // We only get pre-login packets in the handshake process.+ assert_eq!(header.r#type(), PacketType::PreLogin);++ // And we know from this point on how much data we should expect+ inner.read_remaining = header.length() as usize - HEADER_BYTES;++ event!(+ Level::TRACE,+ "Reading packet of {} bytes",+ inner.read_remaining,+ );+ }++ let max_read = cmp::min(inner.read_remaining, buf.len());++ // TLS connector gets whatever we have after the header.+ let read = ready!(+ Pin::new(&mut inner.stream.as_mut().unwrap()).poll_read(cx, &mut buf[..max_read])+ )?;++ inner.read_remaining -= read;++ // All data is read, after this we're expecting a new header.+ if inner.read_remaining == 0 {+ inner.header_pos = 0;+ }++ Poll::Ready(Ok(read))+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncWrite for TlsPreloginWrapper<S> {+ fn poll_write(+ mut self: Pin<&mut Self>,+ cx: &mut task::Context<'_>,+ buf: &[u8],+ ) -> Poll<io::Result<usize>> {+ // Normal operation does not need any extra treatment, we handle+ // packets in the codec.+ if !self.pending_handshake {+ return Pin::new(&mut self.stream.as_mut().unwrap()).poll_write(cx, buf);+ }++ // Buffering data.+ self.wr_buf.extend_from_slice(buf);++ Poll::Ready(Ok(buf.len()))+ }++ fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {+ let inner = self.get_mut();++ // If on handshake mode, wraps the data to a TDS packet before sending.+ if inner.pending_handshake && inner.wr_buf.len() > HEADER_BYTES {+ if !inner.header_written {+ let mut header = PacketHeader::new(inner.wr_buf.len(), 0);++ header.set_type(PacketType::PreLogin);+ header.set_status(PacketStatus::EndOfMessage);++ header+ .encode(&mut &mut inner.wr_buf[0..HEADER_BYTES])+ .map_err(|_| {+ io::Error::new(io::ErrorKind::InvalidInput, "Could not encode header.")+ })?;++ inner.header_written = true;+ }++ while !inner.wr_buf.is_empty() {+ event!(+ Level::TRACE,+ "Writing a packet of {} bytes",+ inner.wr_buf.len(),+ );++ let written = ready!(+ Pin::new(&mut inner.stream.as_mut().unwrap()).poll_write(cx, &inner.wr_buf)+ )?;++ inner.wr_buf.drain(..written);+ }++ inner.wr_buf.resize(HEADER_BYTES, 0);+ inner.header_written = false;+ }++ Pin::new(&mut inner.stream.as_mut().unwrap()).poll_flush(cx)+ }++ fn poll_close(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {+ Pin::new(&mut self.stream.as_mut().unwrap()).poll_close(cx)+ }+}diff --git a/vendor/tiberius/src/client/tls_stream.rs b/vendor/tiberius/src/client/tls_stream.rsnew file mode 100644index 0000000000..9eba1060f7--- /dev/null+++ b/vendor/tiberius/src/client/tls_stream.rs@@ -0,0 +1,44 @@+use crate::Config;+use futures_util::io::{AsyncRead, AsyncWrite};++#[cfg(feature = "native-tls")]+mod native_tls_stream;++#[cfg(feature = "rustls")]+mod rustls_tls_stream;++#[cfg(feature = "vendored-openssl")]+mod opentls_tls_stream;++#[cfg(feature = "native-tls")]+pub(crate) use native_tls_stream::TlsStream;++#[cfg(feature = "rustls")]+pub(crate) use rustls_tls_stream::TlsStream;++#[cfg(feature = "vendored-openssl")]+pub(crate) use opentls_tls_stream::TlsStream;++#[cfg(feature = "rustls")]+pub(crate) async fn create_tls_stream<S: AsyncRead + AsyncWrite + Unpin + Send>(+ config: &Config,+ stream: S,+) -> crate::Result<TlsStream<S>> {+ TlsStream::new(config, stream).await+}++#[cfg(feature = "native-tls")]+pub(crate) async fn create_tls_stream<S: AsyncRead + AsyncWrite + Unpin + Send>(+ config: &Config,+ stream: S,+) -> crate::Result<TlsStream<S>> {+ native_tls_stream::create_tls_stream(config, stream).await+}++#[cfg(feature = "vendored-openssl")]+pub(crate) async fn create_tls_stream<S: AsyncRead + AsyncWrite + Unpin + Send>(+ config: &Config,+ stream: S,+) -> crate::Result<TlsStream<S>> {+ opentls_tls_stream::create_tls_stream(config, stream).await+}diff --git a/vendor/tiberius/src/client/tls_stream/native_tls_stream.rs b/vendor/tiberius/src/client/tls_stream/native_tls_stream.rsnew file mode 100644index 0000000000..cf5591d80d--- /dev/null+++ b/vendor/tiberius/src/client/tls_stream/native_tls_stream.rs@@ -0,0 +1,60 @@+use crate::{+ client::{config::Config, TrustConfig},+ error::{Error, IoErrorKind},+};+pub(crate) use async_native_tls::TlsStream;+use async_native_tls::{Certificate, TlsConnector};+use futures_util::io::{AsyncRead, AsyncWrite};+use std::fs;+use tracing::{event, Level};++pub(crate) async fn create_tls_stream<S: AsyncRead + AsyncWrite + Unpin + Send>(+ config: &Config,+ stream: S,+) -> crate::Result<TlsStream<S>> {+ let mut builder = TlsConnector::new();++ match &config.trust {+ TrustConfig::CaCertificateLocation(path) => {+ if let Ok(buf) = fs::read(path) {+ let cert = match path.extension() {+ Some(ext)+ if ext.to_ascii_lowercase() == "pem"+ || ext.to_ascii_lowercase() == "crt" =>+ {+ Some(Certificate::from_pem(&buf)?)+ }+ Some(ext) if ext.to_ascii_lowercase() == "der" => {+ Some(Certificate::from_der(&buf)?)+ }+ Some(_) | None => return Err(Error::Io {+ kind: IoErrorKind::InvalidInput,+ message: "Provided CA certificate with unsupported file-extension! Supported types are pem, crt and der.".to_string()}),+ };+ if let Some(c) = cert {+ builder = builder.add_root_certificate(c);+ }+ } else {+ return Err(Error::Io {+ kind: IoErrorKind::InvalidData,+ message: "Could not read provided CA certificate!".to_string(),+ });+ }+ }+ TrustConfig::TrustAll => {+ event!(+ Level::WARN,+ "Trusting the server certificate without validation."+ );++ builder = builder.danger_accept_invalid_certs(true);+ builder = builder.danger_accept_invalid_hostnames(true);+ builder = builder.use_sni(false);+ }+ TrustConfig::Default => {+ event!(Level::INFO, "Using default trust configuration.");+ }+ }++ Ok(builder.connect(config.get_host(), stream).await?)+}diff --git a/vendor/tiberius/src/client/tls_stream/opentls_tls_stream.rs b/vendor/tiberius/src/client/tls_stream/opentls_tls_stream.rsnew file mode 100644index 0000000000..1f028669e2--- /dev/null+++ b/vendor/tiberius/src/client/tls_stream/opentls_tls_stream.rs@@ -0,0 +1,60 @@+use crate::{+ client::{config::Config, TrustConfig},+ error::{Error, IoErrorKind},+};+use futures_util::io::{AsyncRead, AsyncWrite};+pub(crate) use opentls::async_io::{TlsConnector, TlsStream};+use opentls::Certificate;+use std::fs;+use tracing::{event, Level};++pub(crate) async fn create_tls_stream<S: AsyncRead + AsyncWrite + Unpin + Send>(+ config: &Config,+ stream: S,+) -> crate::Result<TlsStream<S>> {+ let mut builder = TlsConnector::new();++ match &config.trust {+ TrustConfig::CaCertificateLocation(path) => {+ if let Ok(buf) = fs::read(path) {+ let cert = match path.extension() {+ Some(ext)+ if ext.to_ascii_lowercase() == "pem"+ || ext.to_ascii_lowercase() == "crt" =>+ {+ Some(Certificate::from_pem(&buf)?)+ }+ Some(ext) if ext.to_ascii_lowercase() == "der" => {+ Some(Certificate::from_der(&buf)?)+ }+ Some(_) | None => return Err(Error::Io {+ kind: IoErrorKind::InvalidInput,+ message: "Provided CA certificate with unsupported file-extension! Supported types are pem, crt and der.".to_string()}),+ };+ if let Some(c) = cert {+ builder = builder.add_root_certificate(c);+ }+ } else {+ return Err(Error::Io {+ kind: IoErrorKind::InvalidData,+ message: "Could not read provided CA certificate!".to_string(),+ });+ }+ }+ TrustConfig::TrustAll => {+ event!(+ Level::WARN,+ "Trusting the server certificate without validation."+ );++ builder = builder.danger_accept_invalid_certs(true);+ builder = builder.danger_accept_invalid_hostnames(true);+ builder = builder.use_sni(false);+ }+ TrustConfig::Default => {+ event!(Level::INFO, "Using default trust configuration.");+ }+ }++ Ok(builder.connect(config.get_host(), stream).await?)+}diff --git a/vendor/tiberius/src/client/tls_stream/rustls_tls_stream.rs b/vendor/tiberius/src/client/tls_stream/rustls_tls_stream.rsnew file mode 100644index 0000000000..e417583a63--- /dev/null+++ b/vendor/tiberius/src/client/tls_stream/rustls_tls_stream.rs@@ -0,0 +1,215 @@+use crate::{+ client::{config::Config, TrustConfig},+ error::IoErrorKind,+ Error,+};+use futures_util::io::{AsyncRead, AsyncWrite};+use std::{+ fs, io,+ pin::Pin,+ sync::Arc,+ task::{Context, Poll},+ time::SystemTime,+};+use tokio_rustls::{+ rustls::{+ client::{+ HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier,+ WantsTransparencyPolicyOrClientCert,+ },+ Certificate, ClientConfig, ConfigBuilder, DigitallySignedStruct, Error as RustlsError,+ RootCertStore, ServerName, WantsVerifier,+ },+ TlsConnector,+};+use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt};+use tracing::{event, Level};++impl From<tokio_rustls::rustls::Error> for Error {+ fn from(e: tokio_rustls::rustls::Error) -> Self {+ crate::Error::Tls(e.to_string())+ }+}++pub(crate) struct TlsStream<S: AsyncRead + AsyncWrite + Unpin + Send>(+ Compat<tokio_rustls::client::TlsStream<Compat<S>>>,+);++struct NoCertVerifier;++impl ServerCertVerifier for NoCertVerifier {+ fn verify_server_cert(+ &self,+ _end_entity: &Certificate,+ _intermediates: &[Certificate],+ _server_name: &ServerName,+ _scts: &mut dyn Iterator<Item = &[u8]>,+ _ocsp_response: &[u8],+ _now: SystemTime,+ ) -> Result<ServerCertVerified, RustlsError> {+ Ok(ServerCertVerified::assertion())+ }++ fn verify_tls12_signature(+ &self,+ _message: &[u8],+ _cert: &Certificate,+ _dss: &DigitallySignedStruct,+ ) -> Result<HandshakeSignatureValid, RustlsError> {+ Ok(HandshakeSignatureValid::assertion())+ }+}++fn get_server_name(config: &Config) -> crate::Result<ServerName> {+ match (ServerName::try_from(config.get_host()), &config.trust) {+ (Ok(sn), _) => Ok(sn),+ (Err(_), TrustConfig::TrustAll) => {+ Ok(ServerName::try_from("placeholder.domain.com").unwrap())+ }+ (Err(e), _) => Err(crate::Error::Tls(e.to_string())),+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> TlsStream<S> {+ pub(super) async fn new(config: &Config, stream: S) -> crate::Result<Self> {+ event!(Level::INFO, "Performing a TLS handshake");++ let builder = ClientConfig::builder().with_safe_defaults();++ let client_config = match &config.trust {+ TrustConfig::CaCertificateLocation(path) => {+ if let Ok(buf) = fs::read(path) {+ let cert = match path.extension() {+ Some(ext)+ if ext.to_ascii_lowercase() == "pem"+ || ext.to_ascii_lowercase() == "crt" =>+ {+ let pem_cert = rustls_pemfile::certs(&mut buf.as_slice())?;+ if pem_cert.len() != 1 {+ return Err(crate::Error::Io {+ kind: IoErrorKind::InvalidInput,+ message: format!("Certificate file {} contain 0 or more than 1 certs", path.to_string_lossy()),+ });+ }++ Certificate(pem_cert.into_iter().next().unwrap())+ }+ Some(ext) if ext.to_ascii_lowercase() == "der" => {+ Certificate(buf)+ }+ Some(_) | None => return Err(crate::Error::Io {+ kind: IoErrorKind::InvalidInput,+ message: "Provided CA certificate with unsupported file-extension! Supported types are pem, crt and der.".to_string(),+ }),+ };+ let mut cert_store = RootCertStore::empty();+ cert_store.add(&cert)?;+ builder+ .with_root_certificates(cert_store)+ .with_no_client_auth()+ } else {+ return Err(Error::Io {+ kind: IoErrorKind::InvalidData,+ message: "Could not read provided CA certificate!".to_string(),+ });+ }+ }+ TrustConfig::TrustAll => {+ event!(+ Level::WARN,+ "Trusting the server certificate without validation."+ );+ let mut config = builder+ .with_root_certificates(RootCertStore::empty())+ .with_no_client_auth();+ config+ .dangerous()+ .set_certificate_verifier(Arc::new(NoCertVerifier {}));+ // config.enable_sni = false;+ config+ }+ TrustConfig::Default => {+ event!(Level::INFO, "Using default trust configuration.");+ builder.with_native_roots().with_no_client_auth()+ }+ };++ let connector = TlsConnector::from(Arc::new(client_config));++ let tls_stream = connector+ .connect(get_server_name(config)?, stream.compat())+ .await?;++ Ok(TlsStream(tls_stream.compat()))+ }++ pub(crate) fn get_mut(&mut self) -> &mut S {+ self.0.get_mut().get_mut().0.get_mut()+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncRead for TlsStream<S> {+ fn poll_read(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ buf: &mut [u8],+ ) -> Poll<io::Result<usize>> {+ let inner = Pin::get_mut(self);+ Pin::new(&mut inner.0).poll_read(cx, buf)+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncWrite for TlsStream<S> {+ fn poll_write(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ buf: &[u8],+ ) -> Poll<io::Result<usize>> {+ let inner = Pin::get_mut(self);+ Pin::new(&mut inner.0).poll_write(cx, buf)+ }++ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ let inner = Pin::get_mut(self);+ Pin::new(&mut inner.0).poll_flush(cx)+ }++ fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ let inner = Pin::get_mut(self);+ Pin::new(&mut inner.0).poll_close(cx)+ }+}++trait ConfigBuilderExt {+ fn with_native_roots(self) -> ConfigBuilder<ClientConfig, WantsTransparencyPolicyOrClientCert>;+}++impl ConfigBuilderExt for ConfigBuilder<ClientConfig, WantsVerifier> {+ fn with_native_roots(self) -> ConfigBuilder<ClientConfig, WantsTransparencyPolicyOrClientCert> {+ let mut roots = RootCertStore::empty();+ let mut valid_count = 0;+ let mut invalid_count = 0;++ for cert in rustls_native_certs::load_native_certs().expect("could not load platform certs")+ {+ let cert = Certificate(cert.0);+ match roots.add(&cert) {+ Ok(_) => valid_count += 1,+ Err(err) => {+ tracing::event!(Level::TRACE, "invalid cert der {:?}", cert.0);+ tracing::event!(Level::DEBUG, "certificate parsing failed: {:?}", err);+ invalid_count += 1+ }+ }+ }+ tracing::event!(+ Level::TRACE,+ "with_native_roots processed {} valid and {} invalid certs",+ valid_count,+ invalid_count+ );+ assert!(!roots.is_empty(), "no CA certificates found");++ self.with_root_certificates(roots)+ }+}diff --git a/vendor/tiberius/src/error.rs b/vendor/tiberius/src/error.rsnew file mode 100644index 0000000000..98bf01b588--- /dev/null+++ b/vendor/tiberius/src/error.rs@@ -0,0 +1,159 @@+//! Error module+pub use crate::tds::codec::TokenError;+pub use std::io::ErrorKind as IoErrorKind;+use std::{borrow::Cow, convert::Infallible, io};+use thiserror::Error;++/// A unified error enum that contains several errors that might occurr during+/// the lifecycle of this driver+#[derive(Debug, Clone, Error, PartialEq, Eq)]+pub enum Error {+ #[error("An error occured during the attempt of performing I/O: {}", message)]+ /// An error occured when performing I/O to the server.+ Io {+ /// A list specifying general categories of I/O error.+ kind: IoErrorKind,+ /// The error description.+ message: String,+ },+ #[error("Protocol error: {}", _0)]+ /// An error happened during the request or response parsing.+ Protocol(Cow<'static, str>),+ #[error("Encoding error: {}", _0)]+ /// Server responded with encoding not supported.+ Encoding(Cow<'static, str>),+ #[error("Conversion error: {}", _0)]+ /// Conversion failure from one type to another.+ Conversion(Cow<'static, str>),+ #[error("UTF-8 error")]+ /// Tried to convert data to UTF-8 that was not valid.+ Utf8,+ #[error("UTF-16 error")]+ /// Tried to convert data to UTF-16 that was not valid.+ Utf16,+ #[error("Error parsing an integer: {}", _0)]+ /// Tried to parse an integer that was not an integer.+ ParseInt(std::num::ParseIntError),+ #[error("Token error: {}", _0)]+ /// An error returned by the server.+ Server(TokenError),+ #[error("Error forming TLS connection: {}", _0)]+ /// An error in the TLS handshake.+ Tls(String),+ #[cfg(any(all(unix, feature = "integrated-auth-gssapi"), doc))]+ #[cfg_attr(+ feature = "docs",+ doc(cfg(all(unix, feature = "integrated-auth-gssapi")))+ )]+ /// An error from the GSSAPI library.+ #[error("GSSAPI Error: {}", _0)]+ Gssapi(String),+ #[error(+ "Server requested a connection to an alternative address: `{}:{}`",+ host,+ port+ )]+ /// Server requested a connection to an alternative address.+ Routing {+ /// The requested hostname+ host: String,+ /// The requested port.+ port: u16,+ },+ #[error("BULK UPLOAD input failure: {0}")]+ /// Invalid input in Bulk Upload+ BulkInput(Cow<'static, str>),+}++impl Error {+ /// True, if the error was caused by a deadlock.+ pub fn is_deadlock(&self) -> bool {+ self.code().map(|c| c == 1205).unwrap_or(false)+ }++ /// Returns the error code, if the error originates from the+ /// server.+ pub fn code(&self) -> Option<u32> {+ match self {+ Error::Server(e) => Some(e.code()),+ _ => None,+ }+ }+}++impl From<uuid::Error> for Error {+ fn from(e: uuid::Error) -> Self {+ Self::Conversion(format!("Error convertiong a Guid value {}", e).into())+ }+}++#[cfg(feature = "native-tls")]+impl From<async_native_tls::Error> for Error {+ fn from(v: async_native_tls::Error) -> Self {+ Error::Tls(format!("{}", v))+ }+}++#[cfg(feature = "vendored-openssl")]+impl From<opentls::Error> for Error {+ fn from(v: opentls::Error) -> Self {+ Error::Tls(format!("{}", v))+ }+}++impl From<Infallible> for Error {+ fn from(_: Infallible) -> Self {+ unreachable!()+ }+}++impl From<io::Error> for Error {+ fn from(err: io::Error) -> Error {+ Self::Io {+ kind: err.kind(),+ message: format!("{}", err),+ }+ }+}++impl From<std::num::ParseIntError> for Error {+ fn from(err: std::num::ParseIntError) -> Error {+ Error::ParseInt(err)+ }+}++impl From<std::str::Utf8Error> for Error {+ fn from(_: std::str::Utf8Error) -> Error {+ Error::Utf8+ }+}++impl From<std::string::FromUtf8Error> for Error {+ fn from(_err: std::string::FromUtf8Error) -> Error {+ Error::Utf8+ }+}++impl From<std::string::FromUtf16Error> for Error {+ fn from(_err: std::string::FromUtf16Error) -> Error {+ Error::Utf16+ }+}++impl From<connection_string::Error> for Error {+ fn from(err: connection_string::Error) -> Error {+ let err = Cow::Owned(format!("{}", err));+ Error::Conversion(err)+ }+}++#[cfg(all(unix, feature = "integrated-auth-gssapi"))]+#[cfg_attr(+ feature = "docs",+ doc(cfg(all(unix, feature = "integrated-auth-gssapi")))+)]+impl From<libgssapi::error::Error> for Error {+ fn from(err: libgssapi::error::Error) -> Error {+ Error::Gssapi(format!("{}", err))+ }+}diff --git a/vendor/tiberius/src/from_sql.rs b/vendor/tiberius/src/from_sql.rsnew file mode 100644index 0000000000..8498fa01cd--- /dev/null+++ b/vendor/tiberius/src/from_sql.rs@@ -0,0 +1,134 @@+use crate::{tds::Numeric, xml::XmlData, ColumnData};+use uuid::Uuid;++/// A conversion trait from a TDS type by-reference.+///+/// A `FromSql` implementation for a Rust type is needed for using it as a+/// return parameter from [`Row#get`] or [`Row#try_get`] methods. The following+/// Rust types are already implemented to match the given server types:+///+/// |Rust type|Server type|+/// |--------|--------|+/// |`u8`|`tinyint`|+/// |`i16`|`smallint`|+/// |`i32`|`int`|+/// |`i64`|`bigint`|+/// |`f32`|`float(24)`|+/// |`f64`|`float(53)`|+/// |`bool`|`bit`|+/// |`String`/`&str`|`nvarchar`/`varchar`/`nchar`/`char`/`ntext`/`text`|+/// |`Vec<u8>`/`&[u8]`|`binary`/`varbinary`/`image`|+/// |[`Uuid`]|`uniqueidentifier`|+/// |[`Numeric`]|`numeric`/`decimal`|+/// |[`Decimal`] (with feature flag `rust_decimal`)|`numeric`/`decimal`|+/// |[`XmlData`]|`xml`|+/// |[`NaiveDateTime`] (with feature flag `chrono`)|`datetime`/`datetime2`/`smalldatetime`|+/// |[`NaiveDate`] (with feature flag `chrono`)|`date`|+/// |[`NaiveTime`] (with feature flag `chrono`)|`time`|+/// |[`DateTime`] (with feature flag `chrono`)|`datetimeoffset`|+///+/// See the [`time`] module for more information about the date and time structs.+///+/// [`Row#get`]: struct.Row.html#method.get+/// [`Row#try_get`]: struct.Row.html#method.try_get+/// [`time`]: time/index.html+/// [`Uuid`]: struct.Uuid.html+/// [`Numeric`]: numeric/struct.Numeric.html+/// [`Decimal`]: numeric/struct.Decimal.html+/// [`XmlData`]: xml/struct.XmlData.html+/// [`NaiveDateTime`]: time/chrono/struct.NaiveDateTime.html+/// [`NaiveDate`]: time/chrono/struct.NaiveDate.html+/// [`NaiveTime`]: time/chrono/struct.NaiveTime.html+/// [`DateTime`]: time/chrono/struct.DateTime.html+pub trait FromSql<'a>+where+ Self: Sized + 'a,+{+ /// Returns the value, `None` being a null value, copying the value.+ fn from_sql(value: &'a ColumnData<'static>) -> crate::Result<Option<Self>>;+}++/// A conversion trait from a TDS type by-value.+pub trait FromSqlOwned+where+ Self: Sized,+{+ /// Returns the value, `None` being a null value, taking the ownership.+ fn from_sql_owned(value: ColumnData<'static>) -> crate::Result<Option<Self>>;+}++from_sql!(bool: ColumnData::Bit(val) => (*val, val));+from_sql!(u8: ColumnData::U8(val) => (*val, val), ColumnData::I32(None) => (None, None));+from_sql!(i16: ColumnData::I16(val) => (*val, val), ColumnData::U8(None) => (None, None), ColumnData::I32(None) => (None, None));+from_sql!(i32: ColumnData::I32(val) => (*val, val), ColumnData::U8(None) => (None, None));+from_sql!(i64: ColumnData::I64(val) => (*val, val), ColumnData::U8(None) => (None, None), ColumnData::I32(None) => (None, None));+from_sql!(f32: ColumnData::F32(val) => (*val, val));+from_sql!(f64: ColumnData::F64(val) => (*val, val));+from_sql!(Uuid: ColumnData::Guid(val) => (*val, val));+from_sql!(Numeric: ColumnData::Numeric(n) => (*n, n));++impl FromSqlOwned for XmlData {+ fn from_sql_owned(value: ColumnData<'static>) -> crate::Result<Option<Self>> {+ match value {+ ColumnData::Xml(data) => Ok(data.map(|data| data.into_owned())),+ v => Err(crate::Error::Conversion(+ format!("cannot interpret {:?} as a String value", v).into(),+ )),+ }+ }+}++impl<'a> FromSql<'a> for &'a XmlData {+ fn from_sql(value: &'a ColumnData<'static>) -> crate::Result<Option<Self>> {+ match value {+ ColumnData::Xml(data) => Ok(data.as_ref().map(|s| s.as_ref())),+ v => Err(crate::Error::Conversion(+ format!("cannot interpret {:?} as a String value", v).into(),+ )),+ }+ }+}++impl FromSqlOwned for String {+ fn from_sql_owned(value: ColumnData<'static>) -> crate::Result<Option<Self>> {+ match value {+ ColumnData::String(s) => Ok(s.map(|s| s.into_owned())),+ v => Err(crate::Error::Conversion(+ format!("cannot interpret {:?} as a String value", v).into(),+ )),+ }+ }+}++impl<'a> FromSql<'a> for &'a str {+ fn from_sql(value: &'a ColumnData<'static>) -> crate::Result<Option<Self>> {+ match value {+ ColumnData::String(s) => Ok(s.as_ref().map(|s| s.as_ref())),+ v => Err(crate::Error::Conversion(+ format!("cannot interpret {:?} as a String value", v).into(),+ )),+ }+ }+}++impl FromSqlOwned for Vec<u8> {+ fn from_sql_owned(value: ColumnData<'static>) -> crate::Result<Option<Self>> {+ match value {+ ColumnData::Binary(b) => Ok(b.map(|s| s.into_owned())),+ v => Err(crate::Error::Conversion(+ format!("cannot interpret {:?} as a String value", v).into(),+ )),+ }+ }+}++impl<'a> FromSql<'a> for &'a [u8] {+ fn from_sql(value: &'a ColumnData<'static>) -> crate::Result<Option<Self>> {+ match value {+ ColumnData::Binary(b) => Ok(b.as_ref().map(|s| s.as_ref())),+ v => Err(crate::Error::Conversion(+ format!("cannot interpret {:?} as a &[u8] value", v).into(),+ )),+ }+ }+}diff --git a/vendor/tiberius/src/lib.rs b/vendor/tiberius/src/lib.rsnew file mode 100644index 0000000000..882f5ad365--- /dev/null+++ b/vendor/tiberius/src/lib.rs@@ -0,0 +1,302 @@+//! An asynchronous, runtime-independent, pure-rust Tabular Data Stream (TDS)+//! implementation for Microsoft SQL Server.+//!+//! # Connecting with async-std+//!+//! Being not bound to any single runtime, a `TcpStream` must be created+//! separately and injected to the [`Client`].+//!+//! ```no_run+//! use tiberius::{Client, Config, Query, AuthMethod};+//! use async_std::net::TcpStream;+//!+//! #[async_std::main]+//! async fn main() -> anyhow::Result<()> {+//! // Using the builder method to construct the options.+//! let mut config = Config::new();+//!+//! config.host("localhost");+//! config.port(1433);+//!+//! // Using SQL Server authentication.+//! config.authentication(AuthMethod::sql_server("SA", "<YourStrong@Passw0rd>"));+//!+//! // on production, it is not a good idea to do this+//! config.trust_cert();+//!+//! // Taking the address from the configuration, using async-std's+//! // TcpStream to connect to the server.+//! let tcp = TcpStream::connect(config.get_addr()).await?;+//!+//! // We'll disable the Nagle algorithm. Buffering is handled+//! // internally with a `Sink`.+//! tcp.set_nodelay(true)?;+//!+//! // Handling TLS, login and other details related to the SQL Server.+//! let mut client = Client::connect(config, tcp).await?;+//!+//! // Constructing a query object with one parameter annotated with `@P1`.+//! // This requires us to bind a parameter that will then be used in+//! // the statement.+//! let mut select = Query::new("SELECT @P1");+//! select.bind(-4i32);+//!+//! // A response to a query is a stream of data, that must be+//! // polled to the end before querying again. Using streams allows+//! // fetching data in an asynchronous manner, if needed.+//! let stream = select.query(&mut client).await?;+//!+//! // In this case, we know we have only one query, returning one row+//! // and one column, so calling `into_row` will consume the stream+//! // and return us the first row of the first result.+//! let row = stream.into_row().await?;+//!+//! assert_eq!(Some(-4i32), row.unwrap().get(0));+//!+//! Ok(())+//! }+//! ```+//!+//! # Connecting with Tokio+//!+//! Tokio is using their own version of `AsyncRead` and `AsyncWrite` traits,+//! meaning that when wanting to use Tiberius with Tokio, their `TcpStream`+//! needs to be wrapped in Tokio's `Compat` module.+//!+//! ```no_run+//! use tiberius::{Client, Config, AuthMethod};+//! use tokio::net::TcpStream;+//! use tokio_util::compat::TokioAsyncWriteCompatExt;+//!+//! #[tokio::main]+//! async fn main() -> anyhow::Result<()> {+//! let mut config = Config::new();+//!+//! config.host("localhost");+//! config.port(1433);+//! config.authentication(AuthMethod::sql_server("SA", "<YourStrong@Passw0rd>"));+//! config.trust_cert(); // on production, it is not a good idea to do this+//!+//! let tcp = TcpStream::connect(config.get_addr()).await?;+//! tcp.set_nodelay(true)?;+//!+//! // To be able to use Tokio's tcp, we're using the `compat_write` from+//! // the `TokioAsyncWriteCompatExt` to get a stream compatible with the+//! // traits from the `futures` crate.+//! let mut client = Client::connect(config, tcp.compat_write()).await?;+//! # client.query("SELECT @P1", &[&-4i32]).await?;+//!+//! Ok(())+//! }+//! ```+//!+//! # Ways of querying+//!+//! Tiberius offers two ways to query the database: directly from the [`Client`]+//! with the [`Client#query`] and [`Client#execute`], or additionally through+//! the [`Query`] object.+//!+//! ### With the client methods+//!+//! When the query parameters are known when writing the code, the client methods+//! are easy to use.+//!+//! ```no_run+//! # use tiberius::{Client, Config, AuthMethod};+//! # use tokio::net::TcpStream;+//! # use tokio_util::compat::TokioAsyncWriteCompatExt;+//! # #[tokio::main]+//! # async fn main() -> anyhow::Result<()> {+//! # let mut config = Config::new();+//! # config.host("localhost");+//! # config.port(1433);+//! # config.authentication(AuthMethod::sql_server("SA", "<YourStrong@Passw0rd>"));+//! # config.trust_cert();+//! # let tcp = TcpStream::connect(config.get_addr()).await?;+//! # tcp.set_nodelay(true)?;+//! # let mut client = Client::connect(config, tcp.compat_write()).await?;+//! let _res = client.query("SELECT @P1", &[&-4i32]).await?;+//! # Ok(())+//! # }+//! ```+//!+//! ### With the Query object+//!+//! In case of needing to pass the parameters from a dynamic collection, or if+//! wanting to pass them by-value, use the [`Query`] object.+//!+//! ```no_run+//! # use tiberius::{Client, Query, Config, AuthMethod};+//! # use tokio::net::TcpStream;+//! # use tokio_util::compat::TokioAsyncWriteCompatExt;+//! # #[tokio::main]+//! # async fn main() -> anyhow::Result<()> {+//! # let mut config = Config::new();+//! # config.host("localhost");+//! # config.port(1433);+//! # config.authentication(AuthMethod::sql_server("SA", "<YourStrong@Passw0rd>"));+//! # config.trust_cert();+//! # let tcp = TcpStream::connect(config.get_addr()).await?;+//! # tcp.set_nodelay(true)?;+//! # let mut client = Client::connect(config, tcp.compat_write()).await?;+//! let params = vec![String::from("foo"), String::from("bar")];+//! let mut select = Query::new("SELECT @P1, @P2, @P3");+//!+//! for param in params.into_iter() {+//! select.bind(param);+//! }+//!+//! let _res = select.query(&mut client).await?;+//! # Ok(())+//! # }+//! ```+//!+//! # Authentication+//!+//! Tiberius supports different [ways of authentication] to the SQL Server:+//!+//! - SQL Server authentication uses the facilities of the database to+//! authenticate the user.+//! - On Windows, you can authenticate using the currently logged in user or+//! specified Windows credentials.+//! - If enabling the `integrated-auth-gssapi` feature, it is possible to login+//! with the currently active Kerberos credentials.+//!+//! ## AAD(Azure Active Directory) Authentication+//!+//! Tiberius supports AAD authentication by taking an AAD token. Suggest using+//! [azure_identity](https://crates.io/crates/azure_identity) crate to retrieve+//! the token, and config tiberius with token. There is an example in examples+//! folder on how to setup this.+//!+//! # TLS+//!+//! When compiled using the default features, a TLS encryption will be available+//! and by default, used for all traffic. TLS is handled with the given+//! `TcpStream`. Please see the documentation for [`EncryptionLevel`] for+//! details.+//!+//! # SQL Browser+//!+//! On Windows platforms, connecting to the SQL Server might require going through+//! the SQL Browser service to get the correct port for the named instance. This+//! feature requires either the `sql-browser-async-std` or `sql-browser-tokio` feature+//! flag to be enabled and has a bit different way of connecting:+//!+//! ```no_run+//! # #[cfg(any(feature = "sql-browser-async-std", feature = "sql-browser-tokio"))]+//! use tiberius::{Client, Config, AuthMethod};+//! # #[cfg(any(feature = "sql-browser-async-std", feature = "sql-browser-tokio"))]+//! use async_std::net::TcpStream;+//!+//! // An extra trait that allows connecting to a named instance with the given+//! // `TcpStream`.+//! # #[cfg(any(feature = "sql-browser-async-std", feature = "sql-browser-tokio"))]+//! use tiberius::SqlBrowser;+//!+//! #[async_std::main]+//! # #[cfg(any(feature = "sql-browser-async-std", feature = "sql-browser-tokio"))]+//! async fn main() -> anyhow::Result<()> {+//! let mut config = Config::new();+//!+//! config.authentication(AuthMethod::sql_server("SA", "<password>"));+//! config.host("localhost");+//!+//! // The default port of SQL Browser+//! config.port(1434);+//!+//! // The name of the database server instance.+//! config.instance_name("INSTANCE");+//!+//! // on production, it is not a good idea to do this+//! config.trust_cert();+//!+//! // This will create a new `TcpStream` from `async-std`, connected to the+//! // right port of the named instance.+//! let tcp = TcpStream::connect_named(&config).await?;+//!+//! // And from here on continue the connection process in a normal way.+//! let mut client = Client::connect(config, tcp).await?;+//! # client.query("SELECT @P1", &[&-4i32]).await?;+//! Ok(())+//! }+//! # #[cfg(any(not(feature = "sql-browser-async-std"), not(feature = "sql-browser-tokio")))]+//! # fn main() {}+//! ```+//!+//! # Other features+//!+//! - If using an [ADO.NET connection string], it is possible to create a+//! [`Config`] from one. Please see the documentation for+//! [`from_ado_string`] for details.+//! - If wanting to use Tiberius with SQL Server version 2005, one must+//! disable the `tds73` feature.+//!+//! [`EncryptionLevel`]: enum.EncryptionLevel.html+//! [`Client`]: struct.Client.html+//! [`Client#query`]: struct.Client.html#method.query+//! [`Client#execute`]: struct.Client.html#method.execute+//! [`Query`]: struct.Query.html+//! [`Query#bind`]: struct.Query.html#method.bind+//! [`Config`]: struct.Config.html+//! [`from_ado_string`]: struct.Config.html#method.from_ado_string+//! [`time`]: time/index.html+//! [ways of authentication]: enum.AuthMethod.html+//! [ADO.NET connection string]: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings+#![cfg_attr(feature = "docs", feature(doc_cfg))]+#![recursion_limit = "512"]+#![warn(missing_docs)]+#![warn(missing_debug_implementations, rust_2018_idioms)]+#![doc(test(attr(deny(rust_2018_idioms, warnings))))]+#![doc(test(attr(allow(unused_extern_crates, unused_variables))))]++#[cfg(feature = "bigdecimal")]+pub(crate) extern crate bigdecimal_ as bigdecimal;++#[macro_use]+mod macros;++mod client;+mod from_sql;+mod query;+mod sql_read_bytes;+mod to_sql;++pub mod error;+mod result;+mod row;+mod tds;++mod sql_browser;++pub use client::{AuthMethod, Client, Config};+pub(crate) use error::Error;+pub use from_sql::{FromSql, FromSqlOwned};+pub use query::Query;+pub use result::*;+pub use row::{Column, ColumnType, Row};+pub use sql_browser::SqlBrowser;+pub use tds::{+ codec::{BulkLoadRequest, ColumnData, ColumnFlag, IntoRow, TokenRow, TypeLength},+ numeric,+ stream::QueryStream,+ time, xml, EncryptionLevel,+};+pub use to_sql::{IntoSql, ToSql};+pub use uuid::Uuid;++use sql_read_bytes::*;+use tds::codec::*;++/// An alias for a result that holds crate's error type as the error.+pub type Result<T> = std::result::Result<T, Error>;++pub(crate) fn get_driver_version() -> u64 {+ env!("CARGO_PKG_VERSION")+ .splitn(6, '.')+ .enumerate()+ .fold(0u64, |acc, part| match part.1.parse::<u64>() {+ Ok(num) => acc | num << (part.0 * 8),+ _ => acc | 0 << (part.0 * 8),+ })+}diff --git a/vendor/tiberius/src/macros.rs b/vendor/tiberius/src/macros.rsnew file mode 100644index 0000000000..35f24228ff--- /dev/null+++ b/vendor/tiberius/src/macros.rs@@ -0,0 +1,145 @@+macro_rules! uint_enum {+ ($( #[$gattr:meta] )* pub enum $ty:ident { $( $( #[$attr:meta] )* $variant:ident = $val:expr,)* }) => {+ uint_enum!($( #[$gattr ])* (pub) enum $ty { $( $( #[$attr] )* $variant = $val, )* });+ };+ ($( #[$gattr:meta] )* enum $ty:ident { $( $( #[$attr:meta] )* $variant:ident = $val:expr,)* }) => {+ #[allow(missing_docs)]+ uint_enum!($( #[$gattr ])* () enum $ty { $( $( #[$attr] )* $variant = $val, )* });+ };++ ($( #[$gattr:meta] )* ( $($vis:tt)* ) enum $ty:ident { $( $( #[$attr:meta] )* $variant:ident = $val:expr,)* }) => {+ #[derive(Debug, Copy, Clone, PartialEq, Eq)]+ $( #[$gattr] )*+ #[allow(missing_docs)]+ $( $vis )* enum $ty {+ $( $( #[$attr ])* $variant = $val, )*+ }++ impl ::std::convert::TryFrom<u8> for $ty {+ type Error = ();+ fn try_from(n: u8) -> ::std::result::Result<$ty, ()> {+ match n {+ $( x if x == $ty::$variant as u8 => Ok($ty::$variant), )*+ _ => Err(()),+ }+ }+ }++ impl ::std::convert::TryFrom<u32> for $ty {+ type Error = ();+ fn try_from(n: u32) -> ::std::result::Result<$ty, ()> {+ match n {+ $( x if x == $ty::$variant as u32 => Ok($ty::$variant), )*+ _ => Err(()),+ }+ }+ }+ }+}++macro_rules! to_sql {+ ($target:ident, $( $ty:ty: ($variant:expr, $val:expr) ;)* ) => {+ $(+ impl crate::ToSql for $ty {+ fn to_sql(&self) -> crate::tds::codec::ColumnData<'_> {+ let $target = self;+ $variant(Some($val))+ }+ }++ impl crate::ToSql for Option<$ty> {+ fn to_sql(&self) -> crate::tds::codec::ColumnData<'_> {+ match self {+ Some(val) => {+ let $target = val;+ $variant(Some($val))+ },+ None => $variant(None)+ }+ }+ }++ impl crate::ToSql for &Option<$ty> {+ fn to_sql(&self) -> crate::tds::codec::ColumnData<'_> {+ match self {+ Some(val) => {+ let $target = val;+ $variant(Some($val))+ },+ None => $variant(None)+ }+ }+ }+ )*+ };+}++macro_rules! into_sql {+ ($target:ident, $( $ty:ty: ($variant:expr, $val:expr) ;)* ) => {+ $(+ impl<'a> crate::IntoSql<'a> for $ty {+ fn into_sql(self) -> crate::tds::codec::ColumnData<'a> {+ let $target = self;+ $variant(Some($val))+ }+ }++ impl<'a> crate::IntoSql<'a> for Option<$ty> {+ fn into_sql(self) -> crate::tds::codec::ColumnData<'a> {+ match self {+ Some(val) => {+ let $target = val;+ $variant(Some($val))+ },+ None => $variant(None)+ }+ }+ }+ )*+ }+}++macro_rules! from_sql {+ ($( $ty:ty: $($pat:pat => ($borrowed_val:expr, $owned_val:expr)),* );* ) => {+ $(+ impl<'a> crate::FromSql<'a> for $ty {+ fn from_sql(data: &'a crate::tds::codec::ColumnData<'static>) -> crate::Result<Option<Self>> {+ match data {+ $( $pat => Ok($borrowed_val), )*+ _ => Err(crate::Error::Conversion(format!("cannot interpret {:?} as an {} value", data, stringify!($ty)).into()))+ }+ }+ }++ impl crate::FromSqlOwned for $ty {+ fn from_sql_owned(data: crate::tds::codec::ColumnData<'static>) -> crate::Result<Option<Self>> {+ match data {+ $( $pat => Ok($owned_val), )*+ _ => Err(crate::Error::Conversion(format!("cannot interpret {:?} as an {} value", data, stringify!($ty)).into()))+ }+ }+ }+ )*+ };+ ($( $ty:ty: $($pat:pat => $borrowed_val:expr),* );* ) => {+ $(+ impl<'a> crate::FromSql<'a> for $ty {+ fn from_sql(data: &'a crate::tds::codec::ColumnData<'static>) -> crate::Result<Option<Self>> {+ match data {+ $( $pat => Ok($borrowed_val), )*+ _ => Err(crate::Error::Conversion(format!("cannot interpret {:?} as an {} value", data, stringify!($ty)).into()))+ }+ }+ }++ impl crate::FromSqlOwned for $ty {+ fn from_sql_owned(data: crate::tds::codec::ColumnData<'static>) -> crate::Result<Option<Self>> {+ match data {+ $( $pat => Ok($borrowed_val), )*+ _ => Err(crate::Error::Conversion(format!("cannot interpret {:?} as an {} value", data, stringify!($ty)).into()))+ }+ }+ }+ )*+ };+}diff --git a/vendor/tiberius/src/query.rs b/vendor/tiberius/src/query.rsnew file mode 100644index 0000000000..86e949996d--- /dev/null+++ b/vendor/tiberius/src/query.rs@@ -0,0 +1,138 @@+use std::borrow::Cow;++use futures_util::io::{AsyncRead, AsyncWrite};++use crate::{+ tds::{codec::RpcProcId, stream::TokenStream},+ Client, ColumnData, ExecuteResult, IntoSql, QueryStream,+};++/// A query object with bind parameters.+#[derive(Debug)]+pub struct Query<'a> {+ sql: Cow<'a, str>,+ params: Vec<ColumnData<'a>>,+}++impl<'a> Query<'a> {+ /// Construct a new query object with the given SQL. If the SQL is+ /// parameterized, the given number of parameters must be bound to the+ /// object before executing.+ ///+ /// The `sql` can define the parameter placement by annotating them with+ /// `@PN`, where N is the index of the parameter, starting from `1`.+ pub fn new(sql: impl Into<Cow<'a, str>>) -> Self {+ Self {+ sql: sql.into(),+ params: Vec::new(),+ }+ }++ /// Bind a new parameter to the query. Must be called exactly as many times+ /// as there are parameters in the given SQL. Otherwise the query will fail+ /// on execution.+ pub fn bind(&mut self, param: impl IntoSql<'a> + 'a) {+ self.params.push(param.into_sql());+ }++ /// Executes SQL statements in the SQL Server, returning the number rows+ /// affected. Useful for `INSERT`, `UPDATE` and `DELETE` statements. See+ /// [`Client#execute`] for a simpler API if the parameters are statically+ /// known.+ ///+ /// # Example+ ///+ /// ```no_run+ /// # use tiberius::{Config, Query};+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let mut query = Query::new("INSERT INTO ##Test (id) VALUES (@P1), (@P2), (@P3)");+ ///+ /// query.bind("foo");+ /// query.bind(2i32);+ /// query.bind(String::from("bar"));+ ///+ /// let results = query.execute(&mut client).await?;+ /// # Ok(())+ /// # }+ /// ```+ ///+ /// [`ToSql`]: trait.ToSql.html+ /// [`FromSql`]: trait.FromSql.html+ /// [`Client#execute`]: struct.Client.html#method.execute+ pub async fn execute<'b, S>(self, client: &'b mut Client<S>) -> crate::Result<ExecuteResult>+ where+ S: AsyncRead + AsyncWrite + Unpin + Send,+ {+ client.connection.flush_stream().await?;++ let rpc_params = Client::<S>::rpc_params(self.sql);++ client+ .rpc_perform_query(RpcProcId::ExecuteSQL, rpc_params, self.params.into_iter())+ .await?;++ ExecuteResult::new(&mut client.connection).await+ }++ /// Executes SQL statements in the SQL Server, returning resulting rows.+ /// Useful for `SELECT` statements. See [`Client#query`] for a simpler API+ /// if the parameters are statically known.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::{Config, Query};+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let mut query = Query::new("SELECT @P1, @P2, @P3");+ ///+ /// query.bind(1i32);+ /// query.bind(2i32);+ /// query.bind(3i32);+ ///+ /// let stream = query.query(&mut client).await?;+ /// # Ok(())+ /// # }+ /// ```+ ///+ /// [`QueryStream`]: struct.QueryStream.html+ /// [`ToSql`]: trait.ToSql.html+ /// [`FromSql`]: trait.FromSql.html+ /// [`Client#query`]: struct.Client.html#method.query+ pub async fn query<'b, S>(self, client: &'b mut Client<S>) -> crate::Result<QueryStream<'b>>+ where+ S: AsyncRead + AsyncWrite + Unpin + Send,+ {+ client.connection.flush_stream().await?;+ let rpc_params = Client::<S>::rpc_params(self.sql);++ client+ .rpc_perform_query(RpcProcId::ExecuteSQL, rpc_params, self.params.into_iter())+ .await?;++ let ts = TokenStream::new(&mut client.connection);+ let mut result = QueryStream::new(ts.try_unfold());+ result.forward_to_metadata().await?;++ Ok(result)+ }+}diff --git a/vendor/tiberius/src/result.rs b/vendor/tiberius/src/result.rsnew file mode 100644index 0000000000..19ba6faf9f--- /dev/null+++ b/vendor/tiberius/src/result.rs@@ -0,0 +1,115 @@+pub use crate::tds::stream::{QueryItem, ResultMetadata};+use crate::{+ client::Connection,+ tds::stream::{ReceivedToken, TokenStream},+};+use futures_util::io::{AsyncRead, AsyncWrite};+use futures_util::stream::TryStreamExt;+use std::fmt::Debug;++/// A result from a query execution, listing the number of affected rows.+///+/// If executing multiple queries, the resulting counts will be come separately,+/// marking the rows affected for each query.+///+/// # Example+///+/// ```no_run+/// # use tiberius::Config;+/// # use tokio_util::compat::TokioAsyncWriteCompatExt;+/// # use std::env;+/// # #[tokio::main]+/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+/// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+/// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+/// # );+/// # let config = Config::from_ado_string(&c_str)?;+/// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+/// # tcp.set_nodelay(true)?;+/// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+/// let result = client+/// .execute(+/// "INSERT INTO #Test (id) VALUES (@P1); INSERT INTO #Test (id) VALUES (@P2, @P3)",+/// &[&1i32, &2i32, &3i32],+/// )+/// .await?;+///+/// assert_eq!(&[1, 2], result.rows_affected());+/// # Ok(())+/// # }+/// ```+///+/// [`Client`]: struct.Client.html+/// [`Rows`]: struct.Row.html+/// [`next_resultset`]: #method.next_resultset+#[derive(Debug)]+pub struct ExecuteResult {+ rows_affected: Vec<u64>,+}++impl<'a> ExecuteResult {+ pub(crate) async fn new<S: AsyncRead + AsyncWrite + Unpin + Send>(+ connection: &'a mut Connection<S>,+ ) -> crate::Result<Self> {+ let mut token_stream = TokenStream::new(connection).try_unfold();+ let mut rows_affected = Vec::new();++ while let Some(token) = token_stream.try_next().await? {+ match token {+ ReceivedToken::DoneProc(done) if done.is_final() => (),+ ReceivedToken::DoneProc(done) => rows_affected.push(done.rows()),+ ReceivedToken::DoneInProc(done) => rows_affected.push(done.rows()),+ ReceivedToken::Done(done) => rows_affected.push(done.rows()),+ _ => (),+ }+ }++ Ok(Self { rows_affected })+ }++ /// A slice of numbers of rows affected in the same order as the given+ /// queries.+ pub fn rows_affected(&self) -> &[u64] {+ self.rows_affected.as_slice()+ }++ /// Aggregates all resulting row counts into a sum.+ ///+ /// # Example+ ///+ /// ```no_run+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let rows_affected = client+ /// .execute(+ /// "INSERT INTO #Test (id) VALUES (@P1); INSERT INTO #Test (id) VALUES (@P2, @P3)",+ /// &[&1i32, &2i32, &3i32],+ /// )+ /// .await?;+ ///+ /// assert_eq!(3, rows_affected.total());+ /// # Ok(())+ /// # }+ pub fn total(self) -> u64 {+ self.rows_affected.into_iter().sum()+ }+}++impl IntoIterator for ExecuteResult {+ type Item = u64;+ type IntoIter = std::vec::IntoIter<Self::Item>;++ fn into_iter(self) -> Self::IntoIter {+ self.rows_affected.into_iter()+ }+}diff --git a/vendor/tiberius/src/row.rs b/vendor/tiberius/src/row.rsnew file mode 100644index 0000000000..5441be7006--- /dev/null+++ b/vendor/tiberius/src/row.rs@@ -0,0 +1,425 @@+use crate::{+ error::Error,+ tds::codec::{ColumnData, FixedLenType, TokenRow, TypeInfo, VarLenType},+ FromSql,+};+use std::{fmt::Display, sync::Arc};++/// A column of data from a query.+#[derive(Debug, Clone)]+pub struct Column {+ pub(crate) name: String,+ pub(crate) column_type: ColumnType,+}++impl Column {+ /// Construct a new Column.+ pub fn new(name: String, column_type: ColumnType) -> Self {+ Self { name, column_type }+ }++ /// The name of the column.+ pub fn name(&self) -> &str {+ &self.name+ }++ /// The type of the column.+ pub fn column_type(&self) -> ColumnType {+ self.column_type+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+/// The type of the column.+pub enum ColumnType {+ /// The column doesn't have a specified type.+ Null,+ /// A bit or boolean value.+ Bit,+ /// An 8-bit integer value.+ Int1,+ /// A 16-bit integer value.+ Int2,+ /// A 32-bit integer value.+ Int4,+ /// A 64-bit integer value.+ Int8,+ /// A 32-bit datetime value.+ Datetime4,+ /// A 32-bit floating point value.+ Float4,+ /// A 64-bit floating point value.+ Float8,+ /// Money value.+ Money,+ /// A TDS 7.2 datetime value.+ Datetime,+ /// A 32-bit money value.+ Money4,+ /// A unique identifier, UUID.+ Guid,+ /// N-bit integer value (variable).+ Intn,+ /// A bit value in a variable-length type.+ Bitn,+ /// A decimal value (same as `Numericn`).+ Decimaln,+ /// A numeric value (same as `Decimaln`).+ Numericn,+ /// A n-bit floating point value.+ Floatn,+ /// A n-bit datetime value (TDS 7.2).+ Datetimen,+ /// A n-bit date value (TDS 7.3).+ Daten,+ /// A n-bit time value (TDS 7.3).+ Timen,+ /// A n-bit datetime2 value (TDS 7.3).+ Datetime2,+ /// A n-bit datetime value with an offset (TDS 7.3).+ DatetimeOffsetn,+ /// A variable binary value.+ BigVarBin,+ /// A large variable string value.+ BigVarChar,+ /// A binary value.+ BigBinary,+ /// A string value.+ BigChar,+ /// A variable string value with UTF-16 encoding.+ NVarchar,+ /// A string value with UTF-16 encoding.+ NChar,+ /// A XML value.+ Xml,+ /// User-defined type.+ Udt,+ /// A text value (deprecated).+ Text,+ /// A image value (deprecated).+ Image,+ /// A text value with UTF-16 encoding (deprecated).+ NText,+ /// An SQL variant type.+ SSVariant,+}++impl From<&TypeInfo> for ColumnType {+ fn from(ti: &TypeInfo) -> Self {+ match ti {+ TypeInfo::FixedLen(flt) => match flt {+ FixedLenType::Int1 => Self::Int1,+ FixedLenType::Bit => Self::Bit,+ FixedLenType::Int2 => Self::Int2,+ FixedLenType::Int4 => Self::Int4,+ FixedLenType::Datetime4 => Self::Datetime4,+ FixedLenType::Float4 => Self::Float4,+ FixedLenType::Money => Self::Money,+ FixedLenType::Datetime => Self::Datetime,+ FixedLenType::Float8 => Self::Float8,+ FixedLenType::Money4 => Self::Money4,+ FixedLenType::Int8 => Self::Int8,+ FixedLenType::Null => Self::Null,+ },+ TypeInfo::VarLenSized(cx) => match cx.r#type() {+ VarLenType::Guid => Self::Guid,+ VarLenType::Intn => match cx.len() {+ 1 => Self::Int1,+ 2 => Self::Int2,+ 4 => Self::Int4,+ 8 => Self::Int8,+ _ => Self::Intn,+ },+ VarLenType::Bitn => Self::Bitn,+ VarLenType::Decimaln => Self::Decimaln,+ VarLenType::Numericn => Self::Numericn,+ VarLenType::Floatn => match cx.len() {+ 4 => Self::Float4,+ 8 => Self::Float8,+ _ => Self::Floatn,+ },+ VarLenType::Money => Self::Money,+ VarLenType::Datetimen => Self::Datetimen,+ #[cfg(feature = "tds73")]+ VarLenType::Daten => Self::Daten,+ #[cfg(feature = "tds73")]+ VarLenType::Timen => Self::Timen,+ #[cfg(feature = "tds73")]+ VarLenType::Datetime2 => Self::Datetime2,+ #[cfg(feature = "tds73")]+ VarLenType::DatetimeOffsetn => Self::DatetimeOffsetn,+ VarLenType::BigVarBin => Self::BigVarBin,+ VarLenType::BigVarChar => Self::BigVarChar,+ VarLenType::BigBinary => Self::BigBinary,+ VarLenType::BigChar => Self::BigChar,+ VarLenType::NVarchar => Self::NVarchar,+ VarLenType::NChar => Self::NChar,+ VarLenType::Xml => Self::Xml,+ VarLenType::Udt => Self::Udt,+ VarLenType::Text => Self::Text,+ VarLenType::Image => Self::Image,+ VarLenType::NText => Self::NText,+ VarLenType::SSVariant => Self::SSVariant,+ },+ TypeInfo::VarLenSizedPrecision { ty, .. } => match ty {+ VarLenType::Guid => Self::Guid,+ VarLenType::Intn => Self::Intn,+ VarLenType::Bitn => Self::Bitn,+ VarLenType::Decimaln => Self::Decimaln,+ VarLenType::Numericn => Self::Numericn,+ VarLenType::Floatn => Self::Floatn,+ VarLenType::Money => Self::Money,+ VarLenType::Datetimen => Self::Datetimen,+ #[cfg(feature = "tds73")]+ VarLenType::Daten => Self::Daten,+ #[cfg(feature = "tds73")]+ VarLenType::Timen => Self::Timen,+ #[cfg(feature = "tds73")]+ VarLenType::Datetime2 => Self::Datetime2,+ #[cfg(feature = "tds73")]+ VarLenType::DatetimeOffsetn => Self::DatetimeOffsetn,+ VarLenType::BigVarBin => Self::BigVarBin,+ VarLenType::BigVarChar => Self::BigVarChar,+ VarLenType::BigBinary => Self::BigBinary,+ VarLenType::BigChar => Self::BigChar,+ VarLenType::NVarchar => Self::NVarchar,+ VarLenType::NChar => Self::NChar,+ VarLenType::Xml => Self::Xml,+ VarLenType::Udt => Self::Udt,+ VarLenType::Text => Self::Text,+ VarLenType::Image => Self::Image,+ VarLenType::NText => Self::NText,+ VarLenType::SSVariant => Self::SSVariant,+ },+ TypeInfo::Xml { .. } => Self::Xml,+ }+ }+}++/// A row of data from a query.+///+/// Data can be accessed either by copying through [`get`] or [`try_get`]+/// methods, or moving by value using the [`IntoIterator`] implementation.+///+/// ```+/// # use tiberius::{Config, FromSqlOwned};+/// # use tokio_util::compat::TokioAsyncWriteCompatExt;+/// # use std::env;+/// # #[tokio::main]+/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+/// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+/// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+/// # );+/// # let config = Config::from_ado_string(&c_str)?;+/// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+/// # tcp.set_nodelay(true)?;+/// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+/// // by-reference+/// let row = client+/// .query("SELECT @P1 AS col1", &[&"test"])+/// .await?+/// .into_row()+/// .await?+/// .unwrap();+///+/// assert_eq!(Some("test"), row.get("col1"));+///+/// // ...or by-value+/// let row = client+/// .query("SELECT @P1 AS col1", &[&"test"])+/// .await?+/// .into_row()+/// .await?+/// .unwrap();+///+/// for val in row.into_iter() {+/// assert_eq!(+/// Some(String::from("test")),+/// String::from_sql_owned(val)?+/// )+/// }+/// # Ok(())+/// # }+/// ```+///+/// [`get`]: #method.get+/// [`try_get`]: #method.try_get+/// [`IntoIterator`]: #impl-IntoIterator+#[derive(Debug)]+pub struct Row {+ pub(crate) columns: Arc<Vec<Column>>,+ pub(crate) data: TokenRow<'static>,+ pub(crate) result_index: usize,+}++pub trait QueryIdx+where+ Self: Display,+{+ fn idx(&self, row: &Row) -> Option<usize>;+}++impl QueryIdx for usize {+ fn idx(&self, _row: &Row) -> Option<usize> {+ Some(*self)+ }+}++impl QueryIdx for &str {+ fn idx(&self, row: &Row) -> Option<usize> {+ row.columns.iter().position(|c| c.name() == *self)+ }+}++impl Row {+ /// Columns defining the row data. Columns listed here are in the same order+ /// as the resulting data.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let row = client+ /// .query("SELECT 1 AS foo, 2 AS bar", &[])+ /// .await?+ /// .into_row()+ /// .await?+ /// .unwrap();+ ///+ /// assert_eq!("foo", row.columns()[0].name());+ /// assert_eq!("bar", row.columns()[1].name());+ /// # Ok(())+ /// # }+ /// ```+ pub fn columns(&self) -> &[Column] {+ &self.columns+ }++ /// Return an iterator over row column-value pairs.+ pub fn cells(&self) -> impl Iterator<Item = (&Column, &ColumnData<'static>)> {+ self.columns().iter().zip(self.data.iter())+ }++ /// The result set number, starting from zero and increasing if the stream+ /// has results from more than one query.+ pub fn result_index(&self) -> usize {+ self.result_index+ }++ /// Returns the number of columns in the row.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let row = client+ /// .query("SELECT 1, 2", &[])+ /// .await?+ /// .into_row()+ /// .await?+ /// .unwrap();+ ///+ /// assert_eq!(2, row.len());+ /// # Ok(())+ /// # }+ /// ```+ #[allow(clippy::len_without_is_empty)]+ pub fn len(&self) -> usize {+ self.data.len()+ }++ /// Retrieve a column value for a given column index, which can either be+ /// the zero-indexed position or the name of the column.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # #[tokio::main]+ /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let row = client+ /// .query("SELECT @P1 AS col1", &[&1i32])+ /// .await?+ /// .into_row()+ /// .await?+ /// .unwrap();+ ///+ /// assert_eq!(Some(1i32), row.get(0));+ /// assert_eq!(Some(1i32), row.get("col1"));+ /// # Ok(())+ /// # }+ /// ```+ ///+ /// # Panics+ ///+ /// - The requested type conversion (SQL->Rust) is not possible.+ /// - The given index is out of bounds (column does not exist).+ ///+ /// Use [`try_get`] for a non-panicking version of the function.+ ///+ /// [`try_get`]: #method.try_get+ #[track_caller]+ pub fn get<'a, R, I>(&'a self, idx: I) -> Option<R>+ where+ R: FromSql<'a>,+ I: QueryIdx,+ {+ self.try_get(idx).unwrap()+ }++ /// Retrieve a column's value for a given column index.+ #[track_caller]+ pub fn try_get<'a, R, I>(&'a self, idx: I) -> crate::Result<Option<R>>+ where+ R: FromSql<'a>,+ I: QueryIdx,+ {+ let idx = idx.idx(self).ok_or_else(|| {+ Error::Conversion(format!("Could not find column with index {}", idx).into())+ })?;++ let data = self.data.get(idx).unwrap();++ R::from_sql(data)+ }+}++impl IntoIterator for Row {+ type Item = ColumnData<'static>;+ type IntoIter = std::vec::IntoIter<Self::Item>;++ fn into_iter(self) -> Self::IntoIter {+ self.data.into_iter()+ }+}diff --git a/vendor/tiberius/src/sql_browser.rs b/vendor/tiberius/src/sql_browser.rsnew file mode 100644index 0000000000..b07e8ee22e--- /dev/null+++ b/vendor/tiberius/src/sql_browser.rs@@ -0,0 +1,63 @@+#[cfg(feature = "sql-browser-tokio")]+mod tokio;++#[cfg(feature = "sql-browser-async-std")]+mod async_std;++#[cfg(feature = "sql-browser-smol")]+mod smol;++use crate::client::Config;+use async_trait::async_trait;++/// An extension trait to a `TcpStream` to find a port and connecting to a+/// named database instance.+///+/// Only needed on Windows platforms, where the server port is not known and the+/// address is in the form of `hostname\\INSTANCE`.+#[async_trait]+pub trait SqlBrowser {+ /// If the given builder defines a named instance, finds the correct port+ /// and returns a `TcpStream` to be used in the [`Client`]. If instance name+ /// is not defined, connects directly to the given host and port.+ ///+ /// [`Client`]: struct.Client.html+ async fn connect_named(builder: &Config) -> crate::Result<Self>+ where+ Self: Sized + Send + Sync;+}++#[cfg(any(+ feature = "sql-browser-async-std",+ feature = "sql-browser-tokio",+ feature = "sql-browser-smol"+))]+fn get_port_from_sql_browser_reply(+ mut buf: Vec<u8>,+ len: usize,+ instance_name: &str,+) -> crate::Result<u16> {+ const DELIMITER: &[u8] = b"tcp;";++ buf.truncate(len);++ let err = crate::Error::Conversion(+ format!("Could not resolve SQL browser instance {}", instance_name).into(),+ );++ if len == 0 {+ return Err(err);+ }++ let rsp = &buf[3..len];++ let port: u16 = rsp+ .windows(DELIMITER.len())+ .rev()+ .position(|window| window == DELIMITER)+ .and_then(|pos| rsp[(rsp.len() - pos)..].split(|item| *item == b';').next())+ .ok_or(err)+ .and_then(|val| Ok(std::str::from_utf8(val)?.parse()?))?;++ Ok(port)+}diff --git a/vendor/tiberius/src/sql_browser/async_std.rs b/vendor/tiberius/src/sql_browser/async_std.rsnew file mode 100644index 0000000000..14f55de574--- /dev/null+++ b/vendor/tiberius/src/sql_browser/async_std.rs@@ -0,0 +1,72 @@+use super::SqlBrowser;+use async_std::{+ io,+ net::{self, ToSocketAddrs},+};+use async_trait::async_trait;+use futures_util::future::TryFutureExt;+use std::time;+use tracing::Level;++#[async_trait]+impl SqlBrowser for net::TcpStream {+ /// This method can be used to connect to SQL Server named instances+ /// when on a Windows platform with the `sql-browser-async-std` feature+ /// enabled. Please see the crate examples for more detailed examples.+ async fn connect_named(builder: &crate::client::Config) -> crate::Result<Self> {+ let addrs = builder.get_addr().to_socket_addrs().await?;++ for mut addr in addrs {+ if let Some(ref instance_name) = builder.instance_name {+ // First resolve the instance to a port via the+ // SSRP protocol/MS-SQLR protocol [1]+ // [1] https://msdn.microsoft.com/en-us/library/cc219703.aspx++ let local_bind: std::net::SocketAddr = if addr.is_ipv4() {+ "0.0.0.0:0".parse().unwrap()+ } else {+ "[::]:0".parse().unwrap()+ };++ tracing::event!(+ Level::TRACE,+ "Connecting to instance `{}` using SQL Browser in port `{}`",+ instance_name,+ builder.get_port()+ );++ let msg = [&[4u8], instance_name.as_bytes()].concat();+ let mut buf = vec![0u8; 4096];++ let socket = net::UdpSocket::bind(&local_bind).await?;+ socket.send_to(&msg, &addr).await?;++ let timeout = time::Duration::from_millis(1000);++ let len = io::timeout(timeout, socket.recv(&mut buf))+ .map_err(|_| {+ crate::error::Error::Conversion(+ format!(+ "SQL browser timeout during resolving instance {}. Please check if browser is running in port {} and does the instance exist.",+ instance_name,+ builder.get_port(),+ )+ .into(),+ )+ })+ .await?;++ let port = super::get_port_from_sql_browser_reply(buf, len, instance_name)?;+ tracing::event!(Level::TRACE, "Found port `{}` from SQL Browser", port);+ addr.set_port(port);+ };++ if let Ok(stream) = net::TcpStream::connect(addr).await {+ stream.set_nodelay(true)?;+ return Ok(stream);+ }+ }++ Err(io::Error::new(io::ErrorKind::NotFound, "Could not resolve server host").into())+ }+}diff --git a/vendor/tiberius/src/sql_browser/smol.rs b/vendor/tiberius/src/sql_browser/smol.rsnew file mode 100644index 0000000000..252b834e36--- /dev/null+++ b/vendor/tiberius/src/sql_browser/smol.rs@@ -0,0 +1,79 @@+use super::SqlBrowser;+use crate::client::Config;+use async_io::Timer;+use async_net::{resolve, TcpStream, UdpSocket};+use async_trait::async_trait;+use futures_lite::FutureExt;+use futures_util::future::TryFutureExt;+use std::io;+use std::time::Duration;+use tracing::Level;++#[async_trait]+impl SqlBrowser for TcpStream {+ /// This method can be used to connect to SQL Server named instances+ /// when on a Windows paltform with the `sql-browser-tokio` feature+ /// enabled. Please see the crate examples for more detailed examples.+ async fn connect_named(builder: &Config) -> crate::Result<Self> {+ let addrs = resolve(builder.get_addr()).await?;++ for mut addr in addrs {+ if let Some(ref instance_name) = builder.instance_name {+ // First resolve the instance to a port via the+ // SSRP protocol/MS-SQLR protocol [1]+ // [1] https://msdn.microsoft.com/en-us/library/cc219703.aspx++ let local_bind: std::net::SocketAddr = if addr.is_ipv4() {+ "0.0.0.0:0".parse().unwrap()+ } else {+ "[::]:0".parse().unwrap()+ };++ tracing::event!(+ Level::TRACE,+ "Connecting to instance `{}` using SQL Browser in port `{}`",+ instance_name,+ builder.get_port()+ );++ let msg = [&[4u8], instance_name.as_bytes()].concat();+ let mut buf = vec![0u8; 4096];++ let socket = UdpSocket::bind(&local_bind).await?;+ socket.send_to(&msg, &addr).await?;++ let timeout = Duration::from_millis(1000);++ let len = socket.recv(&mut buf).or(async {+ Timer::after(timeout).await;+ Err(std::io::ErrorKind::TimedOut.into())+ })+ .map_err(|e| {+ if e.kind() == std::io::ErrorKind::TimedOut {+ crate::error::Error::Conversion(+ format!(+ "SQL browser timeout during resolving instance {}. Please check if browser is running in port {} and does the instance exist.",+ instance_name,+ builder.get_port(),+ )+ .into(),+ )+ } else {+ e.into()+ }+ }).await?;++ let port = super::get_port_from_sql_browser_reply(buf, len, instance_name)?;+ tracing::event!(Level::TRACE, "Found port `{}` from SQL Browser", port);+ addr.set_port(port);+ };++ if let Ok(stream) = TcpStream::connect(addr).await {+ stream.set_nodelay(true)?;+ return Ok(stream);+ }+ }++ Err(io::Error::new(io::ErrorKind::NotFound, "Could not resolve server host").into())+ }+}diff --git a/vendor/tiberius/src/sql_browser/tokio.rs b/vendor/tiberius/src/sql_browser/tokio.rsnew file mode 100644index 0000000000..1fbf6e0e33--- /dev/null+++ b/vendor/tiberius/src/sql_browser/tokio.rs@@ -0,0 +1,74 @@+use super::SqlBrowser;+use crate::client::Config;+use async_trait::async_trait;+use futures_util::future::TryFutureExt;+use net::{TcpStream, UdpSocket};+use std::io;+use tokio::{+ net,+ time::{self, error::Elapsed, Duration},+};+use tracing::Level;++#[async_trait]+impl SqlBrowser for TcpStream {+ /// This method can be used to connect to SQL Server named instances+ /// when on a Windows paltform with the `sql-browser-tokio` feature+ /// enabled. Please see the crate examples for more detailed examples.+ async fn connect_named(builder: &Config) -> crate::Result<Self> {+ let addrs = net::lookup_host(builder.get_addr()).await?;++ for mut addr in addrs {+ if let Some(ref instance_name) = builder.instance_name {+ // First resolve the instance to a port via the+ // SSRP protocol/MS-SQLR protocol [1]+ // [1] https://msdn.microsoft.com/en-us/library/cc219703.aspx++ let local_bind: std::net::SocketAddr = if addr.is_ipv4() {+ "0.0.0.0:0".parse().unwrap()+ } else {+ "[::]:0".parse().unwrap()+ };++ tracing::event!(+ Level::TRACE,+ "Connecting to instance `{}` using SQL Browser in port `{}`",+ instance_name,+ builder.get_port()+ );++ let msg = [&[4u8], instance_name.as_bytes()].concat();+ let mut buf = vec![0u8; 4096];++ let socket = UdpSocket::bind(&local_bind).await?;+ socket.send_to(&msg, &addr).await?;++ let timeout = Duration::from_millis(1000);++ let len = time::timeout(timeout, socket.recv(&mut buf))+ .map_err(|_: Elapsed| {+ crate::error::Error::Conversion(+ format!(+ "SQL browser timeout during resolving instance {}. Please check if browser is running in port {} and does the instance exist.",+ instance_name,+ builder.get_port(),+ )+ .into(),+ )+ })+ .await??;++ let port = super::get_port_from_sql_browser_reply(buf, len, instance_name)?;+ tracing::event!(Level::TRACE, "Found port `{}` from SQL Browser", port);+ addr.set_port(port);+ };++ if let Ok(stream) = TcpStream::connect(addr).await {+ stream.set_nodelay(true)?;+ return Ok(stream);+ }+ }++ Err(io::Error::new(io::ErrorKind::NotFound, "Could not resolve server host").into())+ }+}diff --git a/vendor/tiberius/src/sql_read_bytes.rs b/vendor/tiberius/src/sql_read_bytes.rsnew file mode 100644index 0000000000..0455a1ce76--- /dev/null+++ b/vendor/tiberius/src/sql_read_bytes.rs@@ -0,0 +1,398 @@+use crate::tds::Context;+use bytes::Buf;+use futures_util::io::AsyncRead;+use pin_project_lite::pin_project;+use std::io::ErrorKind::UnexpectedEof;+use std::{future::Future, io, mem::size_of, pin::Pin, task};+use task::Poll;++macro_rules! varchar_reader {+ ($name:ident, $length_reader:ident) => {+ pin_project! {+ #[doc(hidden)]+ pub struct $name<R> {+ #[pin]+ src: R,+ length: Option<usize>,+ buf: Option<Vec<u16>>,+ read: usize+ }+ }++ #[allow(dead_code)]+ impl<R> $name<R> {+ pub(crate) fn new(src: R) -> Self {+ Self {+ src,+ length: None,+ buf: None,+ read: 0,+ }+ }+ }++ impl<R> Future for $name<R>+ where+ R: AsyncRead,+ {+ type Output = io::Result<String>;++ fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {+ let mut me = self.project();++ // We must know the length of the string first.+ while me.length.is_none() {+ let mut read_len = $length_reader::new(&mut me.src);++ match Pin::new(&mut read_len).poll(cx) {+ Poll::Pending => return Poll::Pending,+ Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),+ Poll::Ready(Ok(length)) => {+ *me.length = Some(length as usize);+ *me.buf = Some(Vec::with_capacity(length as usize));+ }+ }+ }++ // We've set the length and initialized the buffer+ let len = me.length.unwrap();+ let buf = me.buf.as_mut().unwrap();++ // Everything's read, we can return the string.+ if *me.read == len {+ let s = String::from_utf16(&buf).map_err(|_| {+ io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 data.")+ })?;++ return Poll::Ready(Ok(s));+ }++ // Read the utf-16 data+ while *me.read < len {+ let mut read_u16 = ReadU16Le::new(&mut me.src);++ match Pin::new(&mut read_u16).poll(cx) {+ Poll::Pending => return Poll::Pending,+ Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),+ Poll::Ready(Ok(n)) => {+ buf.push(n);+ *me.read += 1;+ }+ }+ }++ // Everything's read, we can return the string.+ let s = String::from_utf16(&buf).map_err(|_| {+ io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 data.")+ })?;++ return Poll::Ready(Ok(s));+ }+ }+ };+}++macro_rules! bytes_reader {+ ($name:ident, $ty:ty, $reader:ident) => {+ bytes_reader!($name, $ty, $reader, size_of::<$ty>());+ };+ ($name:ident, $ty:ty, $reader:ident, $bytes:expr) => {+ pin_project! {+ #[doc(hidden)]+ pub struct $name<R> {+ #[pin]+ src: R,+ buf: [u8; $bytes],+ read: u8,+ }+ }++ #[allow(dead_code)]+ impl<R> $name<R> {+ pub(crate) fn new(src: R) -> Self {+ $name {+ src,+ buf: [0; $bytes],+ read: 0,+ }+ }+ }++ impl<R> Future for $name<R>+ where+ R: AsyncRead,+ {+ type Output = io::Result<$ty>;++ fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {+ let mut me = self.project();++ if *me.read == $bytes as u8 {+ return Poll::Ready(Ok(Buf::$reader(&mut &me.buf[..])));+ }++ while *me.read < $bytes as u8 {+ *me.read += match me+ .src+ .as_mut()+ .poll_read(cx, &mut me.buf[*me.read as usize..])+ {+ Poll::Pending => return Poll::Pending,+ Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),+ Poll::Ready(Ok(0)) => {+ return Poll::Ready(Err(UnexpectedEof.into()));+ }+ Poll::Ready(Ok(n)) => n as u8,+ };+ }++ let num = Buf::$reader(&mut &me.buf[..]);++ Poll::Ready(Ok(num))+ }+ }+ };+}++/// The `SqlReadBytes` trait is used to read bytes from the wire.+// Many of the methods have an `allow(dead_code)` attribute because they are not currently used but they could be anytime in the future.+pub(crate) trait SqlReadBytes: AsyncRead + Unpin {+ // Pretty-print current wire content.+ #[allow(dead_code)]+ fn debug_buffer(&self);++ // The client state.+ fn context(&self) -> &Context;++ // A mutable reference to the SQL client state.+ fn context_mut(&mut self) -> &mut Context;++ // Read a single i8 value.+ #[allow(dead_code)]+ fn read_i8(&mut self) -> ReadI8<&mut Self>+ where+ Self: Unpin,+ {+ ReadI8::new(self)+ }++ // Read a single byte value.+ fn read_u8(&mut self) -> ReadU8<&mut Self>+ where+ Self: Unpin,+ {+ ReadU8::new(self)+ }++ // Read a single big-endian u32 value.+ fn read_u32(&mut self) -> ReadU32Be<&mut Self>+ where+ Self: Unpin,+ {+ ReadU32Be::new(self)+ }++ // Read a single big-endian f32 value.+ #[allow(dead_code)]+ fn read_f32(&mut self) -> ReadF32<&mut Self>+ where+ Self: Unpin,+ {+ ReadF32::new(self)+ }++ // Read a single big-endian f64 value.+ #[allow(dead_code)]+ fn read_f64(&mut self) -> ReadF64<&mut Self>+ where+ Self: Unpin,+ {+ ReadF64::new(self)+ }++ // Read a single f32 value.+ fn read_f32_le(&mut self) -> ReadF32Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadF32Le::new(self)+ }++ // Read a single f64 value.+ fn read_f64_le(&mut self) -> ReadF64Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadF64Le::new(self)+ }++ // Read a single u16 value.+ fn read_u16_le(&mut self) -> ReadU16Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadU16Le::new(self)+ }++ // Read a single u32 value.+ fn read_u32_le(&mut self) -> ReadU32Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadU32Le::new(self)+ }++ // Read a single u64 value.+ fn read_u64_le(&mut self) -> ReadU64Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadU64Le::new(self)+ }++ // Read a single u128 value.+ #[allow(dead_code)]+ fn read_u128_le(&mut self) -> ReadU128Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadU128Le::new(self)+ }++ // Read a single i16 value.+ fn read_i16_le(&mut self) -> ReadI16Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadI16Le::new(self)+ }++ // Read a single i32 value.+ fn read_i32_le(&mut self) -> ReadI32Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadI32Le::new(self)+ }++ // Read a single i64 value.+ fn read_i64_le(&mut self) -> ReadI64Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadI64Le::new(self)+ }++ // Read a single i128 value.+ #[allow(dead_code)]+ fn read_i128_le(&mut self) -> ReadI128Le<&mut Self>+ where+ Self: Unpin,+ {+ ReadI128Le::new(self)+ }++ // A variable-length character stream defined by a length-field of an u8.+ fn read_b_varchar(&mut self) -> ReadBVarchar<&mut Self>+ where+ Self: Unpin,+ {+ ReadBVarchar::new(self)+ }++ // A variable-length character stream defined by a length-field of an u16.+ fn read_us_varchar(&mut self) -> ReadUSVarchar<&mut Self>+ where+ Self: Unpin,+ {+ ReadUSVarchar::new(self)+ }+}++varchar_reader!(ReadBVarchar, ReadU8);+varchar_reader!(ReadUSVarchar, ReadU16Le);++bytes_reader!(ReadI8, i8, get_i8);+bytes_reader!(ReadU8, u8, get_u8);+bytes_reader!(ReadU32Be, u32, get_u32);++bytes_reader!(ReadU16Le, u16, get_u16_le);+bytes_reader!(ReadU32Le, u32, get_u32_le);+bytes_reader!(ReadU64Le, u64, get_u64_le);+bytes_reader!(ReadU128Le, u128, get_u128_le);++bytes_reader!(ReadI16Le, i16, get_i16_le);+bytes_reader!(ReadI32Le, i32, get_i32_le);+bytes_reader!(ReadI64Le, i64, get_i64_le);+bytes_reader!(ReadI128Le, i128, get_i128_le);++bytes_reader!(ReadF32, f32, get_f32);+bytes_reader!(ReadF64, f64, get_f64);++bytes_reader!(ReadF32Le, f32, get_f32_le);+bytes_reader!(ReadF64Le, f64, get_f64_le);++#[cfg(test)]+pub(crate) mod test_utils {+ use crate::tds::Context;+ use crate::SqlReadBytes;+ use bytes::BytesMut;+ use futures_util::io::AsyncRead;+ use std::io;+ use std::pin::Pin;+ use std::task::Poll;++ // a test util to run decode logic on BytesMut, for testing loop back+ pub(crate) trait IntoSqlReadBytes {+ type T: SqlReadBytes;+ fn into_sql_read_bytes(self) -> Self::T;+ }++ impl IntoSqlReadBytes for BytesMut {+ type T = BytesMutReader;++ fn into_sql_read_bytes(self) -> Self::T {+ BytesMutReader { buf: self }+ }+ }++ pub(crate) struct BytesMutReader {+ buf: BytesMut,+ }++ impl AsyncRead for BytesMutReader {+ fn poll_read(+ self: Pin<&mut Self>,+ _cx: &mut std::task::Context<'_>,+ buf: &mut [u8],+ ) -> Poll<std::io::Result<usize>> {+ let this = self.get_mut();+ let size = buf.len();++ // Got EOF before having all the data.+ if this.buf.len() < size {+ return Poll::Ready(Err(io::Error::new(+ io::ErrorKind::UnexpectedEof,+ "No more packets in the wire",+ )));+ }++ buf.copy_from_slice(this.buf.split_to(size).as_ref());+ Poll::Ready(Ok(size))+ }+ }++ impl SqlReadBytes for BytesMutReader {+ fn debug_buffer(&self) {+ todo!()+ }++ fn context(&self) -> &Context {+ todo!()+ }++ fn context_mut(&mut self) -> &mut Context {+ todo!()+ }+ }+}diff --git a/vendor/tiberius/src/tds.rs b/vendor/tiberius/src/tds.rsnew file mode 100644index 0000000000..f4b6f92535--- /dev/null+++ b/vendor/tiberius/src/tds.rs@@ -0,0 +1,30 @@+pub mod codec;+mod collation;+mod context;+pub mod numeric;+pub mod stream;+pub mod time;+pub mod xml;++pub(crate) use collation::*;+pub(crate) use context::*;+pub(crate) use numeric::*;++/// The amount of bytes a packet header consists of+pub(crate) const HEADER_BYTES: usize = 8;++uint_enum! {+ /// The configured encryption level specifying if encryption is required+ #[repr(u8)]+ pub enum EncryptionLevel {+ /// Only use encryption for the login procedure+ Off = 0,+ /// Encrypt everything if possible+ On = 1,+ /// Do not encrypt anything+ NotSupported = 2,+ /// Encrypt everything and fail if not possible+ Required = 3,+ }++}diff --git a/vendor/tiberius/src/tds/codec.rs b/vendor/tiberius/src/tds/codec.rsnew file mode 100644index 0000000000..07f1331068--- /dev/null+++ b/vendor/tiberius/src/tds/codec.rs@@ -0,0 +1,64 @@+mod batch_request;+mod bulk_load;+mod column_data;+mod decode;+mod encode;+mod guid;+mod header;+mod iterator_ext;+mod login;+mod packet;+mod pre_login;+mod rpc_request;+mod token;+mod type_info;++pub use batch_request::*;+pub use bulk_load::*;+use bytes::BytesMut;+pub use column_data::*;+pub use decode::*;+pub(crate) use encode::*;+use futures_util::stream::{Stream, TryStreamExt};+pub use header::*;+pub(crate) use iterator_ext::*;+pub use login::*;+pub use packet::*;+pub use pre_login::*;+pub use rpc_request::*;+pub use token::*;+pub use type_info::*;++const HEADER_BYTES: usize = 8;+const ALL_HEADERS_LEN_TX: usize = 22;++#[derive(Debug)]+#[repr(u16)]+#[allow(dead_code)]+enum AllHeaderTy {+ QueryDescriptor = 1,+ TransactionDescriptor = 2,+ TraceActivity = 3,+}++pub struct PacketCodec;++pub(crate) async fn collect_from<S, T>(stream: &mut S) -> crate::Result<T>+where+ T: Decode<BytesMut> + Sized,+ S: Stream<Item = crate::Result<Packet>> + Unpin,+{+ let mut buf = BytesMut::new();++ while let Some(packet) = stream.try_next().await? {+ let is_last = packet.is_last();+ let (_, payload) = packet.into_parts();+ buf.extend(payload);++ if is_last {+ break;+ }+ }++ T::decode(&mut buf)+}diff --git a/vendor/tiberius/src/tds/codec/batch_request.rs b/vendor/tiberius/src/tds/codec/batch_request.rsnew file mode 100644index 0000000000..f68da0e2ec--- /dev/null+++ b/vendor/tiberius/src/tds/codec/batch_request.rs@@ -0,0 +1,33 @@+use super::{AllHeaderTy, Encode, ALL_HEADERS_LEN_TX};+use bytes::{BufMut, BytesMut};+use std::borrow::Cow;++pub struct BatchRequest<'a> {+ queries: Cow<'a, str>,+ transaction_descriptor: [u8; 8],+}++impl<'a> BatchRequest<'a> {+ pub fn new(queries: impl Into<Cow<'a, str>>, transaction_descriptor: [u8; 8]) -> Self {+ Self {+ queries: queries.into(),+ transaction_descriptor,+ }+ }+}++impl<'a> Encode<BytesMut> for BatchRequest<'a> {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u32_le(ALL_HEADERS_LEN_TX as u32);+ dst.put_u32_le(ALL_HEADERS_LEN_TX as u32 - 4);+ dst.put_u16_le(AllHeaderTy::TransactionDescriptor as u16);+ dst.put_slice(&self.transaction_descriptor);+ dst.put_u32_le(1);++ for c in self.queries.encode_utf16() {+ dst.put_u16_le(c);+ }++ Ok(())+ }+}diff --git a/vendor/tiberius/src/tds/codec/bulk_load.rs b/vendor/tiberius/src/tds/codec/bulk_load.rsnew file mode 100644index 0000000000..36a17d5cbe--- /dev/null+++ b/vendor/tiberius/src/tds/codec/bulk_load.rs@@ -0,0 +1,114 @@+use asynchronous_codec::BytesMut;+use futures_util::io::{AsyncRead, AsyncWrite};+use tracing::{event, Level};++use crate::{+ client::Connection, sql_read_bytes::SqlReadBytes, BytesMutWithDataColumns, ExecuteResult,+};++use super::{+ Encode, MetaDataColumn, PacketHeader, PacketStatus, TokenColMetaData, TokenDone, TokenRow,+ HEADER_BYTES,+};++/// A handler for a bulk insert data flow.+#[derive(Debug)]+pub struct BulkLoadRequest<'a, S>+where+ S: AsyncRead + AsyncWrite + Unpin + Send,+{+ connection: &'a mut Connection<S>,+ packet_id: u8,+ buf: BytesMut,+ columns: Vec<MetaDataColumn<'a>>,+}++impl<'a, S> BulkLoadRequest<'a, S>+where+ S: AsyncRead + AsyncWrite + Unpin + Send,+{+ pub(crate) fn new(+ connection: &'a mut Connection<S>,+ columns: Vec<MetaDataColumn<'a>>,+ ) -> crate::Result<Self> {+ let packet_id = connection.context_mut().next_packet_id();+ let mut buf = BytesMut::new();++ let cmd = TokenColMetaData {+ columns: columns.clone(),+ };++ cmd.encode(&mut buf)?;++ let this = Self {+ connection,+ packet_id,+ buf,+ columns,+ };++ Ok(this)+ }++ /// Adds a new row to the bulk insert, flushing only when having a full packet of data.+ ///+ /// # Warning+ ///+ /// After the last row, [`finalize`] must be called to flush the buffered+ /// data and for the data to actually be available in the table.+ ///+ /// [`finalize`]: #method.finalize+ pub async fn send(&mut self, row: TokenRow<'a>) -> crate::Result<()> {+ let mut buf_with_columns = BytesMutWithDataColumns::new(&mut self.buf, &self.columns);++ row.encode(&mut buf_with_columns)?;+ self.write_packets().await?;++ Ok(())+ }++ /// Ends the bulk load, flushing all pending data to the wire.+ ///+ /// This method must be called after sending all the data to flush all+ /// pending data and to get the server actually to store the rows to the+ /// table.+ pub async fn finalize(mut self) -> crate::Result<ExecuteResult> {+ TokenDone::default().encode(&mut self.buf)?;+ self.write_packets().await?;++ let mut header = PacketHeader::bulk_load(self.packet_id);+ header.set_status(PacketStatus::EndOfMessage);++ let data = self.buf.split();++ event!(+ Level::TRACE,+ "Finalizing a bulk insert ({} bytes)",+ data.len() + HEADER_BYTES,+ );++ self.connection.write_to_wire(header, data).await?;+ self.connection.flush_sink().await?;++ ExecuteResult::new(self.connection).await+ }++ async fn write_packets(&mut self) -> crate::Result<()> {+ let packet_size = (self.connection.context().packet_size() as usize) - HEADER_BYTES;++ while self.buf.len() > packet_size {+ let header = PacketHeader::bulk_load(self.packet_id);+ let data = self.buf.split_to(packet_size);++ event!(+ Level::TRACE,+ "Bulk insert packet ({} bytes)",+ data.len() + HEADER_BYTES,+ );++ self.connection.write_to_wire(header, data).await?;+ }++ Ok(())+ }+}diff --git a/vendor/tiberius/src/tds/codec/column_data.rs b/vendor/tiberius/src/tds/codec/column_data.rsnew file mode 100644index 0000000000..5933160d1b--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data.rs@@ -0,0 +1,1590 @@+mod binary;+mod bit;+mod bytes_mut_with_type_info;+#[cfg(feature = "tds73")]+mod date;+#[cfg(feature = "tds73")]+mod datetime2;+mod datetimen;+#[cfg(feature = "tds73")]+mod datetimeoffsetn;+mod fixed_len;+mod float;+mod guid;+mod image;+mod int;+mod money;+mod plp;+mod string;+mod text;+#[cfg(feature = "tds73")]+mod time;+mod var_len;+mod xml;++use super::{Encode, FixedLenType, TypeInfo, VarLenType};+#[cfg(feature = "tds73")]+use crate::tds::time::{Date, DateTime2, DateTimeOffset, Time};+use crate::{+ tds::{time::DateTime, time::SmallDateTime, xml::XmlData, Numeric},+ SqlReadBytes,+};+use bytes::BufMut;+pub(crate) use bytes_mut_with_type_info::BytesMutWithTypeInfo;+use std::borrow::{BorrowMut, Cow};+use uuid::Uuid;++const MAX_NVARCHAR_SIZE: usize = 1 << 30;++#[derive(Clone, Debug, PartialEq)]+/// A container of a value that can be represented as a TDS value.+pub enum ColumnData<'a> {+ /// 8-bit integer, unsigned.+ U8(Option<u8>),+ /// 16-bit integer, signed.+ I16(Option<i16>),+ /// 32-bit integer, signed.+ I32(Option<i32>),+ /// 64-bit integer, signed.+ I64(Option<i64>),+ /// 32-bit floating point number.+ F32(Option<f32>),+ /// 64-bit floating point number.+ F64(Option<f64>),+ /// Boolean.+ Bit(Option<bool>),+ /// A string value.+ String(Option<Cow<'a, str>>),+ /// A Guid (UUID) value.+ Guid(Option<Uuid>),+ /// Binary data.+ Binary(Option<Cow<'a, [u8]>>),+ /// Numeric value (a decimal).+ Numeric(Option<Numeric>),+ /// XML data.+ Xml(Option<Cow<'a, XmlData>>),+ /// DateTime value.+ DateTime(Option<DateTime>),+ /// A small DateTime value.+ SmallDateTime(Option<SmallDateTime>),+ #[cfg(feature = "tds73")]+ #[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+ /// Time value.+ Time(Option<Time>),+ #[cfg(feature = "tds73")]+ #[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+ /// Date value.+ Date(Option<Date>),+ #[cfg(feature = "tds73")]+ #[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+ /// DateTime2 value.+ DateTime2(Option<DateTime2>),+ #[cfg(feature = "tds73")]+ #[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+ /// DateTime2 value with an offset.+ DateTimeOffset(Option<DateTimeOffset>),+}++impl<'a> ColumnData<'a> {+ pub(crate) fn type_name(&self) -> Cow<'static, str> {+ match self {+ ColumnData::U8(_) => "tinyint".into(),+ ColumnData::I16(_) => "smallint".into(),+ ColumnData::I32(_) => "int".into(),+ ColumnData::I64(_) => "bigint".into(),+ ColumnData::F32(_) => "float(24)".into(),+ ColumnData::F64(_) => "float(53)".into(),+ ColumnData::Bit(_) => "bit".into(),+ ColumnData::String(None) => "nvarchar(4000)".into(),+ ColumnData::String(Some(ref s)) if s.len() <= 4000 => "nvarchar(4000)".into(),+ ColumnData::String(Some(ref s)) if s.len() <= MAX_NVARCHAR_SIZE => {+ "nvarchar(max)".into()+ }+ ColumnData::String(_) => "ntext(max)".into(),+ ColumnData::Guid(_) => "uniqueidentifier".into(),+ ColumnData::Binary(Some(ref b)) if b.len() <= 8000 => "varbinary(8000)".into(),+ ColumnData::Binary(_) => "varbinary(max)".into(),+ ColumnData::Numeric(Some(ref n)) => {+ format!("numeric({},{})", n.precision(), n.scale()).into()+ }+ ColumnData::Numeric(None) => "numeric".into(),+ ColumnData::Xml(_) => "xml".into(),+ ColumnData::DateTime(_) => "datetime".into(),+ ColumnData::SmallDateTime(_) => "smalldatetime".into(),+ #[cfg(feature = "tds73")]+ ColumnData::Time(_) => "time".into(),+ #[cfg(feature = "tds73")]+ ColumnData::Date(_) => "date".into(),+ #[cfg(feature = "tds73")]+ ColumnData::DateTime2(_) => "datetime2".into(),+ #[cfg(feature = "tds73")]+ ColumnData::DateTimeOffset(_) => "datetimeoffset".into(),+ }+ }++ pub(crate) async fn decode<R>(src: &mut R, ctx: &TypeInfo) -> crate::Result<ColumnData<'a>>+ where+ R: SqlReadBytes + Unpin,+ {+ let res = match ctx {+ TypeInfo::FixedLen(fixed_ty) => fixed_len::decode(src, fixed_ty).await?,+ TypeInfo::VarLenSized(cx) => var_len::decode(src, cx).await?,+ TypeInfo::VarLenSizedPrecision { ty, scale, .. } => match ty {+ VarLenType::Decimaln | VarLenType::Numericn => {+ ColumnData::Numeric(Numeric::decode(src, *scale).await?)+ }+ _ => todo!(),+ },+ TypeInfo::Xml { schema, size } => xml::decode(src, *size, schema.clone()).await?,+ };++ Ok(res)+ }+}++impl<'a> Encode<BytesMutWithTypeInfo<'a>> for ColumnData<'a> {+ fn encode(self, dst: &mut BytesMutWithTypeInfo<'a>) -> crate::Result<()> {+ match (self, dst.type_info()) {+ (ColumnData::Bit(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Bitn =>+ {+ if let Some(val) = opt {+ dst.put_u8(1);+ dst.put_u8(val as u8);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::Bit(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Bit))) => {+ dst.put_u8(val as u8);+ }+ (ColumnData::Bit(Some(val)), None) => {+ // if TypeInfo was not given, encode a TypeInfo+ // the first 1 is part of TYPE_INFO+ // the second 1 is part of TYPE_VARBYTE+ let header = [VarLenType::Bitn as u8, 1, 1];+ dst.extend_from_slice(&header);+ dst.put_u8(val as u8);+ }+ (ColumnData::U8(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Intn =>+ {+ if let Some(val) = opt {+ dst.put_u8(1);+ dst.put_u8(val);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::U8(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Int1))) => {+ dst.put_u8(val);+ }+ (ColumnData::U8(Some(val)), None) => {+ let header = [VarLenType::Intn as u8, 1, 1];+ dst.extend_from_slice(&header);+ dst.put_u8(val);+ }+ (ColumnData::I16(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Int2))) => {+ dst.put_i16_le(val);+ }+ (ColumnData::I16(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Intn =>+ {+ if let Some(val) = opt {+ dst.put_u8(2);+ dst.put_i16_le(val);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::I16(Some(val)), None) => {+ let header = [VarLenType::Intn as u8, 2, 2];+ dst.extend_from_slice(&header);++ dst.put_i16_le(val);+ }+ (ColumnData::I32(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Int4))) => {+ dst.put_i32_le(val);+ }+ (ColumnData::I32(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Intn =>+ {+ if let Some(val) = opt {+ dst.put_u8(4);+ dst.put_i32_le(val);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::I32(Some(val)), None) => {+ let header = [VarLenType::Intn as u8, 4, 4];+ dst.extend_from_slice(&header);+ dst.put_i32_le(val);+ }+ (ColumnData::I64(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Int8))) => {+ dst.put_i64_le(val);+ }+ (ColumnData::I64(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Intn =>+ {+ if let Some(val) = opt {+ dst.put_u8(8);+ dst.put_i64_le(val);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::I64(Some(val)), None) => {+ let header = [VarLenType::Intn as u8, 8, 8];+ dst.extend_from_slice(&header);+ dst.put_i64_le(val);+ }+ (ColumnData::F32(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Float4))) => {+ dst.put_f32_le(val);+ }+ (ColumnData::F32(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Floatn =>+ {+ if let Some(val) = opt {+ dst.put_u8(4);+ dst.put_f32_le(val);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::F32(Some(val)), None) => {+ let header = [VarLenType::Floatn as u8, 4, 4];+ dst.extend_from_slice(&header);+ dst.put_f32_le(val);+ }+ (ColumnData::F64(Some(val)), Some(TypeInfo::FixedLen(FixedLenType::Float8))) => {+ dst.put_f64_le(val);+ }+ (ColumnData::F64(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Floatn =>+ {+ if let Some(val) = opt {+ dst.put_u8(8);+ dst.put_f64_le(val);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::F64(Some(val)), None) => {+ let header = [VarLenType::Floatn as u8, 8, 8];+ dst.extend_from_slice(&header);+ dst.put_f64_le(val);+ }+ (ColumnData::Guid(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Guid =>+ {+ if let Some(uuid) = opt {+ dst.put_u8(16);++ let mut data = *uuid.as_bytes();+ super::guid::reorder_bytes(&mut data);+ dst.extend_from_slice(&data);+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::Guid(Some(uuid)), None) => {+ let header = [VarLenType::Guid as u8, 16, 16];+ dst.extend_from_slice(&header);++ let mut data = *uuid.as_bytes();+ super::guid::reorder_bytes(&mut data);+ dst.extend_from_slice(&data);+ }+ (ColumnData::String(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::BigChar+ || vlc.r#type() == VarLenType::BigVarChar =>+ {+ if let Some(str) = opt {+ let mut encoder = vlc.collation().as_ref().unwrap().encoding()?.new_encoder();+ let len = encoder+ .max_buffer_length_from_utf8_without_replacement(str.len())+ .unwrap();+ let mut bytes = Vec::with_capacity(len);+ let (res, _) = encoder.encode_from_utf8_to_vec_without_replacement(+ str.as_ref(),+ &mut bytes,+ true,+ );+ if let encoding_rs::EncoderResult::Unmappable(_) = res {+ return Err(crate::Error::Encoding("unrepresentable character".into()));+ }++ if bytes.len() > vlc.len() {+ return Err(crate::Error::BulkInput(+ format!(+ "Encoded string length {} exceed column limit {}",+ bytes.len(),+ vlc.len()+ )+ .into(),+ ));+ }++ if vlc.len() < 0xffff {+ dst.put_u16_le(bytes.len() as u16);+ dst.extend_from_slice(bytes.as_slice());+ } else {+ // unknown size+ dst.put_u64_le(0xfffffffffffffffe);++ assert!(+ str.len() < 0xffffffff,+ "if str longer than this, need to implement multiple blobs"+ );++ dst.put_u32_le(bytes.len() as u32);+ dst.extend_from_slice(bytes.as_slice());++ if !bytes.is_empty() {+ // no next blob+ dst.put_u32_le(0u32);+ }+ }+ } else if vlc.len() < 0xffff {+ dst.put_u16_le(0xffff);+ } else {+ dst.put_u64_le(0xffffffffffffffff)+ }+ }+ (ColumnData::String(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::NVarchar || vlc.r#type() == VarLenType::NChar =>+ {+ if let Some(str) = opt {+ if vlc.len() < 0xffff {+ let len_pos = dst.len();+ dst.put_u16_le(0u16);++ for chr in str.encode_utf16() {+ dst.put_u16_le(chr);+ }++ let length = dst.len() - len_pos - 2;++ if length > vlc.len() {+ return Err(crate::Error::BulkInput(+ format!(+ "Encoded string length {} exceed column limit {}",+ length,+ vlc.len()+ )+ .into(),+ ));+ }++ let dst: &mut [u8] = dst.borrow_mut();+ let mut dst = &mut dst[len_pos..];+ dst.put_u16_le(length as u16);+ } else {+ // unknown size+ dst.put_u64_le(0xfffffffffffffffe);++ assert!(+ str.len() < 0xffffffff,+ "if str longer than this, need to implement multiple blobs"+ );++ let len_pos = dst.len();+ dst.put_u32_le(0u32);++ for chr in str.encode_utf16() {+ dst.put_u16_le(chr);+ }++ let length = dst.len() - len_pos - 4;++ if length > vlc.len() {+ return Err(crate::Error::BulkInput(+ format!(+ "Encoded string length {} exceed column limit {}",+ length,+ vlc.len()+ )+ .into(),+ ));+ }++ if length > 0 {+ // no next blob+ dst.put_u32_le(0u32);+ }++ let dst: &mut [u8] = dst.borrow_mut();+ let mut dst = &mut dst[len_pos..];+ dst.put_u32_le(length as u32);+ }+ } else if vlc.len() < 0xffff {+ dst.put_u16_le(0xffff);+ } else {+ dst.put_u64_le(0xffffffffffffffff)+ }+ }+ (ColumnData::String(Some(ref s)), None) if s.len() <= 4000 => {+ dst.put_u8(VarLenType::NVarchar as u8);+ dst.put_u16_le(8000);+ dst.extend_from_slice(&[0u8; 5][..]);++ let mut length = 0u16;+ let len_pos = dst.len();++ dst.put_u16_le(length);++ for chr in s.encode_utf16() {+ length += 1;+ dst.put_u16_le(chr);+ }++ let dst: &mut [u8] = dst.borrow_mut();+ let bytes = (length * 2).to_le_bytes(); // u16, two bytes++ for (i, byte) in bytes.iter().enumerate() {+ dst[len_pos + i] = *byte;+ }+ }+ (ColumnData::String(Some(ref s)), None) => {+ // length: 0xffff and raw collation+ dst.put_u8(VarLenType::NVarchar as u8);+ dst.extend_from_slice(&[0xff_u8; 2]);+ dst.extend_from_slice(&[0u8; 5]);++ // we cannot cheaply predetermine the length of the UCS2 string beforehand+ // (2 * bytes(UTF8) is not always right) - so just let the SQL server handle it+ dst.put_u64_le(0xfffffffffffffffe_u64);++ // Write the varchar length+ let mut length = 0u32;+ let len_pos = dst.len();++ dst.put_u32_le(length);++ for chr in s.encode_utf16() {+ length += 1;+ dst.put_u16_le(chr);+ }++ if length > 0 {+ // PLP_TERMINATOR+ dst.put_u32_le(0);+ }++ let dst: &mut [u8] = dst.borrow_mut();+ let bytes = (length * 2).to_le_bytes(); // u32, four bytes++ for (i, byte) in bytes.iter().enumerate() {+ dst[len_pos + i] = *byte;+ }+ }+ (ColumnData::Binary(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::BigBinary+ || vlc.r#type() == VarLenType::BigVarBin =>+ {+ if let Some(bytes) = opt {+ if bytes.len() > vlc.len() {+ return Err(crate::Error::BulkInput(+ format!(+ "Binary length {} exceed column limit {}",+ bytes.len(),+ vlc.len()+ )+ .into(),+ ));+ }++ if vlc.len() < 0xffff {+ dst.put_u16_le(bytes.len() as u16);+ dst.extend(bytes.into_owned());+ } else {+ // unknown size+ dst.put_u64_le(0xfffffffffffffffe);+ dst.put_u32_le(bytes.len() as u32);++ if !bytes.is_empty() {+ dst.extend(bytes.into_owned());+ dst.put_u32_le(0);+ }+ }+ } else if vlc.len() < 0xffff {+ dst.put_u16_le(0xffff);+ } else {+ dst.put_u64_le(0xffffffffffffffff);+ }+ }+ (ColumnData::Binary(Some(bytes)), None) if bytes.len() <= 8000 => {+ dst.put_u8(VarLenType::BigVarBin as u8);+ dst.put_u16_le(8000);+ dst.put_u16_le(bytes.len() as u16);+ dst.extend(bytes.into_owned());+ }+ (ColumnData::Binary(Some(bytes)), None) => {+ dst.put_u8(VarLenType::BigVarBin as u8);+ // Max length+ dst.put_u16_le(0xffff_u16);+ // Also the length is unknown+ dst.put_u64_le(0xfffffffffffffffe_u64);+ // We'll write in one chunk, length is the whole bytes length+ dst.put_u32_le(bytes.len() as u32);++ if !bytes.is_empty() {+ // Payload+ dst.extend(bytes.into_owned());+ // PLP_TERMINATOR+ dst.put_u32_le(0);+ }+ }+ (ColumnData::DateTime(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Datetimen =>+ {+ if let Some(dt) = opt {+ dst.put_u8(8);+ dt.encode(dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::DateTime(Some(dt)), Some(TypeInfo::FixedLen(FixedLenType::Datetime))) => {+ dt.encode(dst)?;+ }+ (ColumnData::DateTime(Some(dt)), None) => {+ dst.extend_from_slice(&[VarLenType::Datetimen as u8, 8, 8]);+ dt.encode(&mut *dst)?;+ }+ (ColumnData::SmallDateTime(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Datetimen =>+ {+ if let Some(dt) = opt {+ dst.put_u8(4);+ dt.encode(dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ (+ ColumnData::SmallDateTime(Some(dt)),+ Some(TypeInfo::FixedLen(FixedLenType::Datetime4)),+ ) => {+ dt.encode(dst)?;+ }+ (ColumnData::SmallDateTime(Some(dt)), None) => {+ dst.extend_from_slice(&[VarLenType::Datetimen as u8, 4, 4]);+ dt.encode(&mut *dst)?;+ }+ #[cfg(feature = "tds73")]+ (ColumnData::Date(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Daten =>+ {+ if let Some(dt) = opt {+ dst.put_u8(3);+ dt.encode(dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ #[cfg(feature = "tds73")]+ (ColumnData::Date(Some(date)), None) => {+ dst.extend_from_slice(&[VarLenType::Daten as u8, 3]);+ date.encode(&mut *dst)?;+ }+ #[cfg(feature = "tds73")]+ (ColumnData::Time(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Timen =>+ {+ if let Some(time) = opt {+ dst.put_u8(time.len()?);+ time.encode(dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ #[cfg(feature = "tds73")]+ (ColumnData::Time(Some(time)), None) => {+ dst.extend_from_slice(&[VarLenType::Timen as u8, time.scale(), time.len()?]);+ time.encode(&mut *dst)?;+ }+ #[cfg(feature = "tds73")]+ (ColumnData::DateTime2(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::Datetime2 =>+ {+ if let Some(mut dt2) = opt {+ if dt2.time().scale() != vlc.len() as u8 {+ let time = dt2.time();+ let increments = (time.increments() as f64+ * 10_f64.powi(vlc.len() as i32 - time.scale() as i32))+ as u64;+ dt2 = DateTime2::new(dt2.date(), Time::new(increments, vlc.len() as u8));+ }+ dst.put_u8(dt2.time().len()? + 3);+ dt2.encode(dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ #[cfg(feature = "tds73")]+ (ColumnData::DateTime2(Some(dt)), None) => {+ let len = dt.time().len()? + 3;+ dst.extend_from_slice(&[VarLenType::Datetime2 as u8, dt.time().scale(), len]);+ dt.encode(&mut *dst)?;+ }+ #[cfg(feature = "tds73")]+ (ColumnData::DateTimeOffset(opt), Some(TypeInfo::VarLenSized(vlc)))+ if vlc.r#type() == VarLenType::DatetimeOffsetn =>+ {+ if let Some(dto) = opt {+ dst.put_u8(dto.datetime2().time().len()? + 5);+ dto.encode(dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ #[cfg(feature = "tds73")]+ (ColumnData::DateTimeOffset(Some(dto)), None) => {+ let headers = [+ VarLenType::DatetimeOffsetn as u8,+ dto.datetime2().time().scale(),+ dto.datetime2().time().len()? + 5,+ ];++ dst.extend_from_slice(&headers);+ dto.encode(&mut *dst)?;+ }+ (ColumnData::Xml(opt), Some(TypeInfo::Xml { .. })) => {+ if let Some(xml) = opt {+ xml.into_owned().encode(dst)?;+ } else {+ dst.put_u64_le(0xffffffffffffffff_u64);+ }+ }+ (ColumnData::Xml(Some(xml)), None) => {+ dst.put_u8(VarLenType::Xml as u8);+ dst.put_u8(0);+ xml.into_owned().encode(&mut *dst)?;+ }+ (ColumnData::Numeric(opt), Some(TypeInfo::VarLenSizedPrecision { ty, scale, .. }))+ if ty == &VarLenType::Numericn || ty == &VarLenType::Decimaln =>+ {+ if let Some(num) = opt {+ if scale != &num.scale() {+ todo!("this still need some work, if client scale not aligned with server, we need to do conversion but will lose precision")+ }+ num.encode(&mut *dst)?;+ } else {+ dst.put_u8(0);+ }+ }+ (ColumnData::Numeric(Some(num)), None) => {+ let headers = &[+ VarLenType::Numericn as u8,+ num.len(),+ num.precision(),+ num.scale(),+ ];++ dst.extend_from_slice(headers);+ num.encode(&mut *dst)?;+ }+ (_, None) => {+ // None/null+ dst.put_u8(FixedLenType::Null as u8);+ }+ (v, ref ti) => {+ return Err(crate::Error::BulkInput(+ format!("invalid data type, expecting {:?} but found {:?}", ti, v).into(),+ ));+ }+ }++ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sql_read_bytes::test_utils::IntoSqlReadBytes;+ use crate::tds::Collation;+ use crate::{Error, VarLenContext};+ use bytes::{BufMut, BytesMut};++ async fn decode_wire(+ ty: VarLenType,+ len: usize,+ collation: Option<Collation>,+ wire: &[u8],+ ) -> crate::Result<ColumnData<'static>> {+ let reader = &mut BytesMut::from(wire).into_sql_read_bytes();+ ColumnData::decode(+ reader,+ &TypeInfo::VarLenSized(VarLenContext::new(ty, len, collation)),+ )+ .await+ }++ fn short_string_wire(payload: &[u8]) -> BytesMut {+ let mut wire = BytesMut::new();+ wire.put_u16_le(payload.len() as u16);+ wire.extend_from_slice(payload);+ wire+ }++ fn ntext_wire(payload: &[u8]) -> BytesMut {+ let mut wire = BytesMut::new();+ wire.put_u8(1); // text pointer length+ wire.put_u8(0); // text pointer+ wire.put_i32_le(0); // timestamp days+ wire.put_u32_le(0); // timestamp fractions+ wire.put_u32_le(payload.len() as u32);+ wire.extend_from_slice(payload);+ wire+ }++ fn decoded_string(value: ColumnData<'static>) -> Option<String> {+ match value {+ ColumnData::String(value) => value.map(Cow::into_owned),+ other => panic!("expected string column data, got {other:?}"),+ }+ }++ #[tokio::test]+ async fn nvarchar_replaces_lone_surrogates() {+ for payload in [[0x00, 0xd8], [0x00, 0xdc]] {+ let value = decode_wire(+ VarLenType::NVarchar,+ 40,+ Some(Collation::new(13632521, 52)),+ &short_string_wire(&payload),+ )+ .await+ .expect("malformed UTF-16 row values must remain readable");++ assert_eq!(decoded_string(value).as_deref(), Some("\u{fffd}"));+ }+ }++ #[tokio::test]+ async fn nchar_replaces_lone_surrogates() {+ for payload in [[0x00, 0xd8], [0x00, 0xdc]] {+ let value = decode_wire(+ VarLenType::NChar,+ 40,+ Some(Collation::new(13632521, 52)),+ &short_string_wire(&payload),+ )+ .await+ .expect("malformed UTF-16 row values must remain readable");++ assert_eq!(decoded_string(value).as_deref(), Some("\u{fffd}"));+ }+ }++ #[tokio::test]+ async fn ntext_replaces_lone_surrogates() {+ for payload in [[0x00, 0xd8], [0x00, 0xdc]] {+ let value = decode_wire(VarLenType::NText, 0, None, &ntext_wire(&payload))+ .await+ .expect("malformed UTF-16 row values must remain readable");++ assert_eq!(decoded_string(value).as_deref(), Some("\u{fffd}"));+ }+ }++ #[tokio::test]+ async fn unicode_row_values_preserve_valid_text() {+ let cases: &[(&[u8], &str)] = &[+ (&[0x2d, 0x4e, 0x87, 0x65], "中文"),+ (&[0x3d, 0xd8, 0x00, 0xde], "😀"),+ ];++ for (payload, expected) in cases {+ let nvarchar = decode_wire(+ VarLenType::NVarchar,+ 40,+ Some(Collation::new(13632521, 52)),+ &short_string_wire(payload),+ )+ .await+ .expect("valid UTF-16 must decode");+ let ntext = decode_wire(VarLenType::NText, 0, None, &ntext_wire(payload))+ .await+ .expect("valid NTEXT UTF-16 must decode");++ assert_eq!(decoded_string(nvarchar).as_deref(), Some(*expected));+ assert_eq!(decoded_string(ntext).as_deref(), Some(*expected));+ }+ }++ #[tokio::test]+ async fn unicode_row_values_preserve_nulls() {+ let nvarchar = decode_wire(+ VarLenType::NVarchar,+ 40,+ Some(Collation::new(13632521, 52)),+ &[0xff, 0xff],+ )+ .await+ .expect("NULL nvarchar must decode");+ let ntext = decode_wire(VarLenType::NText, 0, None, &[0])+ .await+ .expect("NULL ntext must decode");++ assert_eq!(decoded_string(nvarchar), None);+ assert_eq!(decoded_string(ntext), None);+ }++ #[tokio::test]+ async fn unicode_row_values_reject_odd_byte_lengths() {+ let nvarchar = decode_wire(+ VarLenType::NVarchar,+ 40,+ Some(Collation::new(13632521, 52)),+ &short_string_wire(&[0x41, 0x00, 0x42]),+ )+ .await+ .expect_err("odd nvarchar length must be a protocol error");+ let ntext = decode_wire(+ VarLenType::NText,+ 0,+ None,+ &ntext_wire(&[0x41, 0x00, 0x42]),+ )+ .await+ .expect_err("odd ntext length must be a protocol error");++ assert!(matches!(nvarchar, Error::Protocol(_)));+ assert!(matches!(ntext, Error::Protocol(_)));+ }++ #[tokio::test]+ async fn bigvarchar_keeps_codepage_decoding() {+ let value = decode_wire(+ VarLenType::BigVarChar,+ 40,+ Some(Collation::new(13632521, 52)),+ &short_string_wire(b"plain varchar"),+ )+ .await+ .expect("varchar must keep using its codepage decoder");++ assert_eq!(decoded_string(value).as_deref(), Some("plain varchar"));+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn xml_keeps_strict_utf16_decoding() {+ let reader = &mut short_string_wire(&[0x00, 0xd8]).into_sql_read_bytes();+ let error = ColumnData::decode(+ reader,+ &TypeInfo::Xml {+ schema: None,+ size: 40,+ },+ )+ .await+ .expect_err("malformed XML must retain strict UTF-16 decoding");++ assert!(matches!(error, Error::Utf16));+ }++ async fn test_round_trip(ti: TypeInfo, d: ColumnData<'_>) {+ let mut buf = BytesMut::new();+ let mut buf_with_ti = BytesMutWithTypeInfo::new(&mut buf).with_type_info(&ti);++ d.clone()+ .encode(&mut buf_with_ti)+ .expect("encode must succeed");++ let reader = &mut buf.into_sql_read_bytes();+ let nd = ColumnData::decode(reader, &ti)+ .await+ .expect("decode must succeed");++ assert_eq!(nd, d);++ reader+ .read_u8()+ .await+ .expect_err("decode must consume entire buffer");+ }++ #[tokio::test]+ async fn i32_with_varlen_int() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 4, None)),+ ColumnData::I32(Some(42)),+ )+ .await;+ }++ #[tokio::test]+ async fn none_with_varlen_int() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 4, None)),+ ColumnData::I32(None),+ )+ .await;+ }++ #[tokio::test]+ async fn i32_with_fixedlen_int() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Int4),+ ColumnData::I32(Some(42)),+ )+ .await;+ }++ #[tokio::test]+ async fn bit_with_varlen_bit() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Bitn, 1, None)),+ ColumnData::Bit(Some(true)),+ )+ .await;+ }++ #[tokio::test]+ async fn none_with_varlen_bit() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Bitn, 1, None)),+ ColumnData::Bit(None),+ )+ .await;+ }++ #[tokio::test]+ async fn bit_with_fixedlen_bit() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Bit),+ ColumnData::Bit(Some(true)),+ )+ .await;+ }++ #[tokio::test]+ async fn u8_with_varlen_int() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 1, None)),+ ColumnData::U8(Some(8u8)),+ )+ .await;+ }++ #[tokio::test]+ async fn none_u8_with_varlen_int() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 1, None)),+ ColumnData::U8(None),+ )+ .await;+ }++ #[tokio::test]+ async fn u8_with_fixedlen_int() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Int1),+ ColumnData::U8(Some(8u8)),+ )+ .await;+ }++ #[tokio::test]+ async fn i16_with_varlen_intn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 2, None)),+ ColumnData::I16(Some(8i16)),+ )+ .await;+ }++ #[tokio::test]+ async fn none_i16_with_varlen_intn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 2, None)),+ ColumnData::I16(None),+ )+ .await;+ }++ #[tokio::test]+ async fn none_with_varlen_intn() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Int2),+ ColumnData::I16(Some(8i16)),+ )+ .await;+ }++ #[tokio::test]+ async fn i64_with_varlen_intn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 8, None)),+ ColumnData::I64(Some(8i64)),+ )+ .await;+ }++ #[tokio::test]+ async fn i64_none_with_varlen_intn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 8, None)),+ ColumnData::I64(None),+ )+ .await;+ }++ #[tokio::test]+ async fn i64_with_fixedlen_int8() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Int8),+ ColumnData::I64(Some(8i64)),+ )+ .await;+ }++ #[tokio::test]+ async fn f32_with_varlen_floatn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Floatn, 4, None)),+ ColumnData::F32(Some(8f32)),+ )+ .await;+ }++ #[tokio::test]+ async fn null_f32_with_varlen_floatn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Floatn, 4, None)),+ ColumnData::F32(None),+ )+ .await;+ }++ #[tokio::test]+ async fn f32_with_fixedlen_float4() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Float4),+ ColumnData::F32(Some(8f32)),+ )+ .await;+ }++ #[tokio::test]+ async fn f64_with_varlen_floatn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Floatn, 8, None)),+ ColumnData::F64(Some(8f64)),+ )+ .await;+ }++ #[tokio::test]+ async fn none_f64_with_varlen_floatn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Floatn, 8, None)),+ ColumnData::F64(None),+ )+ .await;+ }++ #[tokio::test]+ async fn f64_with_fixedlen_float8() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Float8),+ ColumnData::F64(Some(8f64)),+ )+ .await;+ }++ #[tokio::test]+ async fn guid_with_varlen_guid() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Guid, 16, None)),+ ColumnData::Guid(Some(Uuid::new_v4())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_guid_with_varlen_guid() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Guid, 16, None)),+ ColumnData::Guid(None),+ )+ .await;+ }++ #[tokio::test]+ async fn numeric_with_varlen_sized_precision() {+ test_round_trip(+ TypeInfo::VarLenSizedPrecision {+ ty: VarLenType::Numericn,+ size: 17,+ precision: 18,+ scale: 0,+ },+ ColumnData::Numeric(Some(Numeric::new_with_scale(23, 0))),+ )+ .await;+ }++ #[tokio::test]+ async fn none_numeric_with_varlen_sized_precision() {+ test_round_trip(+ TypeInfo::VarLenSizedPrecision {+ ty: VarLenType::Numericn,+ size: 17,+ precision: 18,+ scale: 0,+ },+ ColumnData::Numeric(None),+ )+ .await;+ }++ #[tokio::test]+ async fn string_with_varlen_bigchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("aaa".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn long_string_with_varlen_bigchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigChar,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("aaa".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_long_string_with_varlen_bigchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigChar,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(None),+ )+ .await;+ }++ #[tokio::test]+ async fn none_string_with_varlen_bigchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(None),+ )+ .await;+ }++ #[tokio::test]+ async fn string_with_varlen_bigvarchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigVarChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("aaa".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_string_with_varlen_bigvarchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigVarChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(None),+ )+ .await;+ }++ #[tokio::test]+ async fn empty_string_with_varlen_bigvarchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigVarChar,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn string_with_varlen_nvarchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NVarchar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("hhh".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_string_with_varlen_nvarchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NVarchar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(None),+ )+ .await;+ }++ #[tokio::test]+ async fn empty_string_with_varlen_nvarchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NVarchar,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn string_with_varlen_nchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("hhh".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn long_string_with_varlen_nchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NChar,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(Some("hhh".into())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_long_string_with_varlen_nchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NChar,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(None),+ )+ .await;+ }++ #[tokio::test]+ async fn none_string_with_varlen_nchar() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::String(None),+ )+ .await;+ }++ #[tokio::test]+ async fn binary_with_varlen_bigbinary() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::BigBinary, 40, None)),+ ColumnData::Binary(Some(b"aaa".as_slice().into())),+ )+ .await;+ }++ #[tokio::test]+ async fn long_binary_with_varlen_bigbinary() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::BigBinary, 0x8ffff, None)),+ ColumnData::Binary(Some(b"aaa".as_slice().into())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_binary_with_varlen_bigbinary() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::BigBinary, 40, None)),+ ColumnData::Binary(None),+ )+ .await;+ }++ #[tokio::test]+ async fn none_long_binary_with_varlen_bigbinary() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::BigBinary, 0x8ffff, None)),+ ColumnData::Binary(None),+ )+ .await;+ }++ #[tokio::test]+ async fn binary_with_varlen_bigvarbin() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::BigVarBin, 40, None)),+ ColumnData::Binary(Some(b"aaa".as_slice().into())),+ )+ .await;+ }++ #[tokio::test]+ async fn none_binary_with_varlen_bigvarbin() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::BigVarBin, 40, None)),+ ColumnData::Binary(None),+ )+ .await;+ }++ #[tokio::test]+ async fn empty_binary_with_varlen_bigvarbin() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::BigVarBin,+ 0x8ffff,+ Some(Collation::new(13632521, 52)),+ )),+ ColumnData::Binary(Some(b"".as_slice().into())),+ )+ .await;+ }++ #[tokio::test]+ async fn datetime_with_varlen_datetimen() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Datetimen, 8, None)),+ ColumnData::DateTime(Some(DateTime::new(200, 3000))),+ )+ .await;+ }++ // this is inconsistent: decode will decode any None datetime to smalldatetime, ignoring size+ // but it's non-critical, so let it be here+ #[tokio::test]+ async fn none_datetime_with_varlen_datetimen() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Datetimen, 8, None)),+ ColumnData::DateTime(None),+ )+ .await;+ }++ #[tokio::test]+ async fn datetime_with_fixedlen_datetime() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Datetime),+ ColumnData::DateTime(Some(DateTime::new(200, 3000))),+ )+ .await;+ }++ #[tokio::test]+ async fn smalldatetime_with_varlen_datetimen() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Datetimen, 4, None)),+ ColumnData::SmallDateTime(Some(SmallDateTime::new(200, 3000))),+ )+ .await;+ }++ #[tokio::test]+ async fn none_smalldatetime_with_varlen_datetimen() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Datetimen, 4, None)),+ ColumnData::SmallDateTime(None),+ )+ .await;+ }++ #[tokio::test]+ async fn smalldatetime_with_fixedlen_datetime4() {+ test_round_trip(+ TypeInfo::FixedLen(FixedLenType::Datetime4),+ ColumnData::SmallDateTime(Some(SmallDateTime::new(200, 3000))),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn date_with_varlen_daten() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Daten, 3, None)),+ ColumnData::Date(Some(Date::new(200))),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn none_date_with_varlen_daten() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Daten, 3, None)),+ ColumnData::Date(None),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn time_with_varlen_timen() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Timen, 7, None)),+ ColumnData::Time(Some(Time::new(55, 7))),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn none_time_with_varlen_timen() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Timen, 7, None)),+ ColumnData::Time(None),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn datetime2_with_varlen_datetime2() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Datetime2, 7, None)),+ ColumnData::DateTime2(Some(DateTime2::new(Date::new(55), Time::new(222, 7)))),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn none_datetime2_with_varlen_datetime2() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Datetime2, 7, None)),+ ColumnData::DateTime2(None),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn datetimeoffset_with_varlen_datetimeoffsetn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::DatetimeOffsetn, 7, None)),+ ColumnData::DateTimeOffset(Some(DateTimeOffset::new(+ DateTime2::new(Date::new(55), Time::new(222, 7)),+ -8,+ ))),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn none_datetimeoffset_with_varlen_datetimeoffsetn() {+ test_round_trip(+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::DatetimeOffsetn, 7, None)),+ ColumnData::DateTimeOffset(None),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn xml_with_xml() {+ test_round_trip(+ TypeInfo::Xml {+ schema: None,+ size: 0xfffffffffffffffe_usize,+ },+ ColumnData::Xml(Some(Cow::Owned(XmlData::new("<a>ddd</a>")))),+ )+ .await;+ }++ #[cfg(feature = "tds73")]+ #[tokio::test]+ async fn none_xml_with_xml() {+ test_round_trip(+ TypeInfo::Xml {+ schema: None,+ size: 0xfffffffffffffffe_usize,+ },+ ColumnData::Xml(None),+ )+ .await;+ }++ #[tokio::test]+ async fn invalid_type_fails() {+ let data = vec![+ (+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Floatn, 4, None)),+ ColumnData::I32(Some(42)),+ ),+ (+ TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Floatn, 4, None)),+ ColumnData::I32(None),+ ),+ (+ TypeInfo::FixedLen(FixedLenType::Int4),+ ColumnData::I32(None),+ ),+ ];++ for (ti, d) in data {+ let mut buf = BytesMut::new();+ let mut buf_ti = BytesMutWithTypeInfo::new(&mut buf).with_type_info(&ti);++ let err = d.encode(&mut buf_ti).expect_err("encode should fail");++ if let Error::BulkInput(_) = err {+ } else {+ panic!("Expected: Error::BulkInput, got: {:?}", err);+ }+ }+ }+}diff --git a/vendor/tiberius/src/tds/codec/column_data/binary.rs b/vendor/tiberius/src/tds/codec/column_data/binary.rsnew file mode 100644index 0000000000..ee0346b9ff--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/binary.rs@@ -0,0 +1,12 @@+use std::borrow::Cow;++use crate::{sql_read_bytes::SqlReadBytes, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, len: usize) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let data = super::plp::decode(src, len).await?.map(Cow::from);++ Ok(ColumnData::Binary(data))+}diff --git a/vendor/tiberius/src/tds/codec/column_data/bit.rs b/vendor/tiberius/src/tds/codec/column_data/bit.rsnew file mode 100644index 0000000000..24f4b379ce--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/bit.rs@@ -0,0 +1,20 @@+use crate::{error::Error, sql_read_bytes::SqlReadBytes, ColumnData};++pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let recv_len = src.read_u8().await? as usize;++ let res = match recv_len {+ 0 => ColumnData::Bit(None),+ 1 => ColumnData::Bit(Some(src.read_u8().await? > 0)),+ v => {+ return Err(Error::Protocol(+ format!("bitn: length of {} is invalid", v).into(),+ ))+ }+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/bytes_mut_with_type_info.rs b/vendor/tiberius/src/tds/codec/column_data/bytes_mut_with_type_info.rsnew file mode 100644index 0000000000..3226590e9b--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/bytes_mut_with_type_info.rs@@ -0,0 +1,68 @@+use crate::TypeInfo;+use bytes::buf::UninitSlice;+use bytes::{BufMut, BytesMut};+use std::borrow::{Borrow, BorrowMut};+use std::ops::{Deref, DerefMut};++pub(crate) struct BytesMutWithTypeInfo<'a> {+ bytes: &'a mut BytesMut,+ type_info: Option<&'a TypeInfo>,+}++impl<'a> BytesMutWithTypeInfo<'a> {+ pub fn new(bytes: &'a mut BytesMut) -> Self {+ BytesMutWithTypeInfo {+ bytes,+ type_info: None,+ }+ }++ pub fn with_type_info(mut self, type_info: &'a TypeInfo) -> Self {+ self.type_info = Some(type_info);+ self+ }++ pub fn type_info(&self) -> Option<&'a TypeInfo> {+ self.type_info+ }+}++unsafe impl<'a> BufMut for BytesMutWithTypeInfo<'a> {+ fn remaining_mut(&self) -> usize {+ self.bytes.remaining_mut()+ }++ unsafe fn advance_mut(&mut self, cnt: usize) {+ self.bytes.advance_mut(cnt)+ }++ fn chunk_mut(&mut self) -> &mut UninitSlice {+ self.bytes.chunk_mut()+ }+}++impl<'a> Borrow<[u8]> for BytesMutWithTypeInfo<'a> {+ fn borrow(&self) -> &[u8] {+ self.bytes.deref()+ }+}++impl<'a> BorrowMut<[u8]> for BytesMutWithTypeInfo<'a> {+ fn borrow_mut(&mut self) -> &mut [u8] {+ self.bytes.borrow_mut()+ }+}++impl<'a> Deref for BytesMutWithTypeInfo<'a> {+ type Target = BytesMut;++ fn deref(&self) -> &Self::Target {+ self.bytes+ }+}++impl<'a> DerefMut for BytesMutWithTypeInfo<'a> {+ fn deref_mut(&mut self) -> &mut Self::Target {+ self.bytes+ }+}diff --git a/vendor/tiberius/src/tds/codec/column_data/date.rs b/vendor/tiberius/src/tds/codec/column_data/date.rsnew file mode 100644index 0000000000..481ecfe18d--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/date.rs@@ -0,0 +1,22 @@+use crate::Error;++use crate::{sql_read_bytes::SqlReadBytes, time::Date, ColumnData};++pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let len = src.read_u8().await?;++ let res = match len {+ 0 => ColumnData::Date(None),+ 3 => ColumnData::Date(Some(Date::decode(src).await?)),+ _ => {+ return Err(Error::Protocol(+ format!("daten: length of {} is invalid", len).into(),+ ))+ }+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/datetime2.rs b/vendor/tiberius/src/tds/codec/column_data/datetime2.rsnew file mode 100644index 0000000000..7bc1fa2627--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/datetime2.rs@@ -0,0 +1,18 @@+use crate::{sql_read_bytes::SqlReadBytes, time::DateTime2, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, len: usize) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let rlen = src.read_u8().await?;++ let date = match rlen {+ 0 => ColumnData::DateTime2(None),+ rlen => {+ let dt = DateTime2::decode(src, len, rlen as usize - 3).await?;+ ColumnData::DateTime2(Some(dt))+ }+ };++ Ok(date)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/datetimen.rs b/vendor/tiberius/src/tds/codec/column_data/datetimen.rsnew file mode 100644index 0000000000..a546152f2b--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/datetimen.rs@@ -0,0 +1,25 @@+use crate::{+ error::Error,+ sql_read_bytes::SqlReadBytes,+ time::{DateTime, SmallDateTime},+ ColumnData,+};++pub(crate) async fn decode<R>(src: &mut R, rlen: u8, len: u8) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let datetime = match (rlen, len) {+ (0, 4) => ColumnData::SmallDateTime(None),+ (0, 8) => ColumnData::DateTime(None),+ (4, _) => ColumnData::SmallDateTime(Some(SmallDateTime::decode(src).await?)),+ (8, _) => ColumnData::DateTime(Some(DateTime::decode(src).await?)),+ _ => {+ return Err(Error::Protocol(+ format!("datetimen: length of {} is invalid", len).into(),+ ))+ }+ };++ Ok(datetime)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/datetimeoffsetn.rs b/vendor/tiberius/src/tds/codec/column_data/datetimeoffsetn.rsnew file mode 100644index 0000000000..d695f34959--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/datetimeoffsetn.rs@@ -0,0 +1,18 @@+use crate::{sql_read_bytes::SqlReadBytes, time::DateTimeOffset, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, len: usize) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let rlen = src.read_u8().await?;++ let dto = match rlen {+ 0 => ColumnData::DateTimeOffset(None),+ _ => {+ let dto = DateTimeOffset::decode(src, len, rlen - 5).await?;+ ColumnData::DateTimeOffset(Some(dto))+ }+ };++ Ok(dto)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/fixed_len.rs b/vendor/tiberius/src/tds/codec/column_data/fixed_len.rsnew file mode 100644index 0000000000..26f560cdf7--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/fixed_len.rs@@ -0,0 +1,26 @@+use crate::{sql_read_bytes::SqlReadBytes, ColumnData, FixedLenType};++pub(crate) async fn decode<R>(+ src: &mut R,+ r#type: &FixedLenType,+) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let data = match r#type {+ FixedLenType::Null => ColumnData::Bit(None),+ FixedLenType::Bit => ColumnData::Bit(Some(src.read_u8().await? != 0)),+ FixedLenType::Int1 => ColumnData::U8(Some(src.read_u8().await?)),+ FixedLenType::Int2 => ColumnData::I16(Some(src.read_i16_le().await?)),+ FixedLenType::Int4 => ColumnData::I32(Some(src.read_i32_le().await?)),+ FixedLenType::Int8 => ColumnData::I64(Some(src.read_i64_le().await?)),+ FixedLenType::Float4 => ColumnData::F32(Some(src.read_f32_le().await?)),+ FixedLenType::Float8 => ColumnData::F64(Some(src.read_f64_le().await?)),+ FixedLenType::Datetime => super::datetimen::decode(src, 8, 8).await?,+ FixedLenType::Datetime4 => super::datetimen::decode(src, 4, 8).await?,+ FixedLenType::Money4 => super::money::decode(src, 4).await?,+ FixedLenType::Money => super::money::decode(src, 8).await?,+ };++ Ok(data)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/float.rs b/vendor/tiberius/src/tds/codec/column_data/float.rsnew file mode 100644index 0000000000..0f24eb4386--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/float.rs@@ -0,0 +1,22 @@+use crate::{error::Error, sql_read_bytes::SqlReadBytes, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, type_len: usize) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let len = src.read_u8().await? as usize;++ let res = match (len, type_len) {+ (0, 4) => ColumnData::F32(None),+ (0, _) => ColumnData::F64(None),+ (4, _) => ColumnData::F32(Some(src.read_f32_le().await?)),+ (8, _) => ColumnData::F64(Some(src.read_f64_le().await?)),+ _ => {+ return Err(Error::Protocol(+ format!("floatn: length of {} is invalid", len).into(),+ ))+ }+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/guid.rs b/vendor/tiberius/src/tds/codec/column_data/guid.rsnew file mode 100644index 0000000000..996cd80f41--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/guid.rs@@ -0,0 +1,31 @@+use uuid::Uuid;++use crate::{error::Error, sql_read_bytes::SqlReadBytes, tds::codec::guid, ColumnData};++pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let len = src.read_u8().await? as usize;++ let res = match len {+ 0 => ColumnData::Guid(None),+ 16 => {+ let mut data = [0u8; 16];++ for item in &mut data {+ *item = src.read_u8().await?;+ }++ guid::reorder_bytes(&mut data);+ ColumnData::Guid(Some(Uuid::from_bytes(data)))+ }+ _ => {+ return Err(Error::Protocol(+ format!("guid: length of {} is invalid", len).into(),+ ))+ }+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/image.rs b/vendor/tiberius/src/tds/codec/column_data/image.rsnew file mode 100644index 0000000000..22a12ebe29--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/image.rs@@ -0,0 +1,28 @@+use crate::{sql_read_bytes::SqlReadBytes, ColumnData};++pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let ptr_len = src.read_u8().await? as usize;++ if ptr_len == 0 {+ return Ok(ColumnData::Binary(None));+ }++ for _ in 0..ptr_len {+ src.read_u8().await?;+ }++ src.read_i32_le().await?; // days+ src.read_u32_le().await?; // second fractions++ let len = src.read_u32_le().await? as usize;+ let mut buf = Vec::with_capacity(len);++ for _ in 0..len {+ buf.push(src.read_u8().await?);+ }++ Ok(ColumnData::Binary(Some(buf.into())))+}diff --git a/vendor/tiberius/src/tds/codec/column_data/int.rs b/vendor/tiberius/src/tds/codec/column_data/int.rsnew file mode 100644index 0000000000..f9d51da48d--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/int.rs@@ -0,0 +1,22 @@+use crate::{sql_read_bytes::SqlReadBytes, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, type_len: usize) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let recv_len = src.read_u8().await? as usize;++ let res = match (recv_len, type_len) {+ (0, 1) => ColumnData::U8(None),+ (0, 2) => ColumnData::I16(None),+ (0, 4) => ColumnData::I32(None),+ (0, _) => ColumnData::I64(None),+ (1, _) => ColumnData::U8(Some(src.read_u8().await?)),+ (2, _) => ColumnData::I16(Some(src.read_i16_le().await?)),+ (4, _) => ColumnData::I32(Some(src.read_i32_le().await?)),+ (8, _) => ColumnData::I64(Some(src.read_i64_le().await?)),+ _ => unimplemented!(),+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/money.rs b/vendor/tiberius/src/tds/codec/column_data/money.rsnew file mode 100644index 0000000000..5627983d4e--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/money.rs@@ -0,0 +1,24 @@+use crate::{error::Error, sql_read_bytes::SqlReadBytes, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, len: u8) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let res = match len {+ 0 => ColumnData::F64(None),+ 4 => ColumnData::F64(Some(src.read_i32_le().await? as f64 / 1e4)),+ 8 => ColumnData::F64(Some({+ let high = src.read_i32_le().await? as i64;+ let low = src.read_u32_le().await? as f64;++ ((high << 32) as f64 + low) / 1e4+ })),+ _ => {+ return Err(Error::Protocol(+ format!("money: length of {} is invalid", len).into(),+ ))+ }+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/plp.rs b/vendor/tiberius/src/tds/codec/column_data/plp.rsnew file mode 100644index 0000000000..2c7fdb7e3a--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/plp.rs@@ -0,0 +1,64 @@+use crate::sql_read_bytes::SqlReadBytes;++// Decode a partially length-prefixed type.+pub(crate) async fn decode<R>(src: &mut R, len: usize) -> crate::Result<Option<Vec<u8>>>+where+ R: SqlReadBytes + Unpin,+{+ match len {+ // Fixed size+ len if len < 0xffff => {+ let len = src.read_u16_le().await? as u64;++ match len {+ // NULL+ 0xffff => Ok(None),+ _ => {+ let mut data = Vec::with_capacity(len as usize);++ for _ in 0..len {+ data.push(src.read_u8().await?);+ }++ Ok(Some(data))+ }+ }+ }+ // Unknown size, length-prefixed blobs+ _ => {+ let len = src.read_u64_le().await?;++ let mut data = match len {+ // NULL+ 0xffffffffffffffff => return Ok(None),+ // Unknown size+ 0xfffffffffffffffe => Vec::new(),+ // Known size+ _ => Vec::with_capacity(len as usize),+ };++ let mut chunk_data_left = 0;++ loop {+ if chunk_data_left == 0 {+ // We have no chunk. Start a new one.+ let chunk_size = src.read_u32_le().await? as usize;++ if chunk_size == 0 {+ break; // found a sentinel, we're done+ } else {+ chunk_data_left = chunk_size+ }+ } else {+ // Just read a byte+ let byte = src.read_u8().await?;+ chunk_data_left -= 1;++ data.push(byte);+ }+ }++ Ok(Some(data))+ }+ }+}diff --git a/vendor/tiberius/src/tds/codec/column_data/string.rs b/vendor/tiberius/src/tds/codec/column_data/string.rsnew file mode 100644index 0000000000..700ba65e7e--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/string.rs@@ -0,0 +1,48 @@+use std::borrow::Cow;++use byteorder::{ByteOrder, LittleEndian};++use crate::{error::Error, sql_read_bytes::SqlReadBytes, tds::Collation, VarLenType};++pub(crate) async fn decode<R>(+ src: &mut R,+ ty: VarLenType,+ len: usize,+ collation: Option<Collation>,+) -> crate::Result<Option<Cow<'static, str>>>+where+ R: SqlReadBytes + Unpin,+{+ use VarLenType::*;++ let data = super::plp::decode(src, len).await?;++ match (data, ty) {+ // Codepages other than UTF+ (Some(buf), BigChar) | (Some(buf), BigVarChar) => {+ let collation = collation.as_ref().unwrap();+ let encoder = collation.encoding()?;++ let s = encoder+ .decode_without_bom_handling_and_without_replacement(buf.as_ref())+ .ok_or_else(|| Error::Encoding("invalid sequence".into()))?+ .to_string();++ Ok(Some(s.into()))+ }+ // UTF-16+ (Some(buf), _) => {+ if buf.len() % 2 != 0 {+ return Err(Error::Protocol("nvarchar: invalid plp length".into()));+ }++ let buf: Vec<_> = buf.chunks(2).map(LittleEndian::read_u16).collect();+ let value = match ty {+ NChar | NVarchar => String::from_utf16_lossy(&buf),+ _ => String::from_utf16(&buf)?,+ };+ Ok(Some(value.into()))+ }+ _ => Ok(None),+ }+}diff --git a/vendor/tiberius/src/tds/codec/column_data/text.rs b/vendor/tiberius/src/tds/codec/column_data/text.rsnew file mode 100644index 0000000000..f73457c84f--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/text.rs@@ -0,0 +1,58 @@+use crate::{error::Error, sql_read_bytes::SqlReadBytes, tds::Collation, ColumnData};++pub(crate) async fn decode<R>(+ src: &mut R,+ collation: Option<Collation>,+) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let ptr_len = src.read_u8().await? as usize;++ if ptr_len == 0 {+ return Ok(ColumnData::String(None));+ }++ for _ in 0..ptr_len {+ src.read_u8().await?;+ }++ src.read_i32_le().await?; // days+ src.read_u32_le().await?; // second fractions++ let text = match collation {+ // TEXT+ Some(collation) => {+ let encoder = collation.encoding()?;+ let text_len = src.read_u32_le().await? as usize;+ let mut buf = Vec::with_capacity(text_len);++ for _ in 0..text_len {+ buf.push(src.read_u8().await?);+ }++ encoder+ .decode_without_bom_handling_and_without_replacement(buf.as_ref())+ .ok_or_else(|| Error::Encoding("invalid sequence".into()))?+ .to_string()+ }+ // NTEXT+ None => {+ let text_len = src.read_u32_le().await? as usize;+ if text_len % 2 != 0 {+ return Err(Error::Protocol("ntext: invalid length".into()));+ }++ let text_len = text_len / 2;+ let mut buf = Vec::with_capacity(text_len);++ for _ in 0..text_len {+ buf.push(src.read_u16_le().await?);+ }++ String::from_utf16_lossy(&buf[..])+ }+ };++ Ok(ColumnData::String(Some(text.into())))+}diff --git a/vendor/tiberius/src/tds/codec/column_data/time.rs b/vendor/tiberius/src/tds/codec/column_data/time.rsnew file mode 100644index 0000000000..350fa9a6c2--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/time.rs@@ -0,0 +1,18 @@+use crate::{sql_read_bytes::SqlReadBytes, time::Time, ColumnData};++pub(crate) async fn decode<R>(src: &mut R, len: usize) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let rlen = src.read_u8().await?;++ let time = match rlen {+ 0 => ColumnData::Time(None),+ _ => {+ let time = Time::decode(src, len, rlen as usize).await?;+ ColumnData::Time(Some(time))+ }+ };++ Ok(time)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/var_len.rs b/vendor/tiberius/src/tds/codec/column_data/var_len.rsnew file mode 100644index 0000000000..20f6a953a6--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/var_len.rs@@ -0,0 +1,48 @@+use crate::{sql_read_bytes::SqlReadBytes, tds::codec::VarLenContext, ColumnData, VarLenType};++pub(crate) async fn decode<R>(+ src: &mut R,+ ctx: &VarLenContext,+) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ use VarLenType::*;++ let ty = ctx.r#type();+ let len = ctx.len();+ let collation = ctx.collation();++ let res = match ty {+ Bitn => super::bit::decode(src).await?,+ Intn => super::int::decode(src, len).await?,+ Floatn => super::float::decode(src, len).await?,+ Guid => super::guid::decode(src).await?,+ BigChar | BigVarChar | NChar | NVarchar => {+ ColumnData::String(super::string::decode(src, ty, len, collation).await?)+ }+ Money => {+ let len = src.read_u8().await?;+ super::money::decode(src, len).await?+ }+ Datetimen => {+ let rlen = src.read_u8().await?;+ super::datetimen::decode(src, rlen, len as u8).await?+ }+ #[cfg(feature = "tds73")]+ Daten => super::date::decode(src).await?,+ #[cfg(feature = "tds73")]+ Timen => super::time::decode(src, len).await?,+ #[cfg(feature = "tds73")]+ Datetime2 => super::datetime2::decode(src, len).await?,+ #[cfg(feature = "tds73")]+ DatetimeOffsetn => super::datetimeoffsetn::decode(src, len).await?,+ BigBinary | BigVarBin => super::binary::decode(src, len).await?,+ Text => super::text::decode(src, collation).await?,+ NText => super::text::decode(src, None).await?,+ Image => super::image::decode(src).await?,+ t => unimplemented!("{:?}", t),+ };++ Ok(res)+}diff --git a/vendor/tiberius/src/tds/codec/column_data/xml.rs b/vendor/tiberius/src/tds/codec/column_data/xml.rsnew file mode 100644index 0000000000..34b191390f--- /dev/null+++ b/vendor/tiberius/src/tds/codec/column_data/xml.rs@@ -0,0 +1,30 @@+use std::{borrow::Cow, sync::Arc};++use crate::{+ sql_read_bytes::SqlReadBytes,+ xml::{XmlData, XmlSchema},+ ColumnData, VarLenType,+};++pub(crate) async fn decode<R>(+ src: &mut R,+ len: usize,+ schema: Option<Arc<XmlSchema>>,+) -> crate::Result<ColumnData<'static>>+where+ R: SqlReadBytes + Unpin,+{+ let xml = super::string::decode(src, VarLenType::Xml, len, None)+ .await?+ .map(|data| {+ let mut data = XmlData::new(data);++ if let Some(schema) = schema {+ data.set_schema(schema);+ }++ Cow::Owned(data)+ });++ Ok(ColumnData::Xml(xml))+}diff --git a/vendor/tiberius/src/tds/codec/decode.rs b/vendor/tiberius/src/tds/codec/decode.rsnew file mode 100644index 0000000000..d19fec0c90--- /dev/null+++ b/vendor/tiberius/src/tds/codec/decode.rs@@ -0,0 +1,64 @@+use super::{Packet, PacketCodec, PacketHeader, HEADER_BYTES};+use crate::Error;+use asynchronous_codec::Decoder;+use bytes::{Buf, BytesMut};+use tracing::{event, Level};++pub trait Decode<B: Buf> {+ fn decode(src: &mut B) -> crate::Result<Self>+ where+ Self: Sized;+}++impl Decoder for PacketCodec {+ type Item = Packet;+ type Error = Error;++ fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {+ if src.len() < HEADER_BYTES {+ src.reserve(HEADER_BYTES);+ return Ok(None);+ }++ let header = PacketHeader::decode(&mut BytesMut::from(&src[0..HEADER_BYTES]))?;+ let length = header.length() as usize;++ if src.len() < length {+ src.reserve(length);+ return Ok(None);+ }++ event!(+ Level::TRACE,+ "Reading a {:?} ({} bytes)",+ header.r#type(),+ length,+ );++ let header = PacketHeader::decode(src)?;++ if length < HEADER_BYTES {+ return Err(Error::Protocol("Invalid packet length".into()));+ }++ let payload = src.split_to(length - HEADER_BYTES);++ Ok(Some(Packet::new(header, payload)))+ }++ fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {+ match self.decode(buf)? {+ Some(frame) => Ok(Some(frame)),+ None => {+ if buf.is_empty() {+ Ok(None)+ } else {+ Err(+ std::io::Error::new(std::io::ErrorKind::Other, "bytes remaining on stream")+ .into(),+ )+ }+ }+ }+ }+}diff --git a/vendor/tiberius/src/tds/codec/encode.rs b/vendor/tiberius/src/tds/codec/encode.rsnew file mode 100644index 0000000000..7c76420f1f--- /dev/null+++ b/vendor/tiberius/src/tds/codec/encode.rs@@ -0,0 +1,17 @@+use super::{Packet, PacketCodec};+use asynchronous_codec::Encoder;+use bytes::{BufMut, BytesMut};++pub(crate) trait Encode<B: BufMut> {+ fn encode(self, dst: &mut B) -> crate::Result<()>;+}++impl Encoder for PacketCodec {+ type Item = Packet;+ type Error = crate::Error;++ fn encode(&mut self, item: Packet, dst: &mut BytesMut) -> Result<(), Self::Error> {+ item.encode(dst)?;+ Ok(())+ }+}diff --git a/vendor/tiberius/src/tds/codec/guid.rs b/vendor/tiberius/src/tds/codec/guid.rsnew file mode 100644index 0000000000..1298997ec9--- /dev/null+++ b/vendor/tiberius/src/tds/codec/guid.rs@@ -0,0 +1,10 @@+/// UUIDs use network byte order (big endian) for the first 3 groups,+/// while GUIDs use native byte order (little endian).+///+/// https://github.com/microsoft/mssql-jdbc/blob/bec39dbba9544aef5f5f6a5495d5acf533efd6da/src/main/java/com/microsoft/sqlserver/jdbc/Util.java#L708-L730+pub(crate) fn reorder_bytes(bytes: &mut uuid::Bytes) {+ bytes.swap(0, 3);+ bytes.swap(1, 2);+ bytes.swap(4, 5);+ bytes.swap(6, 7);+}diff --git a/vendor/tiberius/src/tds/codec/header.rs b/vendor/tiberius/src/tds/codec/header.rsnew file mode 100644index 0000000000..719fc158ba--- /dev/null+++ b/vendor/tiberius/src/tds/codec/header.rs@@ -0,0 +1,173 @@+use super::{Decode, Encode};+use crate::Error;+use bytes::{Buf, BufMut, BytesMut};+use std::convert::TryFrom;++uint_enum! {+ /// the type of the packet [2.2.3.1.1]#[repr(u32)]+ #[repr(u8)]+ pub enum PacketType {+ SQLBatch = 1,+ /// unused+ PreTDSv7Login = 2,+ Rpc = 3,+ TabularResult = 4,+ AttentionSignal = 6,+ BulkLoad = 7,+ /// Federated Authentication Token+ Fat = 8,+ TransactionManagerReq = 14,+ TDSv7Login = 16,+ Sspi = 17,+ PreLogin = 18,+ }+}++uint_enum! {+ /// the message state [2.2.3.1.2]+ #[repr(u8)]+ pub enum PacketStatus {+ NormalMessage = 0,+ EndOfMessage = 1,+ /// [client to server ONLY] (EndOfMessage also required)+ IgnoreEvent = 3,+ /// [client to server ONLY] [>= TDSv7.1]+ ResetConnection = 0x08,+ /// [client to server ONLY] [>= TDSv7.3]+ ResetConnectionSkipTran = 0x10,+ }+}++/// packet header consisting of 8 bytes [2.2.3.1]+#[derive(Debug, Clone, Copy)]+pub(crate) struct PacketHeader {+ ty: PacketType,+ status: PacketStatus,+ /// [BE] the length of the packet (including the 8 header bytes)+ /// must match the negotiated size sending from client to server [since TDSv7.3] after login+ /// (only if not EndOfMessage)+ length: u16,+ /// [BE] the process ID on the server, for debugging purposes only+ spid: u16,+ /// packet id+ id: u8,+ /// currently unused+ window: u8,+}++impl PacketHeader {+ pub fn new(length: usize, id: u8) -> PacketHeader {+ assert!(length <= u16::max_value() as usize);+ PacketHeader {+ ty: PacketType::TDSv7Login,+ status: PacketStatus::ResetConnection,+ length: length as u16,+ spid: 0,+ id,+ window: 0,+ }+ }++ pub fn rpc(id: u8) -> Self {+ Self {+ ty: PacketType::Rpc,+ status: PacketStatus::NormalMessage,+ ..Self::new(0, id)+ }+ }++ pub fn pre_login(id: u8) -> Self {+ Self {+ ty: PacketType::PreLogin,+ status: PacketStatus::EndOfMessage,+ ..Self::new(0, id)+ }+ }++ pub fn login(id: u8) -> Self {+ Self {+ ty: PacketType::TDSv7Login,+ status: PacketStatus::EndOfMessage,+ ..Self::new(0, id)+ }+ }++ pub fn batch(id: u8) -> Self {+ Self {+ ty: PacketType::SQLBatch,+ status: PacketStatus::NormalMessage,+ ..Self::new(0, id)+ }+ }++ pub fn bulk_load(id: u8) -> Self {+ Self {+ ty: PacketType::BulkLoad,+ status: PacketStatus::NormalMessage,+ ..Self::new(0, id)+ }+ }++ pub fn set_status(&mut self, status: PacketStatus) {+ self.status = status;+ }++ pub fn set_type(&mut self, ty: PacketType) {+ self.ty = ty;+ }++ pub fn status(&self) -> PacketStatus {+ self.status+ }++ pub fn r#type(&self) -> PacketType {+ self.ty+ }++ pub fn length(&self) -> u16 {+ self.length+ }+}++impl<B> Encode<B> for PacketHeader+where+ B: BufMut,+{+ fn encode(self, dst: &mut B) -> crate::Result<()> {+ dst.put_u8(self.ty as u8);+ dst.put_u8(self.status as u8);+ dst.put_u16(self.length);+ dst.put_u16(self.spid);+ dst.put_u8(self.id);+ dst.put_u8(self.window);++ Ok(())+ }+}++impl Decode<BytesMut> for PacketHeader {+ fn decode(src: &mut BytesMut) -> crate::Result<Self>+ where+ Self: Sized,+ {+ let raw_ty = src.get_u8();++ let ty = PacketType::try_from(raw_ty).map_err(|_| {+ Error::Protocol(format!("header: invalid packet type: {}", raw_ty).into())+ })?;++ let status = PacketStatus::try_from(src.get_u8())+ .map_err(|_| Error::Protocol("header: invalid packet status".into()))?;++ let header = PacketHeader {+ ty,+ status,+ length: src.get_u16(),+ spid: src.get_u16(),+ id: src.get_u8(),+ window: src.get_u8(),+ };++ Ok(header)+ }+}diff --git a/vendor/tiberius/src/tds/codec/iterator_ext.rs b/vendor/tiberius/src/tds/codec/iterator_ext.rsnew file mode 100644index 0000000000..aecdd6d5a7--- /dev/null+++ b/vendor/tiberius/src/tds/codec/iterator_ext.rs@@ -0,0 +1,27 @@+use std::fmt::{Display, Write};++pub(crate) trait IteratorJoin {+ fn join(self, sep: &str) -> String;+}++impl<T, I> IteratorJoin for T+where+ T: Iterator<Item = I>,+ I: Display,+{+ fn join(mut self, sep: &str) -> String {+ let (lower_bound, _) = self.size_hint();+ let mut out = String::with_capacity(sep.len() * lower_bound);++ if let Some(first_item) = self.next() {+ write!(out, "{}", first_item).unwrap();+ }++ for item in self {+ out.push_str(sep);+ write!(out, "{}", item).unwrap();+ }++ out+ }+}diff --git a/vendor/tiberius/src/tds/codec/login.rs b/vendor/tiberius/src/tds/codec/login.rsnew file mode 100644index 0000000000..265db381ed--- /dev/null+++ b/vendor/tiberius/src/tds/codec/login.rs@@ -0,0 +1,613 @@+use super::Encode;+use byteorder::{LittleEndian, WriteBytesExt};+use bytes::BytesMut;+use enumflags2::{bitflags, BitFlags};+use io::{Cursor, Write};+use std::fmt::Debug;+use std::{borrow::Cow, io};++uint_enum! {+ #[repr(u32)]+ #[derive(PartialOrd)]+ pub enum FeatureLevel {+ SqlServerV7 = 0x70000000,+ SqlServer2000 = 0x71000000,+ SqlServer2000Sp1 = 0x71000001,+ SqlServer2005 = 0x72090002,+ SqlServer2008 = 0x730A0003,+ SqlServer2008R2 = 0x730B0003,+ /// 2012, 2014, 2016+ SqlServerN = 0x74000004,+ }+}++impl Default for FeatureLevel {+ fn default() -> Self {+ Self::SqlServerN+ }+}++impl FeatureLevel {+ pub fn done_row_count_bytes(self) -> u8 {+ if self as u32 >= FeatureLevel::SqlServer2005 as u32 {+ 8+ } else {+ 4+ }+ }+}++#[bitflags]+#[repr(u8)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OptionFlag1 {+ /// The byte order used by client for numeric and datetime data types.+ /// (default: little-endian)+ BigEndian = 1 << 0,+ /// The character set used on the client. (default: ASCII)+ CharsetEBDDIC = 1 << 1,+ /// Use VAX floating point representation. (default: IEEE 754)+ FloatVax = 1 << 2,+ /// Use ND5000 floating point representation. (default: IEEE 754)+ FloatND5000 = 1 << 3,+ /// Set is dump/load or BCP capabilities are needed by the client.+ /// (default: ON)+ BcpDumploadOff = 1 << 4,+ /// Set if the client requires warning messages on execution of the USE SQL+ /// statement. If this flag is not set, the server MUST NOT inform the+ /// client when the database changes, and therefore the client will be+ /// unaware of any accompanying collation changes. (default: ON)+ UseDbNotify = 1 << 5,+ /// Set if the change to initial database needs to succeed if the connection+ /// is to succeed. (default: OFF)+ InitDbFatal = 1 << 6,+ /// Set if the client requires warning messages on execution of a language+ /// change statement. (default: OFF)+ LangChangeWarn = 1 << 7,+}++#[bitflags]+#[repr(u8)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OptionFlag2 {+ /// Set if the change to initial language needs to succeed if the connect is+ /// to succeed.+ InitLangFatal = 1 << 0,+ /// Set if the client is the ODBC driver. This causes the server to set+ /// `ANSI_DEFAULTS=ON`, `CURSOR_CLOSE_ON_COMMIT`, `IMPLICIT_TRANSACTIONS=OFF`,+ /// `TEXTSIZE=0x7FFFFFFF` (2GB) (TDS 7.2 and earlier) `TEXTSIZE` to infinite+ /// (TDS 7.3), and `ROWCOUNT` to infinite.+ OdbcDriver = 1 << 1,+ /// (not documented)+ TransBoundary = 1 << 2,+ /// (not documented)+ CacheConnect = 1 << 3,+ /// Reserved (not really documented)+ UserTypeServer = 1 << 4,+ /// Distributed Query login+ UserTypeRemUser = 1 << 5,+ /// Replication login+ UserTypeSqlRepl = 1 << 6,+ /// Use integrated security in the client.+ IntegratedSecurity = 1 << 7,+}++#[bitflags]+#[repr(u8)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OptionFlag3 {+ /// Request to change login's password.+ RequestChangePassword = 1 << 0,+ /// XML data type instances are returned as binary XML.+ BinaryXML = 1 << 1,+ /// Client is requesting separate process to be spawned as user instance.+ SpawnUserInstance = 1 << 2,+ /// This bit is used by the server to determine if a client is able to+ /// properly handle collations introduced after TDS 7.2. TDS 7.2 and earlier+ /// clients are encouraged to use this loginpacket bit. Servers MUST ignore+ /// this bit when it is sent by TDS 7.3 or 7.4 clients.+ UnknownCollationHandling = 1 << 3,+ /// ibExtension/cbExtension fields are used.+ ExtensionUsed = 1 << 4,+}++#[bitflags]+#[repr(u8)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum LoginTypeFlag {+ /// Use T-SQL syntax.+ UseTSQL = 1 << 0,+ /// Set if the client is the OLEDB driver. This causes the server to set+ /// ANSI_DEFAULTS to ON, CURSOR_CLOSE_ON_COMMIT and IMPLICIT_TRANSACTIONS to+ /// OFF, TEXTSIZE to 0x7FFFFFFF (2GB) (TDS 7.2 and earlier), TEXTSIZE to+ /// infinite (introduced in TDS 7.3), and ROWCOUNT to infinite.+ UseOLEDB = 1 << 4,+ /// This bit was introduced in TDS 7.4; however, TDS 7.1, 7.2, and 7.3+ /// clients can also use this bit in LOGIN7 to specify that the application+ /// intent of the connection is read-only. The server SHOULD ignore this bit+ /// if the highest TDS version supported by the server is lower than TDS 7.4.+ ReadOnlyIntent = 1 << 5,+}++pub(crate) const FEA_EXT_FEDAUTH: u8 = 0x02u8;+pub(crate) const FEA_EXT_TERMINATOR: u8 = 0xFFu8;+pub(crate) const FED_AUTH_LIBRARYSECURITYTOKEN: u8 = 0x01;++/// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/773a62b6-ee89-4c02-9e5e-344882630aac+#[derive(Debug, Clone, Default)]+#[cfg_attr(test, derive(PartialEq, Eq))]+struct FedAuthExt<'a> {+ fed_auth_echo: bool,+ fed_auth_token: Cow<'a, str>,+ nonce: Option<[u8; 32]>,+}++/// the login packet+#[derive(Debug, Clone, Default)]+#[cfg_attr(test, derive(PartialEq, Eq))]+pub struct LoginMessage<'a> {+ /// the highest TDS version the client supports+ tds_version: FeatureLevel,+ /// the requested packet size+ packet_size: u32,+ /// the version of the interface library+ client_prog_ver: u32,+ /// the process id of the client application+ client_pid: u32,+ /// the connection id of the primary server+ /// (used when connecting to an "Always UP" backup server)+ connection_id: u32,+ option_flags_1: BitFlags<OptionFlag1>,+ option_flags_2: BitFlags<OptionFlag2>,+ /// flag included in option_flags_2+ integrated_security: Option<Vec<u8>>,+ type_flags: BitFlags<LoginTypeFlag>,+ option_flags_3: BitFlags<OptionFlag3>,+ client_timezone: i32,+ client_lcid: u32,+ hostname: Cow<'a, str>,+ username: Cow<'a, str>,+ password: Cow<'a, str>,+ app_name: Cow<'a, str>,+ server_name: Cow<'a, str>,+ /// the default database to connect to+ db_name: Cow<'a, str>,+ fed_auth_ext: Option<FedAuthExt<'a>>,+}++impl<'a> LoginMessage<'a> {+ pub fn new() -> LoginMessage<'a> {+ Self {+ packet_size: 4096,+ option_flags_1: OptionFlag1::UseDbNotify | OptionFlag1::InitDbFatal,+ option_flags_2: OptionFlag2::InitLangFatal | OptionFlag2::OdbcDriver,+ option_flags_3: BitFlags::from_flag(OptionFlag3::UnknownCollationHandling),+ app_name: "tiberius".into(),+ ..Default::default()+ }+ }++ #[cfg(any(all(unix, feature = "integrated-auth-gssapi"), windows))]+ pub fn integrated_security(&mut self, bytes: Option<Vec<u8>>) {+ if bytes.is_some() {+ self.option_flags_2.insert(OptionFlag2::IntegratedSecurity);+ } else {+ self.option_flags_2.remove(OptionFlag2::IntegratedSecurity);+ }++ self.integrated_security = bytes;+ }++ pub fn app_name(&mut self, name: impl Into<Cow<'a, str>>) {+ self.app_name = name.into();+ }++ pub fn db_name(&mut self, db_name: impl Into<Cow<'a, str>>) {+ self.db_name = db_name.into();+ }++ pub fn server_name(&mut self, server_name: impl Into<Cow<'a, str>>) {+ self.server_name = server_name.into();+ }++ pub fn user_name(&mut self, user_name: impl Into<Cow<'a, str>>) {+ self.username = user_name.into();+ }++ pub fn password(&mut self, password: impl Into<Cow<'a, str>>) {+ self.password = password.into();+ }++ pub fn aad_token(+ &mut self,+ token: impl Into<Cow<'a, str>>,+ fed_auth_echo: bool,+ nonce: Option<[u8; 32]>,+ ) {+ self.option_flags_3.insert(OptionFlag3::ExtensionUsed);++ self.fed_auth_ext = Some(FedAuthExt {+ fed_auth_echo,+ fed_auth_token: token.into(),+ nonce,+ })+ }++ pub fn readonly(&mut self, readonly: bool) {+ if readonly {+ self.type_flags.insert(LoginTypeFlag::ReadOnlyIntent);+ } else {+ self.type_flags.remove(LoginTypeFlag::ReadOnlyIntent);+ }+ }+}++impl<'a> Encode<BytesMut> for LoginMessage<'a> {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ let mut cursor = Cursor::new(Vec::with_capacity(512));++ // Space for the length+ cursor.write_u32::<LittleEndian>(0)?;++ cursor.write_u32::<LittleEndian>(self.tds_version as u32)?;+ cursor.write_u32::<LittleEndian>(self.packet_size)?;+ cursor.write_u32::<LittleEndian>(self.client_prog_ver)?;+ cursor.write_u32::<LittleEndian>(self.client_pid)?;+ cursor.write_u32::<LittleEndian>(self.connection_id)?;++ cursor.write_u8(self.option_flags_1.bits())?;+ cursor.write_u8(self.option_flags_2.bits())?;+ cursor.write_u8(self.type_flags.bits())?;+ cursor.write_u8(self.option_flags_3.bits())?;++ cursor.write_u32::<LittleEndian>(self.client_timezone as u32)?;+ cursor.write_u32::<LittleEndian>(self.client_lcid)?;++ // variable length data (OffsetLength)+ let var_data = [+ &self.hostname,+ &self.username,+ &self.password,+ &self.app_name,+ &self.server_name,+ &"".into(), // 5. ibExtension+ &"".into(), // ibCltIntName+ &"".into(), // ibLanguage+ &self.db_name,+ &"".into(), // 9. ClientId (6 bytes); this is included in var_data so we don't lack the bytes of cbSspiLong (4=2*2) and can insert it at the correct position+ &"".into(), // 10. ibSSPI+ &"".into(), // ibAtchDBFile+ &"".into(), // ibChangePassword+ ];++ let mut data_offset = cursor.position() as usize + var_data.len() * 2 * 2 + 6;+ let mut fea_ext_offset = 0;++ for (i, value) in var_data.iter().enumerate() {+ if i == 5 {+ // we might need to update the feature ext potion later+ fea_ext_offset = cursor.position();+ }++ // write the client ID (created from the MAC address)+ if i == 9 {+ cursor.write_u32::<LittleEndian>(0)?; //TODO:+ cursor.write_u16::<LittleEndian>(42)?; //TODO: generate real client id+ continue;+ }++ cursor.write_u16::<LittleEndian>(data_offset as u16)?;++ // ibSSPI+ if i == 10 {+ let length = if let Some(ref bytes) = self.integrated_security {+ let bak = cursor.position();++ cursor.set_position(data_offset as u64);+ cursor.write_all(bytes)?;++ data_offset += bytes.len();+ cursor.set_position(bak);++ bytes.len()+ } else {+ 0+ };++ cursor.write_u16::<LittleEndian>(length as u16)?;++ continue;+ }++ // jump into the data portion of the output+ let bak = cursor.position();+ cursor.set_position(data_offset as u64);++ for codepoint in value.encode_utf16() {+ cursor.write_u16::<LittleEndian>(codepoint)?;+ }++ let new_position = cursor.position() as usize;++ // prepare the password in MS-fashion+ if i == 2 {+ let buffer = cursor.get_mut();+ for byte in buffer.iter_mut().take(new_position).skip(data_offset) {+ *byte = ((*byte << 4) & 0xf0 | (*byte >> 4) & 0x0f) ^ 0xA5;+ }+ }++ let length = new_position - data_offset;+ cursor.set_position(bak);+ data_offset += length;++ // microsoft being really consistent here... using byte offsets with utf16-length's+ // sounds like premature optimization+ cursor.write_u16::<LittleEndian>(length as u16 / 2)?;+ }++ // cbSSPILong+ cursor.write_u32::<LittleEndian>(0)?;++ // FeatureExt+ if let Some(fed_auth_ext) = self.fed_auth_ext {+ // update fea_ext_offset+ cursor.set_position(fea_ext_offset);+ cursor.write_u16::<LittleEndian>(data_offset as u16)?;+ cursor.write_u16::<LittleEndian>(4)?;++ cursor.set_position(data_offset as u64);+ data_offset += 4;+ cursor.write_u32::<LittleEndian>(data_offset as u32)?;++ cursor.write_u8(FEA_EXT_FEDAUTH)?;++ let mut token = Cursor::new(Vec::new());+ for codepoint in fed_auth_ext.fed_auth_token.encode_utf16() {+ token.write_u16::<LittleEndian>(codepoint)?;+ }+ let token = token.into_inner();++ // options (1) + TokenLength(4) + Token.length + nonce.length+ let feature_ext_length =+ 1 + 4 + token.len() + if fed_auth_ext.nonce.is_some() { 32 } else { 0 };++ cursor.write_u32::<LittleEndian>(feature_ext_length as u32)?;++ let mut options: u8 = FED_AUTH_LIBRARYSECURITYTOKEN << 1;+ if fed_auth_ext.fed_auth_echo {+ options |= 1 // fFedAuthEcho+ }++ cursor.write_u8(options)?;++ cursor.write_u32::<LittleEndian>(token.len() as u32)?;+ cursor.write_all(token.as_slice())?;++ if let Some(nonce) = fed_auth_ext.nonce {+ cursor.write_all(nonce.as_ref())?;+ }++ cursor.write_u8(FEA_EXT_TERMINATOR)?;+ }++ cursor.set_position(0);+ cursor.write_u32::<LittleEndian>(cursor.get_ref().len() as u32)?;++ dst.extend(cursor.into_inner());++ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::Decode;+ use byteorder::ReadBytesExt;+ use bytes::BytesMut;+ use std::io::Read;++ impl<'a> Decode<BytesMut> for LoginMessage<'a> {+ fn decode(src: &mut BytesMut) -> crate::Result<Self>+ where+ Self: Sized,+ {+ let mut cursor = Cursor::new(src);+ let mut ret = LoginMessage::new();++ let total_length = cursor.read_u32::<LittleEndian>()?;++ ret.tds_version = cursor+ .read_u32::<LittleEndian>()?+ .try_into()+ .expect("tds_version verification");+ ret.packet_size = cursor.read_u32::<LittleEndian>()?;+ ret.client_prog_ver = cursor.read_u32::<LittleEndian>()?;+ ret.client_pid = cursor.read_u32::<LittleEndian>()?;+ ret.connection_id = cursor.read_u32::<LittleEndian>()?;++ ret.option_flags_1 =+ BitFlags::from_bits(cursor.read_u8()?).expect("option_flags_1 verification");+ ret.option_flags_2 =+ BitFlags::from_bits(cursor.read_u8()?).expect("option_flags_2 verification");+ ret.type_flags =+ BitFlags::from_bits(cursor.read_u8()?).expect("type_flags verification");+ ret.option_flags_3 =+ BitFlags::from_bits(cursor.read_u8()?).expect("option_flags_3 verification");++ ret.client_timezone = cursor.read_u32::<LittleEndian>()? as i32;+ ret.client_lcid = cursor.read_u32::<LittleEndian>()?;++ macro_rules! read_offset_length_bytes {+ () => {{+ let offset = cursor.read_u16::<LittleEndian>()?;+ let length = cursor.read_u16::<LittleEndian>()?;+ let pos = cursor.position();+ cursor.set_position(offset as u64);++ let mut values = vec![0u8; length as usize];+ cursor.read_exact(&mut values)?;++ cursor.set_position(pos);+ values+ }};+ }++ macro_rules! read_offset_length_string {+ () => {+ read_offset_length_string!("")+ };+ ($tag:expr) => {{+ let offset = cursor.read_u16::<LittleEndian>()?;+ let length = cursor.read_u16::<LittleEndian>()?;+ let pos = cursor.position();+ cursor.set_position(offset as u64);++ if $tag == "password" {+ let buffer = cursor.get_mut();+ for byte in buffer+ .iter_mut()+ .skip(offset as usize)+ .take(length as usize * 2)+ {+ *byte ^= 0xA5;+ *byte = ((*byte << 4) & 0xf0 | (*byte >> 4) & 0x0f);+ }+ }++ let mut values = vec![0u16; length as usize];+ cursor.read_u16_into::<LittleEndian>(&mut values)?;+ cursor.set_position(pos);++ String::from_utf16(&values).expect("decode utf16")+ }};+ }++ ret.hostname = read_offset_length_string!().into();+ ret.username = read_offset_length_string!().into();+ ret.password = read_offset_length_string!("password").into();+ ret.app_name = read_offset_length_string!().into();+ ret.server_name = read_offset_length_string!().into();+ let fea_ext_offset = read_offset_length_bytes!(); // 5. ibExtension+ let fea_ext_offset = if fea_ext_offset.len() == 4 {+ u32::from_le_bytes(fea_ext_offset.try_into().unwrap())+ } else {+ 0+ };+ let _ = read_offset_length_string!(); // ibCltIntName+ let _ = read_offset_length_string!(); // ibLanguage+ ret.db_name = read_offset_length_string!().into();+ // 9. ClientId (6 bytes); this is included in var_data so we don't lack the bytes of cbSspiLong (4=2*2) and can insert it at the correct position+ let _ = cursor.read_u32::<LittleEndian>()?;+ let _ = cursor.read_u16::<LittleEndian>()?;+ let is = read_offset_length_bytes!();+ ret.integrated_security = if is.is_empty() { None } else { Some(is) };+ let _ = read_offset_length_string!(); // ibAtchDBFile+ let _ = read_offset_length_string!(); // ibChangePassword+ // let _ = cursor.read_u32::<LittleEndian>()?;+ // cbSSPILong++ if fea_ext_offset != 0 {+ cursor.set_position((fea_ext_offset) as u64);++ assert!(ret.option_flags_3.contains(OptionFlag3::ExtensionUsed));+ loop {+ let fe = cursor.read_u8()?;+ if fe == FEA_EXT_TERMINATOR {+ break;+ } else if fe == FEA_EXT_FEDAUTH {+ let fea_ext_len = cursor.read_u32::<LittleEndian>()?;+ let pos = cursor.position();+ let mut options = cursor.read_u8()?;+ let fed_auth_echo = (options & 1) == 1;+ options >>= 1;+ if options != FED_AUTH_LIBRARYSECURITYTOKEN {+ unimplemented!("unsupported FedAuthLibrary {:?}", options);+ }+ let token_len = cursor.read_u32::<LittleEndian>()? as usize;+ let mut token = vec![0u16; token_len / 2];+ cursor.read_u16_into::<LittleEndian>(&mut token)?;+ let token = String::from_utf16(&token).expect("decode utf16");+ let remaining = fea_ext_len - (cursor.position() - pos) as u32;+ let nonce = if remaining == 32 {+ let mut a = [0u8; 32];+ cursor.read_exact(&mut a)?;+ Some(a)+ } else if remaining == 0 {+ None+ } else {+ panic!("read feature ext fail: {}", remaining);+ };++ let fed_auth_ext = FedAuthExt {+ fed_auth_echo,+ fed_auth_token: token.into(),+ nonce,+ };+ ret.fed_auth_ext = Some(fed_auth_ext);+ } else {+ unimplemented!("unsupported feature ext {:?}", fe);+ }+ }+ }++ assert!(cursor.position() <= total_length as u64);++ Ok(ret)+ }+ }++ #[test]+ fn login_message_round_trip() {+ let mut payload = BytesMut::new();+ let mut login = LoginMessage::new();+ login.db_name("fake-database-name");+ login.app_name("fake-app-name");+ login.server_name("fake-server-name");+ login.user_name("fake-user-name");+ login.password("fake-pw");+ login+ .clone()+ .encode(&mut payload)+ .expect("encode should succeed");++ let decoded = LoginMessage::decode(&mut payload).expect("decode should succeed");++ assert_eq!(login, decoded);+ }++ #[test]+ fn specify_aad_token() {+ let mut login = LoginMessage::new();+ let token = "fake-aad-token";+ let nonce = [3u8; 32];+ login.aad_token(token, true, Some(nonce));++ assert!(login.option_flags_3.contains(OptionFlag3::ExtensionUsed));+ assert_eq!(+ login.fed_auth_ext.expect("fed_auto_specified"),+ FedAuthExt {+ fed_auth_echo: true,+ fed_auth_token: token.into(),+ nonce: Some(nonce)+ }+ )+ }++ #[test]+ fn login_message_with_fed_auth_round_trip() {+ let mut payload = BytesMut::new();+ let mut login = LoginMessage::new();+ let nonce = [1u8; 32];+ login.aad_token("fake-aad-token", true, Some(nonce));+ login+ .clone()+ .encode(&mut payload)+ .expect("encode should succeed");++ let decoded = LoginMessage::decode(&mut payload).expect("decode should succeed");++ assert_eq!(login, decoded);+ }+}diff --git a/vendor/tiberius/src/tds/codec/packet.rs b/vendor/tiberius/src/tds/codec/packet.rsnew file mode 100644index 0000000000..9927ed35d9--- /dev/null+++ b/vendor/tiberius/src/tds/codec/packet.rs@@ -0,0 +1,57 @@+use super::{Decode, Encode, PacketHeader, PacketStatus, HEADER_BYTES};+use bytes::BytesMut;++#[derive(Debug)]+pub struct Packet {+ pub(crate) header: PacketHeader,+ pub(crate) payload: BytesMut,+}++impl Packet {+ pub(crate) fn new(header: PacketHeader, payload: BytesMut) -> Self {+ Self { header, payload }+ }++ pub(crate) fn is_last(&self) -> bool {+ self.header.status() == PacketStatus::EndOfMessage+ }++ pub(crate) fn into_parts(self) -> (PacketHeader, BytesMut) {+ (self.header, self.payload)+ }+}++impl Encode<BytesMut> for Packet {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ let size = (self.payload.len() as u16 + HEADER_BYTES as u16).to_be_bytes();++ self.header.encode(dst)?;+ dst.extend(self.payload);++ dst[2] = size[0];+ dst[3] = size[1];++ Ok(())+ }+}++impl Decode<BytesMut> for Packet {+ fn decode(src: &mut BytesMut) -> crate::Result<Self> {+ Ok(Self {+ header: PacketHeader::decode(src)?,+ payload: src.split(),+ })+ }+}++impl Extend<u8> for Packet {+ fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {+ self.payload.extend(iter)+ }+}++impl<'a> Extend<&'a u8> for Packet {+ fn extend<T: IntoIterator<Item = &'a u8>>(&mut self, iter: T) {+ self.payload.extend(iter)+ }+}diff --git a/vendor/tiberius/src/tds/codec/pre_login.rs b/vendor/tiberius/src/tds/codec/pre_login.rsnew file mode 100644index 0000000000..eb4c27e605--- /dev/null+++ b/vendor/tiberius/src/tds/codec/pre_login.rs@@ -0,0 +1,285 @@+use super::guid::reorder_bytes;+use super::{Decode, Encode};+use crate::{tds, Error, Result};+use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt};+use bytes::{BufMut, BytesMut};+use std::convert::TryFrom;+use std::io::{Cursor, Read};+use tds::EncryptionLevel;+use uuid::Uuid;++/// Client application activity id token used for debugging purposes introduced+/// in TDS 7.4.+#[allow(unused)]+#[derive(Debug, Clone)]+#[cfg_attr(test, derive(PartialEq))]+pub struct ActivityId {+ id: Uuid,+ sequence: u32,+}++/// The prelogin packet used to initialize a connection+#[derive(Debug, Clone)]+#[cfg_attr(test, derive(PartialEq))]+pub struct PreloginMessage {+ /// [BE] token=0x00+ /// Either the driver version or the version of the SQL server+ pub version: u32,+ pub sub_build: u16,+ /// token=0x01+ pub encryption: EncryptionLevel,+ /// token=0x02+ pub instance_name: Option<String>,+ /// [client] threadid for debugging purposes, token=0x03+ pub thread_id: u32,+ /// token=0x04+ pub mars: bool,+ /// token=0x05+ pub activity_id: Option<ActivityId>,+ /// token=0x06+ pub fed_auth_required: bool,+ pub nonce: Option<[u8; 32]>,+}++impl PreloginMessage {+ pub fn new() -> PreloginMessage {+ let driver_version = crate::get_driver_version();+ PreloginMessage {+ version: driver_version as u32,+ sub_build: (driver_version >> 32) as u16,+ encryption: EncryptionLevel::NotSupported,+ instance_name: None,+ thread_id: 0,+ mars: false,+ activity_id: None,+ fed_auth_required: false,+ nonce: None,+ }+ }++ #[cfg(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ ))]+ pub fn negotiated_encryption(&self, expected: EncryptionLevel) -> EncryptionLevel {+ match (expected, self.encryption) {+ (EncryptionLevel::NotSupported, EncryptionLevel::NotSupported) => {+ EncryptionLevel::NotSupported+ }+ (EncryptionLevel::Off, EncryptionLevel::Off) => EncryptionLevel::Off,+ (EncryptionLevel::On, EncryptionLevel::Off)+ | (EncryptionLevel::On, EncryptionLevel::NotSupported) => {+ panic!("Server does not allow the requested encryption level.")+ }+ (_, _) => EncryptionLevel::On,+ }+ }++ #[cfg(not(any(+ feature = "rustls",+ feature = "native-tls",+ feature = "vendored-openssl"+ )))]+ pub fn negotiated_encryption(&self, _: EncryptionLevel) -> EncryptionLevel {+ EncryptionLevel::NotSupported+ }+}++// prelogin fields+// http://msdn.microsoft.com/en-us/library/dd357559.aspx+const PRELOGIN_VERSION: u8 = 0;+const PRELOGIN_ENCRYPTION: u8 = 1;+const PRELOGIN_INSTOPT: u8 = 2;+const PRELOGIN_THREADID: u8 = 3;+const PRELOGIN_MARS: u8 = 4;+const PRELOGIN_TRACEID: u8 = 5;+const PRELOGIN_FEDAUTHREQUIRED: u8 = 6;+const PRELOGIN_NONCEOPT: u8 = 7;+const PRELOGIN_TERMINATOR: u8 = 0xff;++impl Encode<BytesMut> for PreloginMessage {+ fn encode(self, dst: &mut BytesMut) -> Result<()> {+ let mut fields = Vec::new();+ let mut data_cursor = Cursor::new(Vec::with_capacity(512));++ // version+ fields.push((PRELOGIN_VERSION, 0x04 + 0x02)); // version + subbuild+ data_cursor.write_u32::<BigEndian>(self.version)?;+ data_cursor.write_u16::<BigEndian>(self.sub_build)?;++ // encryption+ fields.push((PRELOGIN_ENCRYPTION, 0x01)); // encryption+ data_cursor.write_u8(self.encryption as u8)?;++ // threadid+ fields.push((PRELOGIN_THREADID, 0x04)); // thread id+ data_cursor.write_u32::<BigEndian>(self.thread_id)?;++ // MARS+ fields.push((PRELOGIN_MARS, 0x01)); // MARS+ data_cursor.write_u8(self.mars as u8)?;++ // fed auth+ if self.fed_auth_required {+ fields.push((PRELOGIN_FEDAUTHREQUIRED, 0x01));+ data_cursor.write_u8(0x01)?;+ }++ // build the packet-body+ // offset = PL_OPTION_TOKEN + PL_OFFSET + PL_OPTION_LENGTH = 5 bytes + the terminator (0xFF)+ let mut data_offset = (fields.len() * 5 + 1) as u16;++ // write the offset table+ for (token, length) in fields {+ dst.put_u8(token);+ dst.put_u16(data_offset);+ dst.put_u16(length);++ data_offset += length;+ }++ dst.put_u8(PRELOGIN_TERMINATOR);+ dst.extend(data_cursor.into_inner());++ Ok(())+ }+}++impl Decode<BytesMut> for PreloginMessage {+ fn decode(src: &mut BytesMut) -> Result<Self>+ where+ Self: Sized,+ {+ let mut cursor = Cursor::new(src);+ let mut ret = PreloginMessage::new();++ // read all options+ loop {+ let token = cursor.read_u8()?;++ // read until terminator+ if token == 0xff {+ break;+ }++ let offset = cursor.read_u16::<BigEndian>()?;+ let length = cursor.read_u16::<BigEndian>()?;+ let old_pos = cursor.position();++ cursor.set_position(offset as u64);++ // verify whether the server acts in accordance to what we requested+ // and if we can handle on what we seemingly agreed to+ // TODO: support parsing more+ match token {+ // version+ PRELOGIN_VERSION => {+ ret.version = cursor.read_u32::<BigEndian>()?;+ ret.sub_build = cursor.read_u16::<BigEndian>()?;+ }+ // encryption+ PRELOGIN_ENCRYPTION => {+ let encrypt = cursor.read_u8()?;+ ret.encryption = tds::EncryptionLevel::try_from(encrypt).map_err(|_| {+ Error::Protocol(format!("invalid encryption value: {}", encrypt).into())+ })?;+ }+ // instance name+ PRELOGIN_INSTOPT => {+ let mut bytes = Vec::new();+ let mut next_byte = cursor.read_u8()?;++ while next_byte != 0x00 {+ bytes.push(next_byte);+ next_byte = cursor.read_u8()?;+ }++ if !bytes.is_empty() {+ ret.instance_name = Some(String::from_utf8_lossy(&bytes).into_owned());+ }+ }+ PRELOGIN_THREADID => {+ ret.thread_id = if length == 0 {+ 0+ } else if length == 4 {+ cursor.read_u32::<BigEndian>()?+ } else {+ panic!("should never happen")+ }+ }+ // mars+ PRELOGIN_MARS => {+ ret.mars = cursor.read_u8()? != 0;+ }+ // activity id+ PRELOGIN_TRACEID => {+ // Data is a Guid, 16 bytes and ordered the wrong way around+ // than Uuid.+ let mut data = [0u8; 16];++ cursor.read_exact(&mut data)?;+ reorder_bytes(&mut data);++ ret.activity_id = Some(ActivityId {+ id: Uuid::from_bytes(data),+ sequence: cursor.read_u32::<LittleEndian>()?,+ });+ }+ // fed auth+ PRELOGIN_FEDAUTHREQUIRED => {+ ret.fed_auth_required = cursor.read_u8()? != 0;+ }+ // nonce+ PRELOGIN_NONCEOPT => {+ let mut data = [0u8; 32];++ for item in data.iter_mut() {+ *item = cursor.read_u8()?;+ }++ ret.nonce = Some(data);+ }+ _ => panic!("unsupported prelogin token: {}", token),+ }++ cursor.set_position(old_pos);+ }++ Ok(ret)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn prelogin_roundtrip() {+ let mut payload = BytesMut::new();+ let prelogin = PreloginMessage::new();+ prelogin+ .clone()+ .encode(&mut payload)+ .expect("encode should succeed");++ let decoded = PreloginMessage::decode(&mut payload).expect("decode should succeed");++ assert_eq!(prelogin, decoded);+ }++ #[test]+ fn prelogin_with_fedauth_roundtrip() {+ let mut payload = BytesMut::new();+ let mut prelogin = PreloginMessage::new();+ prelogin.fed_auth_required = true;+ prelogin+ .clone()+ .encode(&mut payload)+ .expect("encode should succeed");++ let decoded = PreloginMessage::decode(&mut payload).expect("decode should succeed");++ assert_eq!(prelogin, decoded);+ }+}diff --git a/vendor/tiberius/src/tds/codec/rpc_request.rs b/vendor/tiberius/src/tds/codec/rpc_request.rsnew file mode 100644index 0000000000..368cbd3c80--- /dev/null+++ b/vendor/tiberius/src/tds/codec/rpc_request.rs@@ -0,0 +1,145 @@+use super::{AllHeaderTy, Encode, ALL_HEADERS_LEN_TX};+use crate::{tds::codec::ColumnData, BytesMutWithTypeInfo, Result};+use bytes::{BufMut, BytesMut};+use enumflags2::{bitflags, BitFlags};+use std::borrow::BorrowMut;+use std::borrow::Cow;++#[bitflags]+#[repr(u8)]+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum RpcStatus {+ ByRefValue = 1 << 0,+ DefaultValue = 1 << 1,+ // reserved+ Encrypted = 1 << 3,+}++#[bitflags]+#[repr(u16)]+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum RpcOption {+ WithRecomp = 1 << 0,+ NoMeta = 1 << 1,+ ReuseMeta = 1 << 2,+}++#[derive(Debug)]+pub struct TokenRpcRequest<'a> {+ proc_id: RpcProcIdValue<'a>,+ flags: BitFlags<RpcOption>,+ params: Vec<RpcParam<'a>>,+ transaction_desc: [u8; 8],+}++impl<'a> TokenRpcRequest<'a> {+ pub fn new<I>(proc_id: I, params: Vec<RpcParam<'a>>, transaction_desc: [u8; 8]) -> Self+ where+ I: Into<RpcProcIdValue<'a>>,+ {+ Self {+ proc_id: proc_id.into(),+ flags: BitFlags::empty(),+ params,+ transaction_desc,+ }+ }+}++#[derive(Debug)]+pub struct RpcParam<'a> {+ pub name: Cow<'a, str>,+ pub flags: BitFlags<RpcStatus>,+ pub value: ColumnData<'a>,+}++/// 2.2.6.6 RPC Request+#[allow(dead_code)]+#[repr(u8)]+#[derive(Clone, Copy, Debug)]+pub enum RpcProcId {+ CursorOpen = 2,+ CursorFetch = 7,+ CursorClose = 9,+ ExecuteSQL = 10,+ Prepare = 11,+ Execute = 12,+ PrepExec = 13,+ Unprepare = 15,+}++#[derive(Debug)]+#[allow(dead_code)]+pub enum RpcProcIdValue<'a> {+ Name(Cow<'a, str>),+ Id(RpcProcId),+}++impl<'a, S> From<S> for RpcProcIdValue<'a>+where+ S: Into<Cow<'a, str>>,+{+ fn from(s: S) -> Self {+ Self::Name(s.into())+ }+}++impl<'a> From<RpcProcId> for RpcProcIdValue<'a> {+ fn from(id: RpcProcId) -> Self {+ Self::Id(id)+ }+}++impl<'a> Encode<BytesMut> for TokenRpcRequest<'a> {+ fn encode(self, dst: &mut BytesMut) -> Result<()> {+ dst.put_u32_le(ALL_HEADERS_LEN_TX as u32);+ dst.put_u32_le(ALL_HEADERS_LEN_TX as u32 - 4);+ dst.put_u16_le(AllHeaderTy::TransactionDescriptor as u16);+ dst.put_slice(&self.transaction_desc);+ dst.put_u32_le(1);++ match self.proc_id {+ RpcProcIdValue::Id(ref id) => {+ let val = (0xffff_u32) | ((*id as u16) as u32) << 16;+ dst.put_u32_le(val);+ }+ RpcProcIdValue::Name(ref _name) => {+ //let (left_bytes, _) = try!(write_varchar::<u16>(&mut cursor, name, 0));+ //assert_eq!(left_bytes, 0);+ todo!()+ }+ }++ dst.put_u16_le(self.flags.bits());++ for param in self.params.into_iter() {+ param.encode(dst)?;+ }++ Ok(())+ }+}++impl<'a> Encode<BytesMut> for RpcParam<'a> {+ fn encode(self, dst: &mut BytesMut) -> Result<()> {+ let len_pos = dst.len();+ let mut length = 0u8;++ dst.put_u8(length);++ for codepoint in self.name.encode_utf16() {+ length += 1;+ dst.put_u16_le(codepoint);+ }++ dst.put_u8(self.flags.bits());++ let mut dst_fi = BytesMutWithTypeInfo::new(dst);+ self.value.encode(&mut dst_fi)?;++ let dst: &mut [u8] = dst.borrow_mut();+ dst[len_pos] = length;++ Ok(())+ }+}diff --git a/vendor/tiberius/src/tds/codec/token.rs b/vendor/tiberius/src/tds/codec/token.rsnew file mode 100644index 0000000000..706d03710b--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token.rs@@ -0,0 +1,25 @@+mod token_col_metadata;+mod token_done;+mod token_env_change;+mod token_error;+mod token_feature_ext_ack;+mod token_info;+mod token_login_ack;+mod token_order;+mod token_return_value;+mod token_row;+mod token_sspi;+mod token_type;++pub use token_col_metadata::*;+pub use token_done::*;+pub use token_env_change::*;+pub use token_error::*;+pub use token_feature_ext_ack::*;+pub use token_info::*;+pub use token_login_ack::*;+pub use token_order::*;+pub use token_return_value::*;+pub use token_row::*;+pub use token_sspi::*;+pub use token_type::*;diff --git a/vendor/tiberius/src/tds/codec/token/token_col_metadata.rs b/vendor/tiberius/src/tds/codec/token/token_col_metadata.rsnew file mode 100644index 0000000000..53ffdf1c68--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_col_metadata.rs@@ -0,0 +1,349 @@+use std::{+ borrow::{BorrowMut, Cow},+ fmt::Display,+};++use crate::{+ error::Error,+ tds::codec::{Encode, FixedLenType, TokenType, TypeInfo, VarLenType},+ Column, ColumnData, ColumnType, SqlReadBytes,+};+use asynchronous_codec::BytesMut;+use bytes::BufMut;+use enumflags2::{bitflags, BitFlags};++#[derive(Debug, Clone)]+pub struct TokenColMetaData<'a> {+ pub columns: Vec<MetaDataColumn<'a>>,+}++#[derive(Debug, Clone)]+pub struct MetaDataColumn<'a> {+ pub base: BaseMetaDataColumn,+ pub col_name: Cow<'a, str>,+}++impl<'a> Display for MetaDataColumn<'a> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{} ", self.col_name)?;++ match &self.base.ty {+ TypeInfo::FixedLen(fixed) => match fixed {+ FixedLenType::Int1 => write!(f, "tinyint")?,+ FixedLenType::Bit => write!(f, "bit")?,+ FixedLenType::Int2 => write!(f, "smallint")?,+ FixedLenType::Int4 => write!(f, "int")?,+ FixedLenType::Datetime4 => write!(f, "smalldatetime")?,+ FixedLenType::Float4 => write!(f, "real")?,+ FixedLenType::Money => write!(f, "money")?,+ FixedLenType::Datetime => write!(f, "datetime")?,+ FixedLenType::Float8 => write!(f, "float")?,+ FixedLenType::Money4 => write!(f, "smallmoney")?,+ FixedLenType::Int8 => write!(f, "bigint")?,+ FixedLenType::Null => unreachable!(),+ },+ TypeInfo::VarLenSized(ctx) => match ctx.r#type() {+ VarLenType::Bitn => write!(f, "bit")?,+ VarLenType::Guid => write!(f, "uniqueidentifier")?,+ #[cfg(feature = "tds73")]+ VarLenType::Daten => write!(f, "date")?,+ #[cfg(feature = "tds73")]+ VarLenType::Timen => write!(f, "time")?,+ #[cfg(feature = "tds73")]+ VarLenType::Datetime2 => write!(f, "datetime2({})", ctx.len())?,+ VarLenType::Datetimen => write!(f, "datetime")?,+ #[cfg(feature = "tds73")]+ VarLenType::DatetimeOffsetn => write!(f, "datetimeoffset")?,+ VarLenType::BigVarBin => {+ if ctx.len() <= 8000 {+ write!(f, "varbinary({})", ctx.len())?+ } else {+ write!(f, "varbinary(max)")?+ }+ }+ VarLenType::BigVarChar => {+ if ctx.len() <= 8000 {+ write!(f, "varchar({})", ctx.len())?+ } else {+ write!(f, "varchar(max)")?+ }+ }+ VarLenType::BigBinary => write!(f, "binary({})", ctx.len())?,+ VarLenType::BigChar => write!(f, "char({})", ctx.len())?,+ VarLenType::NVarchar => {+ if ctx.len() <= 4000 {+ write!(f, "nvarchar({})", ctx.len())?+ } else {+ write!(f, "nvarchar(max)")?+ }+ }+ VarLenType::NChar => write!(f, "nchar({})", ctx.len())?,+ VarLenType::Text => write!(f, "text")?,+ VarLenType::Image => write!(f, "image")?,+ VarLenType::NText => write!(f, "ntext")?,+ VarLenType::Intn => match ctx.len() {+ 1 => write!(f, "tinyint")?,+ 2 => write!(f, "smallint")?,+ 4 => write!(f, "int")?,+ 8 => write!(f, "bigint")?,+ _ => unreachable!(),+ },+ VarLenType::Floatn => match ctx.len() {+ 4 => write!(f, "real")?,+ 8 => write!(f, "float")?,+ _ => unreachable!(),+ },+ _ => unreachable!(),+ },+ TypeInfo::VarLenSizedPrecision {+ ty,+ size: _,+ precision,+ scale,+ } => match ty {+ VarLenType::Decimaln => write!(f, "decimal({},{})", precision, scale)?,+ VarLenType::Numericn => write!(f, "numeric({},{})", precision, scale)?,+ _ => unreachable!(),+ },+ TypeInfo::Xml { .. } => write!(f, "xml")?,+ }++ Ok(())+ }+}++#[derive(Debug, Clone)]+pub struct BaseMetaDataColumn {+ pub flags: BitFlags<ColumnFlag>,+ pub ty: TypeInfo,+}++impl BaseMetaDataColumn {+ pub(crate) fn null_value(&self) -> ColumnData<'static> {+ match &self.ty {+ TypeInfo::FixedLen(ty) => match ty {+ FixedLenType::Null => ColumnData::I32(None),+ FixedLenType::Int1 => ColumnData::U8(None),+ FixedLenType::Bit => ColumnData::Bit(None),+ FixedLenType::Int2 => ColumnData::I16(None),+ FixedLenType::Int4 => ColumnData::I32(None),+ FixedLenType::Datetime4 => ColumnData::SmallDateTime(None),+ FixedLenType::Float4 => ColumnData::F32(None),+ FixedLenType::Money => ColumnData::F64(None),+ FixedLenType::Datetime => ColumnData::DateTime(None),+ FixedLenType::Float8 => ColumnData::F64(None),+ FixedLenType::Money4 => ColumnData::F32(None),+ FixedLenType::Int8 => ColumnData::I64(None),+ },+ TypeInfo::VarLenSized(cx) => match cx.r#type() {+ VarLenType::Guid => ColumnData::Guid(None),+ VarLenType::Intn => match cx.len() {+ 1 => ColumnData::U8(None),+ 2 => ColumnData::I16(None),+ 4 => ColumnData::I32(None),+ _ => ColumnData::I64(None),+ },+ VarLenType::Bitn => ColumnData::Bit(None),+ VarLenType::Decimaln => ColumnData::Numeric(None),+ VarLenType::Numericn => ColumnData::Numeric(None),+ VarLenType::Floatn => match cx.len() {+ 4 => ColumnData::F32(None),+ _ => ColumnData::F64(None),+ },+ VarLenType::Money => ColumnData::F64(None),+ VarLenType::Datetimen => ColumnData::DateTime(None),+ #[cfg(feature = "tds73")]+ VarLenType::Daten => ColumnData::Date(None),+ #[cfg(feature = "tds73")]+ VarLenType::Timen => ColumnData::Time(None),+ #[cfg(feature = "tds73")]+ VarLenType::Datetime2 => ColumnData::DateTime2(None),+ #[cfg(feature = "tds73")]+ VarLenType::DatetimeOffsetn => ColumnData::DateTimeOffset(None),+ VarLenType::BigVarBin => ColumnData::Binary(None),+ VarLenType::BigVarChar => ColumnData::String(None),+ VarLenType::BigBinary => ColumnData::Binary(None),+ VarLenType::BigChar => ColumnData::String(None),+ VarLenType::NVarchar => ColumnData::String(None),+ VarLenType::NChar => ColumnData::String(None),+ VarLenType::Xml => ColumnData::Xml(None),+ VarLenType::Udt => todo!("User-defined types not supported"),+ VarLenType::Text => ColumnData::String(None),+ VarLenType::Image => ColumnData::Binary(None),+ VarLenType::NText => ColumnData::String(None),+ VarLenType::SSVariant => todo!(),+ },+ TypeInfo::VarLenSizedPrecision { ty, .. } => match ty {+ VarLenType::Guid => ColumnData::Guid(None),+ VarLenType::Intn => ColumnData::I32(None),+ VarLenType::Bitn => ColumnData::Bit(None),+ VarLenType::Decimaln => ColumnData::Numeric(None),+ VarLenType::Numericn => ColumnData::Numeric(None),+ VarLenType::Floatn => ColumnData::F32(None),+ VarLenType::Money => ColumnData::F64(None),+ VarLenType::Datetimen => ColumnData::DateTime(None),+ #[cfg(feature = "tds73")]+ VarLenType::Daten => ColumnData::Date(None),+ #[cfg(feature = "tds73")]+ VarLenType::Timen => ColumnData::Time(None),+ #[cfg(feature = "tds73")]+ VarLenType::Datetime2 => ColumnData::DateTime2(None),+ #[cfg(feature = "tds73")]+ VarLenType::DatetimeOffsetn => ColumnData::DateTimeOffset(None),+ VarLenType::BigVarBin => ColumnData::Binary(None),+ VarLenType::BigVarChar => ColumnData::String(None),+ VarLenType::BigBinary => ColumnData::Binary(None),+ VarLenType::BigChar => ColumnData::String(None),+ VarLenType::NVarchar => ColumnData::String(None),+ VarLenType::NChar => ColumnData::String(None),+ VarLenType::Xml => ColumnData::Xml(None),+ VarLenType::Udt => todo!("User-defined types not supported"),+ VarLenType::Text => ColumnData::String(None),+ VarLenType::Image => ColumnData::Binary(None),+ VarLenType::NText => ColumnData::String(None),+ VarLenType::SSVariant => todo!(),+ },+ TypeInfo::Xml { .. } => ColumnData::Xml(None),+ }+ }+}++impl<'a> Encode<BytesMut> for TokenColMetaData<'a> {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u8(TokenType::ColMetaData as u8);+ dst.put_u16_le(self.columns.len() as u16);++ for col in self.columns.into_iter() {+ col.encode(dst)?;+ }++ Ok(())+ }+}++impl<'a> Encode<BytesMut> for MetaDataColumn<'a> {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u32_le(0);+ self.base.encode(dst)?;++ let len_pos = dst.len();+ let mut length = 0u8;++ dst.put_u8(length);++ for chr in self.col_name.encode_utf16() {+ length += 1;+ dst.put_u16_le(chr);+ }++ let dst: &mut [u8] = dst.borrow_mut();+ dst[len_pos] = length;++ Ok(())+ }+}++impl Encode<BytesMut> for BaseMetaDataColumn {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u16_le(BitFlags::bits(self.flags));+ self.ty.encode(dst)?;++ Ok(())+ }+}++/// A setting a column can hold.+#[bitflags]+#[repr(u16)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ColumnFlag {+ /// The column can be null.+ Nullable = 1 << 0,+ /// Set for string columns with binary collation and always for the XML data+ /// type.+ CaseSensitive = 1 << 1,+ /// If column is writeable.+ Updateable = 1 << 3,+ /// Column modification status unknown.+ UpdateableUnknown = 1 << 4,+ /// Column is an identity.+ Identity = 1 << 5,+ /// Coulumn is computed.+ Computed = 1 << 7,+ /// Column is a fixed-length common language runtime user-defined type (CLR+ /// UDT).+ FixedLenClrType = 1 << 10,+ /// Column is the special XML column for the sparse column set.+ SparseColumnSet = 1 << 11,+ /// Column is encrypted transparently and has to be decrypted to view the+ /// plaintext value. This flag is valid when the column encryption feature+ /// is negotiated between client and server and is turned on.+ Encrypted = 1 << 12,+ /// Column is part of a hidden primary key created to support a T-SQL SELECT+ /// statement containing FOR BROWSE.+ Hidden = 1 << 13,+ /// Column is part of a primary key for the row and the T-SQL SELECT+ /// statement contains FOR BROWSE.+ Key = 1 << 14,+ /// It is unknown whether the column might be nullable.+ NullableUnknown = 1 << 15,+}++impl TokenColMetaData<'static> {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let column_count = src.read_u16_le().await?;+ let mut columns = Vec::with_capacity(column_count as usize);++ if column_count > 0 && column_count < 0xffff {+ for _ in 0..column_count {+ let base = BaseMetaDataColumn::decode(src).await?;+ let col_name = Cow::from(src.read_b_varchar().await?);++ columns.push(MetaDataColumn { base, col_name });+ }+ }++ Ok(TokenColMetaData { columns })+ }+}++impl<'a> TokenColMetaData<'a> {+ pub(crate) fn columns(&self) -> impl Iterator<Item = Column> + '_ {+ self.columns.iter().map(|x| Column {+ name: x.col_name.to_string(),+ column_type: ColumnType::from(&x.base.ty),+ })+ }+}++impl BaseMetaDataColumn {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ use VarLenType::*;++ let _user_ty = src.read_u32_le().await?;++ let flags = BitFlags::from_bits(src.read_u16_le().await?)+ .map_err(|_| Error::Protocol("column metadata: invalid flags".into()))?;++ let ty = TypeInfo::decode(src).await?;++ if let TypeInfo::VarLenSized(cx) = ty {+ if let Text | NText | Image = cx.r#type() {+ let num_of_parts = src.read_u8().await?;++ // table name+ for _ in 0..num_of_parts {+ src.read_us_varchar().await?;+ }+ };+ };++ Ok(BaseMetaDataColumn { flags, ty })+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_done.rs b/vendor/tiberius/src/tds/codec/token/token_done.rsnew file mode 100644index 0000000000..bb45c34ace--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_done.rs@@ -0,0 +1,88 @@+use crate::{tds::codec::Encode, Error, SqlReadBytes, TokenType};+use asynchronous_codec::BytesMut;+use bytes::BufMut;+use enumflags2::{bitflags, BitFlags};+use std::fmt;++#[derive(Debug, Default)]+pub struct TokenDone {+ status: BitFlags<DoneStatus>,+ cur_cmd: u16,+ done_rows: u64,+}++#[bitflags]+#[repr(u16)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DoneStatus {+ More = 1 << 0,+ Error = 1 << 1,+ Inexact = 1 << 2,+ // reserved+ Count = 1 << 4,+ Attention = 1 << 5,+ // reserved+ RpcInBatch = 1 << 7,+ SrvError = 1 << 8,+}++impl TokenDone {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let status = BitFlags::from_bits(src.read_u16_le().await?)+ .map_err(|_| Error::Protocol("done(variant): invalid status".into()))?;++ let cur_cmd = src.read_u16_le().await?;+ let done_row_count_bytes = src.context().version().done_row_count_bytes();++ let done_rows = match done_row_count_bytes {+ 8 => src.read_u64_le().await?,+ 4 => src.read_u32_le().await? as u64,+ _ => unreachable!(),+ };++ Ok(TokenDone {+ status,+ cur_cmd,+ done_rows,+ })+ }++ pub(crate) fn is_final(&self) -> bool {+ self.status.is_empty()+ }++ pub(crate) fn rows(&self) -> u64 {+ self.done_rows+ }+}++impl Encode<BytesMut> for TokenDone {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u8(TokenType::Done as u8);+ dst.put_u16_le(BitFlags::bits(self.status));++ dst.put_u16_le(self.cur_cmd);+ dst.put_u64_le(self.done_rows);++ Ok(())+ }+}++impl fmt::Display for TokenDone {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ if self.done_rows == 0 {+ write!(f, "Done with status {:?}", self.status)+ } else if self.done_rows == 1 {+ write!(f, "Done with status {:?} (1 row left)", self.status)+ } else {+ write!(+ f,+ "Done with status {:?} ({} rows left)",+ self.status, self.done_rows+ )+ }+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_env_change.rs b/vendor/tiberius/src/tds/codec/token/token_env_change.rsnew file mode 100644index 0000000000..ecbb9612f6--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_env_change.rs@@ -0,0 +1,262 @@+use crate::{tds::Collation, Error, SqlReadBytes};+use byteorder::{LittleEndian, ReadBytesExt};+use fmt::Debug;+use futures_util::io::AsyncReadExt;+use std::{+ convert::TryFrom,+ fmt,+ io::{Cursor, Read},+};++uint_enum! {+ #[repr(u8)]+ pub enum EnvChangeTy {+ Database = 1,+ Language = 2,+ CharacterSet = 3,+ PacketSize = 4,+ UnicodeDataSortingLID = 5,+ UnicodeDataSortingCFL = 6,+ SqlCollation = 7,+ /// below here: >= TDSv7.2+ BeginTransaction = 8,+ CommitTransaction = 9,+ RollbackTransaction = 10,+ EnlistDTCTransaction = 11,+ DefectTransaction = 12,+ Rtls = 13,+ PromoteTransaction = 15,+ TransactionManagerAddress = 16,+ TransactionEnded = 17,+ ResetConnection = 18,+ UserName = 19,+ /// below here: TDS v7.4+ Routing = 20,+ }+}++impl fmt::Display for EnvChangeTy {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ EnvChangeTy::Database => write!(f, "Database"),+ EnvChangeTy::Language => write!(f, "Language"),+ EnvChangeTy::CharacterSet => write!(f, "CharacterSet"),+ EnvChangeTy::PacketSize => write!(f, "PacketSize"),+ EnvChangeTy::UnicodeDataSortingLID => write!(f, "UnicodeDataSortingLID"),+ EnvChangeTy::UnicodeDataSortingCFL => write!(f, "UnicodeDataSortingCFL"),+ EnvChangeTy::SqlCollation => write!(f, "SqlCollation"),+ EnvChangeTy::BeginTransaction => write!(f, "BeginTransaction"),+ EnvChangeTy::CommitTransaction => write!(f, "CommitTransaction"),+ EnvChangeTy::RollbackTransaction => write!(f, "RollbackTransaction"),+ EnvChangeTy::EnlistDTCTransaction => write!(f, "EnlistDTCTransaction"),+ EnvChangeTy::DefectTransaction => write!(f, "DefectTransaction"),+ EnvChangeTy::Rtls => write!(f, "RTLS"),+ EnvChangeTy::PromoteTransaction => write!(f, "PromoteTransaction"),+ EnvChangeTy::TransactionManagerAddress => write!(f, "TransactionManagerAddress"),+ EnvChangeTy::TransactionEnded => write!(f, "TransactionEnded"),+ EnvChangeTy::ResetConnection => write!(f, "ResetConnection"),+ EnvChangeTy::UserName => write!(f, "UserName"),+ EnvChangeTy::Routing => write!(f, "Routing"),+ }+ }+}++#[derive(Debug)]+pub enum TokenEnvChange {+ Database(String, String),+ PacketSize(u32, u32),+ SqlCollation {+ old: Option<Collation>,+ new: Option<Collation>,+ },+ BeginTransaction([u8; 8]),+ CommitTransaction,+ RollbackTransaction,+ DefectTransaction,+ Routing {+ host: String,+ port: u16,+ },+ ChangeMirror(String),+ Ignored(EnvChangeTy),+}++impl fmt::Display for TokenEnvChange {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Database(ref old, ref new) => {+ write!(f, "Database change from '{}' to '{}'", old, new)+ }+ Self::PacketSize(old, new) => {+ write!(f, "Packet size change from '{}' to '{}'", old, new)+ }+ Self::SqlCollation { old, new } => match (old, new) {+ (Some(old), Some(new)) => write!(f, "SQL collation change from {} to {}", old, new),+ (_, Some(new)) => write!(f, "SQL collation changed to {}", new),+ (_, _) => write!(f, "SQL collation change"),+ },+ Self::BeginTransaction(_) => write!(f, "Begin transaction"),+ Self::CommitTransaction => write!(f, "Commit transaction"),+ Self::RollbackTransaction => write!(f, "Rollback transaction"),+ Self::DefectTransaction => write!(f, "Defect transaction"),+ Self::Routing { host, port } => write!(+ f,+ "Server requested routing to a new address: {}:{}",+ host, port+ ),+ Self::ChangeMirror(ref mirror) => write!(f, "Fallback mirror server: `{}`", mirror),+ Self::Ignored(ty) => write!(f, "Ignored env change: `{}`", ty),+ }+ }+}++impl TokenEnvChange {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let len = src.read_u16_le().await? as usize;++ // We read all the bytes now, due to whatever environment change tokens+ // we read, they might contain padding zeroes in the end we must+ // discard.+ let mut bytes = vec![0; len];+ src.read_exact(&mut bytes[0..len]).await?;++ let mut buf = Cursor::new(bytes);+ let ty_byte = buf.read_u8()?;++ let ty = EnvChangeTy::try_from(ty_byte)+ .map_err(|_| Error::Protocol(format!("invalid envchange type {:x}", ty_byte).into()))?;++ let token = match ty {+ EnvChangeTy::Database => {+ let len = buf.read_u8()? as usize;+ let mut bytes = vec![0; len];++ for item in bytes.iter_mut().take(len) {+ *item = buf.read_u16::<LittleEndian>()?;+ }++ let new_value = String::from_utf16(&bytes[..])?;++ let len = buf.read_u8()? as usize;+ let mut bytes = vec![0; len];++ for item in bytes.iter_mut().take(len) {+ *item = buf.read_u16::<LittleEndian>()?;+ }++ let old_value = String::from_utf16(&bytes[..])?;++ TokenEnvChange::Database(new_value, old_value)+ }+ EnvChangeTy::PacketSize => {+ let len = buf.read_u8()? as usize;+ let mut bytes = vec![0; len];++ for item in bytes.iter_mut().take(len) {+ *item = buf.read_u16::<LittleEndian>()?;+ }++ let new_value = String::from_utf16(&bytes[..])?;++ let len = buf.read_u8()? as usize;+ let mut bytes = vec![0; len];++ for item in bytes.iter_mut().take(len) {+ *item = buf.read_u16::<LittleEndian>()?;+ }++ let old_value = String::from_utf16(&bytes[..])?;++ TokenEnvChange::PacketSize(new_value.parse()?, old_value.parse()?)+ }+ EnvChangeTy::SqlCollation => {+ let len = buf.read_u8()? as usize;+ let mut new_value = vec![0; len];+ buf.read_exact(&mut new_value[0..len])?;++ let new = if len == 5 {+ let new_sortid = new_value[4];+ let new_info = u32::from_le_bytes([+ new_value[0],+ new_value[1],+ new_value[2],+ new_value[3],+ ]);++ Some(Collation::new(new_info, new_sortid))+ } else {+ None+ };++ let len = buf.read_u8()? as usize;+ let mut old_value = vec![0; len];+ buf.read_exact(&mut old_value[0..len])?;++ let old = if len == 5 {+ let old_sortid = old_value[4];+ let old_info = u32::from_le_bytes([+ old_value[0],+ old_value[1],+ old_value[2],+ old_value[3],+ ]);++ Some(Collation::new(old_info, old_sortid))+ } else {+ None+ };++ TokenEnvChange::SqlCollation { new, old }+ }+ EnvChangeTy::BeginTransaction | EnvChangeTy::EnlistDTCTransaction => {+ let len = buf.read_u8()?;+ assert!(len == 8);++ let mut desc = [0; 8];+ buf.read_exact(&mut desc)?;++ TokenEnvChange::BeginTransaction(desc)+ }++ EnvChangeTy::CommitTransaction => TokenEnvChange::CommitTransaction,+ EnvChangeTy::RollbackTransaction => TokenEnvChange::RollbackTransaction,+ EnvChangeTy::DefectTransaction => TokenEnvChange::DefectTransaction,++ EnvChangeTy::Routing => {+ buf.read_u16::<LittleEndian>()?; // routing data value length+ buf.read_u8()?; // routing protocol, always 0 (tcp)++ let port = buf.read_u16::<LittleEndian>()?;++ let len = buf.read_u16::<LittleEndian>()? as usize; // hostname string length+ let mut bytes = vec![0; len];++ for item in bytes.iter_mut().take(len) {+ *item = buf.read_u16::<LittleEndian>()?;+ }++ let host = String::from_utf16(&bytes[..])?;++ TokenEnvChange::Routing { host, port }+ }+ EnvChangeTy::Rtls => {+ let len = buf.read_u8()? as usize;+ let mut bytes = vec![0; len];++ for item in bytes.iter_mut().take(len) {+ *item = buf.read_u16::<LittleEndian>()?;+ }++ let mirror_name = String::from_utf16(&bytes[..])?;++ TokenEnvChange::ChangeMirror(mirror_name)+ }+ ty => TokenEnvChange::Ignored(ty),+ };++ Ok(token)+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_error.rs b/vendor/tiberius/src/tds/codec/token/token_error.rsnew file mode 100644index 0000000000..d1e435a773--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_error.rs@@ -0,0 +1,103 @@+use crate::{tds::codec::FeatureLevel, SqlReadBytes};+use std::fmt;++#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]+/// An error token returned from the server.+pub struct TokenError {+ /// ErrorCode+ pub(crate) code: u32,+ /// ErrorState (describing code)+ pub(crate) state: u8,+ /// The class (severity) of the error+ pub(crate) class: u8,+ /// The error message+ pub(crate) message: String,+ pub(crate) server: String,+ pub(crate) procedure: String,+ pub(crate) line: u32,+}++impl TokenError {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let _length = src.read_u16_le().await? as usize;++ let code = src.read_u32_le().await?;+ let state = src.read_u8().await?;+ let class = src.read_u8().await?;++ let message = src.read_us_varchar().await?;+ let server = src.read_b_varchar().await?;+ let procedure = src.read_b_varchar().await?;++ let line = if src.context().version() > FeatureLevel::SqlServer2005 {+ src.read_u32_le().await?+ } else {+ src.read_u16_le().await? as u32+ };++ let token = TokenError {+ code,+ state,+ class,+ message,+ server,+ procedure,+ line,+ };++ Ok(token)+ }++ /// The error code, see descriptions from [the manual].+ ///+ /// [the manual]: https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver15+ pub fn code(&self) -> u32 {+ self.code+ }++ /// The error state, used as a modifier to the error number.+ pub fn state(&self) -> u8 {+ self.state+ }++ /// The class (severity) of the error. A class of less than 10 indicates an+ /// informational message.+ pub fn class(&self) -> u8 {+ self.class+ }++ /// The error message returned from the server.+ pub fn message(&self) -> &str {+ &self.message+ }++ /// The server name.+ pub fn server(&self) -> &str {+ &self.server+ }++ /// The name of the stored procedure causing the error.+ pub fn procedure(&self) -> &str {+ &self.procedure+ }++ /// The line number in the SQL batch or stored procedure that caused the+ /// error. Line numbers begin at 1. If the line number is not applicable to+ /// the message, the value is 0.+ pub fn line(&self) -> u32 {+ self.line+ }+}++impl fmt::Display for TokenError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(+ f,+ "'{}' on server {} executing {} on line {} (code: {}, state: {}, class: {})",+ self.message, self.server, self.procedure, self.line, self.code, self.state, self.class+ )+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_feature_ext_ack.rs b/vendor/tiberius/src/tds/codec/token/token_feature_ext_ack.rsnew file mode 100644index 0000000000..1ba108f99c--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_feature_ext_ack.rs@@ -0,0 +1,54 @@+use crate::{SqlReadBytes, FEA_EXT_FEDAUTH, FEA_EXT_TERMINATOR};+use futures_util::AsyncReadExt;++#[derive(Debug)]+pub struct TokenFeatureExtAck {+ pub features: Vec<FeatureAck>,+}++#[derive(Debug)]+#[allow(dead_code)]+pub enum FedAuthAck {+ SecurityToken { nonce: Option<[u8; 32]> },+}++#[derive(Debug)]+#[allow(dead_code)]+pub enum FeatureAck {+ FedAuth(FedAuthAck),+}++impl TokenFeatureExtAck {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let mut features = Vec::new();+ loop {+ let feature_id = src.read_u8().await?;++ if feature_id == FEA_EXT_TERMINATOR {+ break;+ } else if feature_id == FEA_EXT_FEDAUTH {+ let data_len = src.read_u32_le().await?;++ let nonce = if data_len == 32 {+ let mut n = [0u8; 32];+ src.read_exact(&mut n).await?;++ Some(n)+ } else if data_len == 0 {+ None+ } else {+ panic!("invalid Feature_Ext_Ack token");+ };++ features.push(FeatureAck::FedAuth(FedAuthAck::SecurityToken { nonce }))+ } else {+ unimplemented!("unsupported feature {}", feature_id)+ }+ }++ Ok(TokenFeatureExtAck { features })+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_info.rs b/vendor/tiberius/src/tds/codec/token/token_info.rsnew file mode 100644index 0000000000..96c4eca53a--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_info.rs@@ -0,0 +1,43 @@+use crate::SqlReadBytes;++#[allow(dead_code)] // we might want to debug the values+#[derive(Debug)]+pub struct TokenInfo {+ /// info number+ pub(crate) number: u32,+ /// error state+ pub(crate) state: u8,+ /// severity (<10: Info)+ pub(crate) class: u8,+ pub(crate) message: String,+ pub(crate) server: String,+ pub(crate) procedure: String,+ pub(crate) line: u32,+}++impl TokenInfo {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let _length = src.read_u16_le().await?;++ let number = src.read_u32_le().await?;+ let state = src.read_u8().await?;+ let class = src.read_u8().await?;+ let message = src.read_us_varchar().await?;+ let server = src.read_b_varchar().await?;+ let procedure = src.read_b_varchar().await?;+ let line = src.read_u32_le().await?;++ Ok(TokenInfo {+ number,+ state,+ class,+ message,+ server,+ procedure,+ line,+ })+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_login_ack.rs b/vendor/tiberius/src/tds/codec/token/token_login_ack.rsnew file mode 100644index 0000000000..28a4bfc409--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_login_ack.rs@@ -0,0 +1,40 @@+use crate::{Error, FeatureLevel, SqlReadBytes};+use std::convert::TryFrom;++#[allow(dead_code)] // we might want to debug the values+#[derive(Debug)]+pub struct TokenLoginAck {+ /// The type of interface with which the server will accept client requests+ /// 0: SQL_DFLT (server confirms that whatever is sent by the client is acceptable. If the client+ /// requested SQL_DFLT, SQL_TSQL will be used)+ /// 1: SQL_TSQL (TSQL is accepted)+ pub(crate) interface: u8,+ pub(crate) tds_version: FeatureLevel,+ pub(crate) prog_name: String,+ /// major.minor.buildhigh.buildlow+ pub(crate) version: u32,+}++impl TokenLoginAck {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let _length = src.read_u16_le().await?;++ let interface = src.read_u8().await?;++ let tds_version = FeatureLevel::try_from(src.read_u32().await?)+ .map_err(|_| Error::Protocol("Login ACK: Invalid TDS version".into()))?;++ let prog_name = src.read_b_varchar().await?;+ let version = src.read_u32_le().await?;++ Ok(TokenLoginAck {+ interface,+ tds_version,+ prog_name,+ version,+ })+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_order.rs b/vendor/tiberius/src/tds/codec/token/token_order.rsnew file mode 100644index 0000000000..d39dfdbb26--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_order.rs@@ -0,0 +1,24 @@+use crate::SqlReadBytes;++#[allow(dead_code)] // we might want to debug the values+#[derive(Debug)]+pub struct TokenOrder {+ pub(crate) column_indexes: Vec<u16>,+}++impl TokenOrder {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let len = src.read_u16_le().await? / 2;++ let mut column_indexes = Vec::with_capacity(len as usize);++ for _ in 0..len {+ column_indexes.push(src.read_u16_le().await?);+ }++ Ok(TokenOrder { column_indexes })+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_return_value.rs b/vendor/tiberius/src/tds/codec/token/token_return_value.rsnew file mode 100644index 0000000000..183e46be01--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_return_value.rs@@ -0,0 +1,42 @@+use super::BaseMetaDataColumn;+use crate::{tds::codec::ColumnData, Error, SqlReadBytes};++#[derive(Debug)]+#[allow(dead_code)]+pub struct TokenReturnValue {+ pub param_ordinal: u16,+ pub param_name: String,+ /// return value of user defined function+ pub udf: bool,+ pub meta: BaseMetaDataColumn,+ pub value: ColumnData<'static>,+}++impl TokenReturnValue {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let param_ordinal = src.read_u16_le().await?;+ let param_name = src.read_b_varchar().await?;++ let udf = match src.read_u8().await? {+ 0x01 => false,+ 0x02 => true,+ _ => return Err(Error::Protocol("ReturnValue: invalid status".into())),+ };++ let meta = BaseMetaDataColumn::decode(src).await?;+ let value = ColumnData::decode(src, &meta.ty).await?;++ let token = TokenReturnValue {+ param_ordinal,+ param_name,+ udf,+ meta,+ value,+ };++ Ok(token)+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_row.rs b/vendor/tiberius/src/tds/codec/token/token_row.rsnew file mode 100644index 0000000000..b1ff16b6cd--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_row.rs@@ -0,0 +1,210 @@+mod bytes_mut_with_data_columns;+mod into_row;+use crate::tds::codec::encode::Encode;+use crate::{tds::codec::ColumnData, BytesMutWithTypeInfo, SqlReadBytes, TokenType};+use bytes::BufMut;+pub(crate) use bytes_mut_with_data_columns::BytesMutWithDataColumns;+use futures_util::io::AsyncReadExt;+pub use into_row::IntoRow;++/// A row of data.+#[derive(Debug, Default, Clone)]+pub struct TokenRow<'a> {+ data: Vec<ColumnData<'a>>,+}++impl<'a> IntoIterator for TokenRow<'a> {+ type Item = ColumnData<'a>;+ type IntoIter = std::vec::IntoIter<Self::Item>;++ fn into_iter(self) -> Self::IntoIter {+ self.data.into_iter()+ }+}++impl<'a> Encode<BytesMutWithDataColumns<'a>> for TokenRow<'a> {+ fn encode(self, dst: &mut BytesMutWithDataColumns<'a>) -> crate::Result<()> {+ dst.put_u8(TokenType::Row as u8);++ if self.data.len() != dst.data_columns().len() {+ return Err(crate::Error::BulkInput(+ format!(+ "Expecting {} columns but {} were given",+ dst.data_columns().len(),+ self.data.len()+ )+ .into(),+ ));+ }++ for (value, column) in self.data.into_iter().zip(dst.data_columns()) {+ let mut dst_ti = BytesMutWithTypeInfo::new(dst).with_type_info(&column.base.ty);+ value.encode(&mut dst_ti)?+ }++ Ok(())+ }+}++impl<'a> TokenRow<'a> {+ /// Creates a new empty row.+ pub const fn new() -> Self {+ Self { data: Vec::new() }+ }++ /// Creates a new empty row with allocated capacity.+ pub fn with_capacity(capacity: usize) -> Self {+ Self {+ data: Vec::with_capacity(capacity),+ }+ }++ /// Clears the row, removing all column values.+ ///+ /// Note that this method has no effect on the allocated capacity of the row.+ pub fn clear(&mut self) {+ self.data.clear();+ }++ /// The number of columns.+ pub fn len(&self) -> usize {+ self.data.len()+ }++ /// Returns an iterator over column values.+ pub fn iter(&self) -> std::slice::Iter<'_, ColumnData<'a>> {+ self.data.iter()+ }++ /// True if row has no columns.+ pub fn is_empty(&self) -> bool {+ self.data.is_empty()+ }++ /// Gets the columnar data with the given index. `None` if index out of+ /// bounds.+ pub fn get(&self, index: usize) -> Option<&ColumnData<'a>> {+ self.data.get(index)+ }++ /// Adds a new value to the row.+ pub fn push(&mut self, value: ColumnData<'a>) {+ self.data.push(value);+ }+}++impl TokenRow<'static> {+ /// Normal row. We'll read the metadata what we've cached and parse columns+ /// based on that.+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let col_meta = src.context().last_meta().unwrap();++ let mut row = Self {+ data: Vec::with_capacity(col_meta.columns.len()),+ };++ for column in col_meta.columns.iter() {+ let data = ColumnData::decode(src, &column.base.ty).await?;+ row.data.push(data);+ }++ Ok(row)+ }++ /// SQL Server has packed nulls on this row type. We'll read what columns+ /// are null from the bitmap.+ pub(crate) async fn decode_nbc<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let col_meta = src.context().last_meta().unwrap();+ let row_bitmap = RowBitmap::decode(src, col_meta.columns.len()).await?;++ let mut row = Self {+ data: Vec::with_capacity(col_meta.columns.len()),+ };++ for (i, column) in col_meta.columns.iter().enumerate() {+ let data = if row_bitmap.is_null(i) {+ column.base.null_value()+ } else {+ ColumnData::decode(src, &column.base.ty).await?+ };++ row.data.push(data);+ }++ Ok(row)+ }+}++/// A bitmap of null values in the row. Sometimes SQL Server decides to pack the+/// null values in the row, calling it the NBCROW. In this kind of tokens the row+/// itself skips the null columns completely, but they can be found from the bitmap+/// stored in the beginning of the token.+///+/// One byte can store eight bits of information. Bits with value of one being null.+///+/// If our row has eight columns, and our byte in bits is:+///+/// ```ignore+/// 1 0 0 1 0 1 0 0+/// ```+///+/// This would mean columns 0, 3 and 5 are null and should not be parsed at all.+/// For more than eight columns, more bits need to be reserved for the bitmap+/// (see the size calculation).+struct RowBitmap {+ data: Vec<u8>,+}++impl RowBitmap {+ /// Is the given column index null or not.+ #[inline]+ fn is_null(&self, i: usize) -> bool {+ let index = i / 8;+ let bit = i % 8;++ self.data[index] & (1 << bit) > 0+ }++ /// Decode the bitmap data from the beginning of the row. Only doable if the+ /// type is `NbcRowToken`.+ async fn decode<R>(src: &mut R, columns: usize) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let size = (columns + 8 - 1) / 8;+ let mut data = vec![0; size];+ src.read_exact(&mut data[0..size]).await?;++ Ok(Self { data })+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{BaseMetaDataColumn, ColumnFlag, FixedLenType, MetaDataColumn, TypeInfo};+ use bytes::BytesMut;++ #[tokio::test]+ async fn wrong_number_of_columns_will_fail() {+ let row = (true, 5).into_row();+ let columns = vec![MetaDataColumn {+ base: BaseMetaDataColumn {+ flags: ColumnFlag::Nullable.into(),+ ty: TypeInfo::FixedLen(FixedLenType::Bit),+ },+ col_name: Default::default(),+ }];+ let mut buf = BytesMut::new();+ let mut buf_with_columns = BytesMutWithDataColumns::new(&mut buf, &columns);++ row.encode(&mut buf_with_columns)+ .expect_err("wrong number of columns");+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_row/bytes_mut_with_data_columns.rs b/vendor/tiberius/src/tds/codec/token/token_row/bytes_mut_with_data_columns.rsnew file mode 100644index 0000000000..366e2915c0--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_row/bytes_mut_with_data_columns.rs@@ -0,0 +1,63 @@+use crate::MetaDataColumn;+use bytes::buf::UninitSlice;+use bytes::{BufMut, BytesMut};+use std::borrow::{Borrow, BorrowMut};+use std::ops::{Deref, DerefMut};++pub(crate) struct BytesMutWithDataColumns<'a> {+ bytes: &'a mut BytesMut,+ data_columns: &'a Vec<MetaDataColumn<'a>>,+}++impl<'a> BytesMutWithDataColumns<'a> {+ pub fn new(bytes: &'a mut BytesMut, data_columns: &'a Vec<MetaDataColumn<'a>>) -> Self {+ BytesMutWithDataColumns {+ bytes,+ data_columns,+ }+ }++ pub fn data_columns(&self) -> &'a Vec<MetaDataColumn<'a>> {+ self.data_columns+ }+}++unsafe impl<'a> BufMut for BytesMutWithDataColumns<'a> {+ fn remaining_mut(&self) -> usize {+ self.bytes.remaining_mut()+ }++ unsafe fn advance_mut(&mut self, cnt: usize) {+ self.bytes.advance_mut(cnt)+ }++ fn chunk_mut(&mut self) -> &mut UninitSlice {+ self.bytes.chunk_mut()+ }+}++impl<'a> Borrow<[u8]> for BytesMutWithDataColumns<'a> {+ fn borrow(&self) -> &[u8] {+ self.bytes.deref()+ }+}++impl<'a> BorrowMut<[u8]> for BytesMutWithDataColumns<'a> {+ fn borrow_mut(&mut self) -> &mut [u8] {+ self.bytes.borrow_mut()+ }+}++impl<'a> Deref for BytesMutWithDataColumns<'a> {+ type Target = BytesMut;++ fn deref(&self) -> &Self::Target {+ self.bytes+ }+}++impl<'a> DerefMut for BytesMutWithDataColumns<'a> {+ fn deref_mut(&mut self) -> &mut Self::Target {+ self.bytes+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_row/into_row.rs b/vendor/tiberius/src/tds/codec/token/token_row/into_row.rsnew file mode 100644index 0000000000..64e9fcd7b1--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_row/into_row.rs@@ -0,0 +1,207 @@+use crate::{IntoSql, TokenRow};++/// create a TokenRow from list of values+pub trait IntoRow<'a> {+ /// create a TokenRow from list of values which implements IntoSQL+ fn into_row(self) -> TokenRow<'a>;+}++impl<'a, A> IntoRow<'a> for A+where+ A: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.into_sql());+ row+ }+}++impl<'a, A, B> IntoRow<'a> for (A, B)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row+ }+}++impl<'a, A, B, C> IntoRow<'a> for (A, B, C)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row+ }+}++impl<'a, A, B, C, D> IntoRow<'a> for (A, B, C, D)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row+ }+}++impl<'a, A, B, C, D, E> IntoRow<'a> for (A, B, C, D, E)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+ E: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row.push(self.4.into_sql());+ row+ }+}++impl<'a, A, B, C, D, E, F> IntoRow<'a> for (A, B, C, D, E, F)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+ E: IntoSql<'a>,+ F: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row.push(self.4.into_sql());+ row.push(self.5.into_sql());+ row+ }+}++impl<'a, A, B, C, D, E, F, G> IntoRow<'a> for (A, B, C, D, E, F, G)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+ E: IntoSql<'a>,+ F: IntoSql<'a>,+ G: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row.push(self.4.into_sql());+ row.push(self.5.into_sql());+ row.push(self.6.into_sql());+ row+ }+}++impl<'a, A, B, C, D, E, F, G, H> IntoRow<'a> for (A, B, C, D, E, F, G, H)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+ E: IntoSql<'a>,+ F: IntoSql<'a>,+ G: IntoSql<'a>,+ H: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row.push(self.4.into_sql());+ row.push(self.5.into_sql());+ row.push(self.6.into_sql());+ row.push(self.7.into_sql());+ row+ }+}++impl<'a, A, B, C, D, E, F, G, H, I> IntoRow<'a> for (A, B, C, D, E, F, G, H, I)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+ E: IntoSql<'a>,+ F: IntoSql<'a>,+ G: IntoSql<'a>,+ H: IntoSql<'a>,+ I: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row.push(self.4.into_sql());+ row.push(self.5.into_sql());+ row.push(self.6.into_sql());+ row.push(self.7.into_sql());+ row.push(self.8.into_sql());+ row+ }+}++impl<'a, A, B, C, D, E, F, G, H, I, J> IntoRow<'a> for (A, B, C, D, E, F, G, H, I, J)+where+ A: IntoSql<'a>,+ B: IntoSql<'a>,+ C: IntoSql<'a>,+ D: IntoSql<'a>,+ E: IntoSql<'a>,+ F: IntoSql<'a>,+ G: IntoSql<'a>,+ H: IntoSql<'a>,+ I: IntoSql<'a>,+ J: IntoSql<'a>,+{+ fn into_row(self) -> TokenRow<'a> {+ let mut row = TokenRow::new();+ row.push(self.0.into_sql());+ row.push(self.1.into_sql());+ row.push(self.2.into_sql());+ row.push(self.3.into_sql());+ row.push(self.4.into_sql());+ row.push(self.5.into_sql());+ row.push(self.6.into_sql());+ row.push(self.7.into_sql());+ row.push(self.8.into_sql());+ row.push(self.9.into_sql());+ row+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_sspi.rs b/vendor/tiberius/src/tds/codec/token/token_sspi.rsnew file mode 100644index 0000000000..954d6dd8bd--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_sspi.rs@@ -0,0 +1,37 @@+use crate::{sql_read_bytes::SqlReadBytes, tds::codec::Encode};+use bytes::BytesMut;+use futures_util::io::AsyncReadExt;++#[derive(Debug)]+pub struct TokenSspi(Vec<u8>);++impl AsRef<[u8]> for TokenSspi {+ fn as_ref(&self) -> &[u8] {+ self.0.as_ref()+ }+}++impl TokenSspi {+ #[cfg(any(windows, all(unix, feature = "integrated-auth-gssapi")))]+ pub fn new(bytes: Vec<u8>) -> Self {+ Self(bytes)+ }++ pub(crate) async fn decode_async<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let len = src.read_u16_le().await? as usize;+ let mut bytes = vec![0; len];+ src.read_exact(&mut bytes[0..len]).await?;++ Ok(Self(bytes))+ }+}++impl Encode<BytesMut> for TokenSspi {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.extend(self.0);+ Ok(())+ }+}diff --git a/vendor/tiberius/src/tds/codec/token/token_type.rs b/vendor/tiberius/src/tds/codec/token/token_type.rsnew file mode 100644index 0000000000..e4b516bc03--- /dev/null+++ b/vendor/tiberius/src/tds/codec/token/token_type.rs@@ -0,0 +1,82 @@+uint_enum! {+ /// Types of tokens in a token stream. Read from the first byte of the stream.+ pub enum TokenType {+ /// Used to send the status value of an RPC to the client. The server+ /// also uses this token to send the result status value of a stored+ /// procedure executed through SQL Batch.+ ///+ /// This token MUST be returned to the client when an RPC is executed by+ /// the server.+ ReturnStatus = 0x79,++ /// Describes the result setfor interpretation of following ROW data+ /// streams+ ColMetaData = 0x81,++ /// Used to send an error message to the client.+ Error = 0xAA,++ /// Used to send an information message to the client.+ Info = 0xAB,++ /// Used to inform the client by which columns the data is ordered.+ Order = 0xA9,++ /// Describes the column information in browse mode.+ ColInfo = 0xA5,++ /// Used to send the return value of an RPCto the client. When an RPC is+ /// executed, the associated parameters may be defined as input or+ /// output (or "return") parameters.+ ///+ /// This token is used to send a description of the return parameter to+ /// the client. This token is also used to describe the value returned+ /// by a user-defined function (UDF) when executed as an RPC.+ ReturnValue = 0xAC,++ /// Used to send a response to a login request to the client.+ LoginAck = 0xAD,++ /// Used to send a complete row, as defined by the COLNAME and COLFMT+ /// tokens, to the client.+ Row = 0xD1,++ /// Used to send a row with null bitmap compression, as defined by the+ /// COLMETADATA token.+ NbcRow = 0xD2,++ /// The SSPI token returned during the login process.+ Sspi = 0xED,++ /// A notification of an environment change (such as database and+ /// language).+ EnvChange = 0xE3,++ /// Indicates the completion status of a SQL statement.+ ///+ /// This token is used to indicate the completion of a SQL statement.+ /// Because multiple SQL statements may be sent to the server in a+ /// single SQL batch, multiple DONE tokens may be generated. In this+ /// case, all but the final DONE token will have a Status value with the+ /// DONE_MORE bit set.+ ///+ /// A DONE token is returned for each SQL statement in the SQL batch,+ /// except for variable declarations.+ ///+ /// For execution of SQL statements within stored procedures, DONEPROC+ /// and DONEINPROC tokens are used in place of DONE tokens.+ Done = 0xFD,++ /// Indicates the completion status of a stored procedure. This is also+ /// generated for stored procedures executed through SQL statements.+ DoneProc = 0xFE,++ /// Indicates the completion status of a SQL statement within a stored procedure.+ DoneInProc = 0xFF,++ /// used to send an optional acknowledge message to the client for features that+ /// are defined in FeatureExt. The token stream is sent only along with the LOGINACK+ /// in a Login Response message.+ FeatureExtAck = 0xAE,+ }+}diff --git a/vendor/tiberius/src/tds/codec/type_info.rs b/vendor/tiberius/src/tds/codec/type_info.rsnew file mode 100644index 0000000000..20647d70a3--- /dev/null+++ b/vendor/tiberius/src/tds/codec/type_info.rs@@ -0,0 +1,399 @@+use asynchronous_codec::BytesMut;+use bytes::BufMut;++use crate::{tds::Collation, xml::XmlSchema, Error, SqlReadBytes};+use std::{convert::TryFrom, sync::Arc, usize};++use super::Encode;++/// A length of a column in bytes or characters.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TypeLength {+ /// The number of bytes (or characters) reserved in the column.+ Limited(u16),+ /// Unlimited, stored in the heap outside of the row.+ Max,+}++/// Describes a type of a column.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum TypeInfo {+ FixedLen(FixedLenType),+ VarLenSized(VarLenContext),+ VarLenSizedPrecision {+ ty: VarLenType,+ size: usize,+ precision: u8,+ scale: u8,+ },+ Xml {+ schema: Option<Arc<XmlSchema>>,+ size: usize,+ },+}++#[derive(Clone, Debug, Copy, PartialEq, Eq)]+pub struct VarLenContext {+ r#type: VarLenType,+ len: usize,+ collation: Option<Collation>,+}++impl VarLenContext {+ pub fn new(r#type: VarLenType, len: usize, collation: Option<Collation>) -> Self {+ Self {+ r#type,+ len,+ collation,+ }+ }++ /// Get the var len context's r#type.+ pub fn r#type(&self) -> VarLenType {+ self.r#type+ }++ /// Get the var len context's len.+ pub fn len(&self) -> usize {+ self.len+ }++ /// Get the var len context's collation.+ pub fn collation(&self) -> Option<Collation> {+ self.collation+ }+}++impl Encode<BytesMut> for VarLenContext {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u8(self.r#type() as u8);++ // length+ match self.r#type {+ #[cfg(feature = "tds73")]+ VarLenType::Daten+ | VarLenType::Timen+ | VarLenType::DatetimeOffsetn+ | VarLenType::Datetime2 => {+ dst.put_u8(self.len() as u8);+ }+ VarLenType::Bitn+ | VarLenType::Intn+ | VarLenType::Floatn+ | VarLenType::Decimaln+ | VarLenType::Numericn+ | VarLenType::Guid+ | VarLenType::Money+ | VarLenType::Datetimen => {+ dst.put_u8(self.len() as u8);+ }+ VarLenType::NChar+ | VarLenType::BigChar+ | VarLenType::NVarchar+ | VarLenType::BigVarChar+ | VarLenType::BigBinary+ | VarLenType::BigVarBin => {+ dst.put_u16_le(self.len() as u16);+ }+ VarLenType::Image | VarLenType::Text | VarLenType::NText => {+ dst.put_u32_le(self.len() as u32);+ }+ VarLenType::Xml => (),+ typ => todo!("encoding {:?} is not supported yet", typ),+ }++ if let Some(collation) = self.collation() {+ dst.put_u32_le(collation.info());+ dst.put_u8(collation.sort_id());+ }++ Ok(())+ }+}++uint_enum! {+ #[repr(u8)]+ pub enum FixedLenType {+ Null = 0x1F,+ Int1 = 0x30,+ Bit = 0x32,+ Int2 = 0x34,+ Int4 = 0x38,+ Datetime4 = 0x3A,+ Float4 = 0x3B,+ Money = 0x3C,+ Datetime = 0x3D,+ Float8 = 0x3E,+ Money4 = 0x7A,+ Int8 = 0x7F,+ }+}++#[cfg(not(feature = "tds73"))]+uint_enum! {+ /// 2.2.5.4.2+ #[repr(u8)]+ pub enum VarLenType {+ Guid = 0x24,+ Intn = 0x26,+ Bitn = 0x68,+ Decimaln = 0x6A,+ Numericn = 0x6C,+ Floatn = 0x6D,+ Money = 0x6E,+ Datetimen = 0x6F,+ BigVarBin = 0xA5,+ BigVarChar = 0xA7,+ BigBinary = 0xAD,+ BigChar = 0xAF,+ NVarchar = 0xE7,+ NChar = 0xEF,+ Xml = 0xF1,+ // not supported yet+ Udt = 0xF0,+ Text = 0x23,+ Image = 0x22,+ NText = 0x63,+ // not supported yet+ SSVariant = 0x62, // legacy types (not supported since post-7.2):+ // Char = 0x2F,+ // Binary = 0x2D,+ // VarBinary = 0x25,+ // VarChar = 0x27,+ // Numeric = 0x3F,+ // Decimal = 0x37+ }+}++#[cfg(feature = "tds73")]+uint_enum! {+ /// 2.2.5.4.2+ #[repr(u8)]+ pub enum VarLenType {+ Guid = 0x24,+ Intn = 0x26,+ Bitn = 0x68,+ Decimaln = 0x6A,+ Numericn = 0x6C,+ Floatn = 0x6D,+ Money = 0x6E,+ Datetimen = 0x6F,+ Daten = 0x28,+ Timen = 0x29,+ Datetime2 = 0x2A,+ DatetimeOffsetn = 0x2B,+ BigVarBin = 0xA5,+ BigVarChar = 0xA7,+ BigBinary = 0xAD,+ BigChar = 0xAF,+ NVarchar = 0xE7,+ NChar = 0xEF,+ Xml = 0xF1,+ // not supported yet+ Udt = 0xF0,+ Text = 0x23,+ Image = 0x22,+ NText = 0x63,+ // not supported yet+ SSVariant = 0x62, // legacy types (not supported since post-7.2):+ // Char = 0x2F,+ // Binary = 0x2D,+ // VarBinary = 0x25,+ // VarChar = 0x27,+ // Numeric = 0x3F,+ // Decimal = 0x37+ }+}++impl Encode<BytesMut> for TypeInfo {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ match self {+ TypeInfo::FixedLen(ty) => {+ dst.put_u8(ty as u8);+ }+ TypeInfo::VarLenSized(ctx) => ctx.encode(dst)?,+ TypeInfo::VarLenSizedPrecision {+ ty,+ size,+ precision,+ scale,+ } => {+ dst.put_u8(ty as u8);+ dst.put_u8(size as u8);+ dst.put_u8(precision);+ dst.put_u8(scale);+ }+ TypeInfo::Xml { schema, .. } => {+ dst.put_u8(VarLenType::Xml as u8);++ if let Some(xs) = schema {+ dst.put_u8(1);++ let db_name_encoded: Vec<u16> = xs.db_name().encode_utf16().collect();+ dst.put_u8(db_name_encoded.len() as u8);+ for chr in db_name_encoded {+ dst.put_u16_le(chr);+ }++ let owner_encoded: Vec<u16> = xs.owner().encode_utf16().collect();+ dst.put_u8(owner_encoded.len() as u8);+ for chr in owner_encoded {+ dst.put_u16_le(chr);+ }++ let collection_encoded: Vec<u16> = xs.collection().encode_utf16().collect();+ dst.put_u16_le(collection_encoded.len() as u16);+ for chr in collection_encoded {+ dst.put_u16_le(chr);+ }+ } else {+ dst.put_u8(0);+ }+ }+ }++ Ok(())+ }+}++impl TypeInfo {+ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let ty = src.read_u8().await?;++ if let Ok(ty) = FixedLenType::try_from(ty) {+ return Ok(TypeInfo::FixedLen(ty));+ }++ match VarLenType::try_from(ty) {+ Err(()) => Err(Error::Protocol(+ format!("invalid or unsupported column type: {:?}", ty).into(),+ )),+ Ok(VarLenType::Xml) => {+ let has_schema = src.read_u8().await?;++ let schema = if has_schema == 1 {+ let db_name = src.read_b_varchar().await?;+ let owner = src.read_b_varchar().await?;+ let collection = src.read_us_varchar().await?;++ Some(Arc::new(XmlSchema::new(db_name, owner, collection)))+ } else {+ None+ };++ Ok(TypeInfo::Xml {+ schema,+ size: 0xfffffffffffffffe_usize,+ })+ }+ Ok(ty) => {+ let len = match ty {+ #[cfg(feature = "tds73")]+ VarLenType::Timen | VarLenType::DatetimeOffsetn | VarLenType::Datetime2 => {+ src.read_u8().await? as usize+ }+ #[cfg(feature = "tds73")]+ VarLenType::Daten => 3,+ VarLenType::Bitn+ | VarLenType::Intn+ | VarLenType::Floatn+ | VarLenType::Decimaln+ | VarLenType::Numericn+ | VarLenType::Guid+ | VarLenType::Money+ | VarLenType::Datetimen => src.read_u8().await? as usize,+ VarLenType::NChar+ | VarLenType::BigChar+ | VarLenType::NVarchar+ | VarLenType::BigVarChar+ | VarLenType::BigBinary+ | VarLenType::BigVarBin => src.read_u16_le().await? as usize,+ VarLenType::Image | VarLenType::Text | VarLenType::NText => {+ src.read_u32_le().await? as usize+ }+ _ => todo!("not yet implemented for {:?}", ty),+ };++ let collation = match ty {+ VarLenType::NText+ | VarLenType::Text+ | VarLenType::BigChar+ | VarLenType::NChar+ | VarLenType::NVarchar+ | VarLenType::BigVarChar => {+ let info = src.read_u32_le().await?;+ let sort_id = src.read_u8().await?;++ Some(Collation::new(info, sort_id))+ }+ _ => None,+ };++ let vty = match ty {+ VarLenType::Decimaln | VarLenType::Numericn => {+ let precision = src.read_u8().await?;+ let scale = src.read_u8().await?;++ TypeInfo::VarLenSizedPrecision {+ size: len,+ ty,+ precision,+ scale,+ }+ }+ _ => {+ let cx = VarLenContext::new(ty, len, collation);+ TypeInfo::VarLenSized(cx)+ }+ };++ Ok(vty)+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sql_read_bytes::test_utils::IntoSqlReadBytes;++ #[tokio::test]+ async fn round_trip() {+ let types = vec![+ TypeInfo::Xml {+ schema: Some(+ XmlSchema::new("fake-db-name", "fake-owner", "fake-collection").into(),+ ),+ size: 0xfffffffffffffffe_usize,+ },+ TypeInfo::Xml {+ schema: None,+ size: 0xfffffffffffffffe_usize,+ },+ TypeInfo::FixedLen(FixedLenType::Int4),+ TypeInfo::VarLenSized(VarLenContext::new(+ VarLenType::NChar,+ 40,+ Some(Collation::new(13632521, 52)),+ )),+ ];++ for ti in types {+ let mut buf = BytesMut::new();++ ti.clone()+ .encode(&mut buf)+ .expect("encode should be successful");++ let nti = TypeInfo::decode(&mut buf.into_sql_read_bytes())+ .await+ .expect("decode must succeed");++ assert_eq!(nti, ti)+ }+ }+}diff --git a/vendor/tiberius/src/tds/collation.rs b/vendor/tiberius/src/tds/collation.rsnew file mode 100644index 0000000000..20367728ac--- /dev/null+++ b/vendor/tiberius/src/tds/collation.rs@@ -0,0 +1,418 @@+//! legacy implementation of collations (or codepages rather) for dealing with varchar's with legacy databases+//! references [1] which has some mappings from the katmai (SQL Server 2008) source code and is a TDS driver+//! directly from microsoft+//! [2] is helpful to map CP1234 to the appropriate encoding+//!+//! [1] https://github.com/Microsoft/mssql-jdbc/blob/eb14f63077c47ef1fc1c690deb8cfab602baeb85/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java+//! [2] https://github.com/lifthrasiir/rust-encoding/blob/496823171f15d9b9446b2ec3fb7765f22346256b/src/label.rs#L282++use encoding_rs::Encoding;+use std::fmt;++use crate::error::Error;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Collation {+ /// LCID ColFlags Version+ info: u32,+ /// Sortid+ sort_id: u8,+}++impl Collation {+ pub fn new(info: u32, sort_id: u8) -> Self {+ Self { info, sort_id }+ }++ /// return the locale id part of the LCID (the specification here uses ambiguous terms)+ pub fn lcid(&self) -> u16 {+ (self.info & 0xffff) as u16+ }++ pub fn sort_id(&self) -> u8 {+ self.sort_id+ }++ pub fn info(&self) -> u32 {+ self.info+ }++ /// return an encoding for a given collation+ pub fn encoding(&self) -> crate::Result<&'static Encoding> {+ let res = if self.sort_id == 0 {+ lcid_to_encoding(self.lcid())+ } else {+ sortid_to_encoding(self.sort_id)+ };++ res.ok_or_else(|| {+ Error::Encoding(+ format!(+ "encoding: unspported encoding (LCID: {:#02x}, sort ID: {})",+ self.lcid(),+ self.sort_id(),+ )+ .into(),+ )+ })+ }+}++impl fmt::Display for Collation {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self.encoding() {+ Ok(encoding) => write!(f, "{}", encoding.name()),+ _ => write!(f, "None"),+ }+ }+}++/// https://github.com/Microsoft/mssql-jdbc/blob/eb14f63077c47ef1fc1c690deb8cfab602baeb85/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java#L102-L310+/// maps an LCID (it's locale part which is only 2 bytes) to a codepage+///+/// generate the code below from source code:+/// 1. (regex)replace: (.*?)\((.*?),(.*?)\) with $2 => $3+/// 2. replace: Encoding.CP(.*?) with encoding::all::WINDOWS_$1+/// 3. replace: Encoding.UNICODE with encoding::all::UTF16_LE+//+/// the unimplemented!() one's are not supported by rust-encoding+pub fn lcid_to_encoding(locale: u16) -> Option<&'static Encoding> {+ match locale {+ 0x0401 => Some(encoding_rs::WINDOWS_1256),+ 0x0402 => Some(encoding_rs::WINDOWS_1251),+ 0x0403 => Some(encoding_rs::WINDOWS_1252),+ // CP950+ 0x0404 | 0x0c04 | 0x1404 => Some(encoding_rs::BIG5),+ 0x0405 => Some(encoding_rs::WINDOWS_1250),+ 0x0406 => Some(encoding_rs::WINDOWS_1252),+ 0x0407 => Some(encoding_rs::WINDOWS_1252),+ 0x0408 => Some(encoding_rs::WINDOWS_1253),+ 0x0409 => Some(encoding_rs::WINDOWS_1252),+ 0x040a => Some(encoding_rs::WINDOWS_1252),+ 0x040b => Some(encoding_rs::WINDOWS_1252),+ 0x040c => Some(encoding_rs::WINDOWS_1252),+ 0x040d => Some(encoding_rs::WINDOWS_1255),+ 0x040e => Some(encoding_rs::WINDOWS_1250),+ 0x040f => Some(encoding_rs::WINDOWS_1252),+ 0x0410 => Some(encoding_rs::WINDOWS_1252),+ // CP932+ 0x0411 => Some(encoding_rs::SHIFT_JIS),+ 0x0412 => Some(encoding_rs::EUC_KR),+ 0x0413 => Some(encoding_rs::WINDOWS_1252),+ 0x0414 => Some(encoding_rs::WINDOWS_1252),+ 0x0415 => Some(encoding_rs::WINDOWS_1250),+ 0x0416 => Some(encoding_rs::WINDOWS_1252),+ 0x0417 => Some(encoding_rs::WINDOWS_1252),+ 0x0418 => Some(encoding_rs::WINDOWS_1250),+ 0x0419 => Some(encoding_rs::WINDOWS_1251),+ 0x041a => Some(encoding_rs::WINDOWS_1250),+ 0x041b => Some(encoding_rs::WINDOWS_1250),+ 0x041c => Some(encoding_rs::WINDOWS_1250),+ 0x041d => Some(encoding_rs::WINDOWS_1252),+ 0x041e => Some(encoding_rs::WINDOWS_874),+ 0x041f => Some(encoding_rs::WINDOWS_1254),+ 0x0420 => Some(encoding_rs::WINDOWS_1256),+ 0x0421 => Some(encoding_rs::WINDOWS_1252),+ 0x0422 => Some(encoding_rs::WINDOWS_1251),+ 0x0423 => Some(encoding_rs::WINDOWS_1251),+ 0x0424 => Some(encoding_rs::WINDOWS_1250),+ 0x0425 => Some(encoding_rs::WINDOWS_1257),+ 0x0426 => Some(encoding_rs::WINDOWS_1257),+ 0x0427 => Some(encoding_rs::WINDOWS_1257),+ 0x0428 => Some(encoding_rs::WINDOWS_1251),+ 0x0429 => Some(encoding_rs::WINDOWS_1256),+ 0x042a => Some(encoding_rs::WINDOWS_1258),+ 0x042b => Some(encoding_rs::WINDOWS_1252),+ 0x042c => Some(encoding_rs::WINDOWS_1254),+ 0x042d => Some(encoding_rs::WINDOWS_1252),+ 0x042e => Some(encoding_rs::WINDOWS_1252),+ 0x042f => Some(encoding_rs::WINDOWS_1251),+ 0x0432 => Some(encoding_rs::WINDOWS_1252),+ 0x0434 => Some(encoding_rs::WINDOWS_1252),+ 0x0435 => Some(encoding_rs::WINDOWS_1252),+ 0x0436 => Some(encoding_rs::WINDOWS_1252),+ 0x0437 => Some(encoding_rs::WINDOWS_1252),+ 0x0438 => Some(encoding_rs::WINDOWS_1252),+ 0x0439 => Some(encoding_rs::UTF_16LE),+ 0x043a => Some(encoding_rs::UTF_16LE),+ 0x043b => Some(encoding_rs::WINDOWS_1252),+ 0x043e => Some(encoding_rs::WINDOWS_1252),+ 0x043f => Some(encoding_rs::WINDOWS_1251),+ 0x0440 => Some(encoding_rs::WINDOWS_1251),+ 0x0441 => Some(encoding_rs::WINDOWS_1252),+ 0x0442 => Some(encoding_rs::WINDOWS_1250),+ 0x0443 => Some(encoding_rs::WINDOWS_1254),+ 0x0444 => Some(encoding_rs::WINDOWS_1251),+ 0x0445 => Some(encoding_rs::UTF_16LE),+ 0x0446 => Some(encoding_rs::UTF_16LE),+ 0x0447 => Some(encoding_rs::UTF_16LE),+ 0x0448 => Some(encoding_rs::UTF_16LE),+ 0x0449 => Some(encoding_rs::UTF_16LE),+ 0x044a => Some(encoding_rs::UTF_16LE),+ 0x044b => Some(encoding_rs::UTF_16LE),+ 0x044c => Some(encoding_rs::UTF_16LE),+ 0x044d => Some(encoding_rs::UTF_16LE),+ 0x044e => Some(encoding_rs::UTF_16LE),+ 0x044f => Some(encoding_rs::UTF_16LE),+ 0x0450 => Some(encoding_rs::WINDOWS_1251),+ 0x0451 => Some(encoding_rs::UTF_16LE),+ 0x0452 => Some(encoding_rs::WINDOWS_1252),+ 0x0453 => Some(encoding_rs::UTF_16LE),+ 0x0454 => Some(encoding_rs::UTF_16LE),+ 0x0456 => Some(encoding_rs::WINDOWS_1252),+ 0x0457 => Some(encoding_rs::UTF_16LE),+ 0x045a => Some(encoding_rs::UTF_16LE),+ 0x045b => Some(encoding_rs::UTF_16LE),+ 0x045d => Some(encoding_rs::WINDOWS_1252),+ 0x045e => Some(encoding_rs::WINDOWS_1252),+ 0x0461 => Some(encoding_rs::UTF_16LE),+ 0x0462 => Some(encoding_rs::WINDOWS_1252),+ 0x0463 => Some(encoding_rs::UTF_16LE),+ 0x0464 => Some(encoding_rs::WINDOWS_1252),+ 0x0465 => Some(encoding_rs::UTF_16LE),+ 0x0468 => Some(encoding_rs::WINDOWS_1252),+ 0x046a => Some(encoding_rs::WINDOWS_1252),+ 0x046b => Some(encoding_rs::WINDOWS_1252),+ 0x046c => Some(encoding_rs::WINDOWS_1252),+ 0x046d => Some(encoding_rs::WINDOWS_1251),+ 0x046e => Some(encoding_rs::WINDOWS_1252),+ 0x046f => Some(encoding_rs::WINDOWS_1252),+ 0x0470 => Some(encoding_rs::WINDOWS_1252),+ 0x0478 => Some(encoding_rs::WINDOWS_1252),+ 0x047a => Some(encoding_rs::WINDOWS_1252),+ 0x047c => Some(encoding_rs::WINDOWS_1252),+ 0x047e => Some(encoding_rs::WINDOWS_1252),+ 0x0480 => Some(encoding_rs::WINDOWS_1256),+ 0x0481 => Some(encoding_rs::UTF_16LE),+ 0x0482 => Some(encoding_rs::WINDOWS_1252),+ 0x0483 => Some(encoding_rs::WINDOWS_1252),+ 0x0484 => Some(encoding_rs::WINDOWS_1252),+ 0x0485 => Some(encoding_rs::WINDOWS_1251),+ 0x0486 => Some(encoding_rs::WINDOWS_1252),+ 0x0487 => Some(encoding_rs::WINDOWS_1252),+ 0x0488 => Some(encoding_rs::WINDOWS_1252),+ 0x048c => Some(encoding_rs::WINDOWS_1256),+ 0x0801 => Some(encoding_rs::WINDOWS_1256),+ // CP936+ 0x0804 | 0x1004 => Some(encoding_rs::GB18030),+ 0x0807 => Some(encoding_rs::WINDOWS_1252),+ 0x0809 => Some(encoding_rs::WINDOWS_1252),+ 0x080a => Some(encoding_rs::WINDOWS_1252),+ 0x080c => Some(encoding_rs::WINDOWS_1252),+ 0x0810 => Some(encoding_rs::WINDOWS_1252),+ 0x0813 => Some(encoding_rs::WINDOWS_1252),+ 0x0814 => Some(encoding_rs::WINDOWS_1252),+ 0x0816 => Some(encoding_rs::WINDOWS_1252),+ 0x081a => Some(encoding_rs::WINDOWS_1250),+ 0x081d => Some(encoding_rs::WINDOWS_1252),+ 0x0827 => Some(encoding_rs::WINDOWS_1257),+ 0x082c => Some(encoding_rs::WINDOWS_1251),+ 0x082e => Some(encoding_rs::WINDOWS_1252),+ 0x083b => Some(encoding_rs::WINDOWS_1252),+ 0x083c => Some(encoding_rs::WINDOWS_1252),+ 0x083e => Some(encoding_rs::WINDOWS_1252),+ 0x0843 => Some(encoding_rs::WINDOWS_1251),+ 0x0845 => Some(encoding_rs::UTF_16LE),+ 0x0850 => Some(encoding_rs::WINDOWS_1251),+ 0x085d => Some(encoding_rs::WINDOWS_1252),+ 0x085f => Some(encoding_rs::WINDOWS_1252),+ 0x086b => Some(encoding_rs::WINDOWS_1252),+ 0x0c01 => Some(encoding_rs::WINDOWS_1256),+ 0x0c07 => Some(encoding_rs::WINDOWS_1252),+ 0x0c09 => Some(encoding_rs::WINDOWS_1252),+ 0x0c0a => Some(encoding_rs::WINDOWS_1252),+ 0x0c0c => Some(encoding_rs::WINDOWS_1252),+ 0x0c1a => Some(encoding_rs::WINDOWS_1251),+ 0x0c3b => Some(encoding_rs::WINDOWS_1252),+ 0x0c6b => Some(encoding_rs::WINDOWS_1252),+ 0x1001 => Some(encoding_rs::WINDOWS_1256),+ 0x1007 => Some(encoding_rs::WINDOWS_1252),+ 0x1009 => Some(encoding_rs::WINDOWS_1252),+ 0x100a => Some(encoding_rs::WINDOWS_1252),+ 0x100c => Some(encoding_rs::WINDOWS_1252),+ 0x101a => Some(encoding_rs::WINDOWS_1250),+ 0x103b => Some(encoding_rs::WINDOWS_1252),+ 0x1401 => Some(encoding_rs::WINDOWS_1256),+ 0x1407 => Some(encoding_rs::WINDOWS_1252),+ 0x1409 => Some(encoding_rs::WINDOWS_1252),+ 0x140a => Some(encoding_rs::WINDOWS_1252),+ 0x140c => Some(encoding_rs::WINDOWS_1252),+ 0x141a => Some(encoding_rs::WINDOWS_1250),+ 0x143b => Some(encoding_rs::WINDOWS_1252),+ 0x1801 => Some(encoding_rs::WINDOWS_1256),+ 0x1809 => Some(encoding_rs::WINDOWS_1252),+ 0x180a => Some(encoding_rs::WINDOWS_1252),+ 0x180c => Some(encoding_rs::WINDOWS_1252),+ 0x181a => Some(encoding_rs::WINDOWS_1250),+ 0x183b => Some(encoding_rs::WINDOWS_1252),+ 0x1c01 => Some(encoding_rs::WINDOWS_1256),+ 0x1c09 => Some(encoding_rs::WINDOWS_1252),+ 0x1c0a => Some(encoding_rs::WINDOWS_1252),+ 0x1c1a => Some(encoding_rs::WINDOWS_1251),+ 0x1c3b => Some(encoding_rs::WINDOWS_1252),+ 0x2001 => Some(encoding_rs::WINDOWS_1256),+ 0x2009 => Some(encoding_rs::WINDOWS_1252),+ 0x200a => Some(encoding_rs::WINDOWS_1252),+ 0x201a => Some(encoding_rs::WINDOWS_1251),+ 0x203b => Some(encoding_rs::WINDOWS_1252),+ 0x2401 => Some(encoding_rs::WINDOWS_1256),+ 0x2409 => Some(encoding_rs::WINDOWS_1252),+ 0x240a => Some(encoding_rs::WINDOWS_1252),+ 0x243b => Some(encoding_rs::WINDOWS_1252),+ 0x2801 => Some(encoding_rs::WINDOWS_1256),+ 0x2809 => Some(encoding_rs::WINDOWS_1252),+ 0x280a => Some(encoding_rs::WINDOWS_1252),+ 0x2c01 => Some(encoding_rs::WINDOWS_1256),+ 0x2c09 => Some(encoding_rs::WINDOWS_1252),+ 0x2c0a => Some(encoding_rs::WINDOWS_1252),+ 0x3001 => Some(encoding_rs::WINDOWS_1256),+ 0x3009 => Some(encoding_rs::WINDOWS_1252),+ 0x300a => Some(encoding_rs::WINDOWS_1252),+ 0x3401 => Some(encoding_rs::WINDOWS_1256),+ 0x3409 => Some(encoding_rs::WINDOWS_1252),+ 0x340a => Some(encoding_rs::WINDOWS_1252),+ 0x3801 => Some(encoding_rs::WINDOWS_1256),+ 0x380a => Some(encoding_rs::WINDOWS_1252),+ 0x3c01 => Some(encoding_rs::WINDOWS_1256),+ 0x3c0a => Some(encoding_rs::WINDOWS_1252),+ 0x4001 => Some(encoding_rs::WINDOWS_1256),+ 0x4009 => Some(encoding_rs::WINDOWS_1252),+ 0x400a => Some(encoding_rs::WINDOWS_1252),+ 0x4409 => Some(encoding_rs::WINDOWS_1252),+ 0x440a => Some(encoding_rs::WINDOWS_1252),+ 0x4809 => Some(encoding_rs::WINDOWS_1252),+ 0x480a => Some(encoding_rs::WINDOWS_1252),+ 0x4c0a => Some(encoding_rs::WINDOWS_1252),+ 0x500a => Some(encoding_rs::WINDOWS_1252),+ 0x540a => Some(encoding_rs::WINDOWS_1252),+ _ => None,+ }+}++/// [1] https://github.com/Microsoft/mssql-jdbc/blob/eb14f63077c47ef1fc1c690deb8cfab602baeb85/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java#L362-L482+/// [2] https://msdn.microsoft.com/de-de/library/ms144250(v=sql.105).aspx+///+/// [2] does only contain 3/4 of the content [1] contains, so the source code is again the better source of information+///+/// generate the code below from source code:+/// 1. (regex)replace .*\((.*?),.*?,(.*?)\) with $1 => $2+/// 2. see above/as above+pub fn sortid_to_encoding(sort_id: u8) -> Option<&'static Encoding> {+ match sort_id {+ // 30 | 31 | 32 | 33 | 34 | 35 => Some(encoding_rs::WINDOWS_437),+ // 40 | 41 | 42 | 43 | 44 | 45 | 49 => Some(encoding_rs::WINDOWS_850),+ 50 => Some(encoding_rs::WINDOWS_1252),+ 51 => Some(encoding_rs::WINDOWS_1252),+ 52 => Some(encoding_rs::WINDOWS_1252),+ 53 => Some(encoding_rs::WINDOWS_1252),+ 54 => Some(encoding_rs::WINDOWS_1252),+ // 55 | 56 | 57 | 58 | 59 | 60 | 61 => Some(encoding_rs::WINDOWS_850),+ 71 => Some(encoding_rs::WINDOWS_1252),+ 72 => Some(encoding_rs::WINDOWS_1252),+ 73 => Some(encoding_rs::WINDOWS_1252),+ 74 => Some(encoding_rs::WINDOWS_1252),+ 75 => Some(encoding_rs::WINDOWS_1252),+ 80 => Some(encoding_rs::WINDOWS_1250),+ 81 => Some(encoding_rs::WINDOWS_1250),+ 82 => Some(encoding_rs::WINDOWS_1250),+ 83 => Some(encoding_rs::WINDOWS_1250),+ 84 => Some(encoding_rs::WINDOWS_1250),+ 85 => Some(encoding_rs::WINDOWS_1250),+ 86 => Some(encoding_rs::WINDOWS_1250),+ 87 => Some(encoding_rs::WINDOWS_1250),+ 88 => Some(encoding_rs::WINDOWS_1250),+ 89 => Some(encoding_rs::WINDOWS_1250),+ 90 => Some(encoding_rs::WINDOWS_1250),+ 91 => Some(encoding_rs::WINDOWS_1250),+ 92 => Some(encoding_rs::WINDOWS_1250),+ 93 => Some(encoding_rs::WINDOWS_1250),+ 94 => Some(encoding_rs::WINDOWS_1250),+ 95 => Some(encoding_rs::WINDOWS_1250),+ 96 => Some(encoding_rs::WINDOWS_1250),+ 97 => Some(encoding_rs::WINDOWS_1250),+ 98 => Some(encoding_rs::WINDOWS_1250),+ 104 => Some(encoding_rs::WINDOWS_1251),+ 105 => Some(encoding_rs::WINDOWS_1251),+ 106 => Some(encoding_rs::WINDOWS_1251),+ 107 => Some(encoding_rs::WINDOWS_1251),+ 108 => Some(encoding_rs::WINDOWS_1251),+ 112 => Some(encoding_rs::WINDOWS_1253),+ 113 => Some(encoding_rs::WINDOWS_1253),+ 114 => Some(encoding_rs::WINDOWS_1253),+ 120 => Some(encoding_rs::WINDOWS_1253),+ 121 => Some(encoding_rs::WINDOWS_1253),+ 122 => Some(encoding_rs::WINDOWS_1253),+ 124 => Some(encoding_rs::WINDOWS_1253),+ 128 => Some(encoding_rs::WINDOWS_1254),+ 129 => Some(encoding_rs::WINDOWS_1254),+ 130 => Some(encoding_rs::WINDOWS_1254),+ 136 => Some(encoding_rs::WINDOWS_1255),+ 137 => Some(encoding_rs::WINDOWS_1255),+ 138 => Some(encoding_rs::WINDOWS_1255),+ 144 => Some(encoding_rs::WINDOWS_1256),+ 145 => Some(encoding_rs::WINDOWS_1256),+ 146 => Some(encoding_rs::WINDOWS_1256),+ 152 => Some(encoding_rs::WINDOWS_1257),+ 153 => Some(encoding_rs::WINDOWS_1257),+ 154 => Some(encoding_rs::WINDOWS_1257),+ 155 => Some(encoding_rs::WINDOWS_1257),+ 156 => Some(encoding_rs::WINDOWS_1257),+ 157 => Some(encoding_rs::WINDOWS_1257),+ 158 => Some(encoding_rs::WINDOWS_1257),+ 159 => Some(encoding_rs::WINDOWS_1257),+ 160 => Some(encoding_rs::WINDOWS_1257),+ 183 => Some(encoding_rs::WINDOWS_1252),+ 184 => Some(encoding_rs::WINDOWS_1252),+ 185 => Some(encoding_rs::WINDOWS_1252),+ 186 => Some(encoding_rs::WINDOWS_1252),+ // CP 932+ 192 | 193 | 200 => Some(encoding_rs::SHIFT_JIS),+ 194 => Some(encoding_rs::EUC_KR),+ 195 => Some(encoding_rs::EUC_KR),+ // CP950+ 196 | 197 | 202 => Some(encoding_rs::BIG5),+ // CP936 (GB18030 is an extension of it with more chars), should be backwards-compatible)+ 198 | 199 | 203 => Some(encoding_rs::GB18030),+ 201 => Some(encoding_rs::BIG5),+ 204 => Some(encoding_rs::WINDOWS_874),+ 205 => Some(encoding_rs::WINDOWS_874),+ 206 => Some(encoding_rs::WINDOWS_874),+ 210 => Some(encoding_rs::WINDOWS_1252),+ 211 => Some(encoding_rs::WINDOWS_1252),+ 212 => Some(encoding_rs::WINDOWS_1252),+ 213 => Some(encoding_rs::WINDOWS_1252),+ 214 => Some(encoding_rs::WINDOWS_1252),+ 215 => Some(encoding_rs::WINDOWS_1252),+ 216 => Some(encoding_rs::WINDOWS_1252),+ 217 => Some(encoding_rs::WINDOWS_1252),+ _ => None,+ }+}++/* TODO+#[cfg(test)]+mod tests {+ use futures_state_stream::StateStream;+ use tokio::executor::current_thread;+ use crate::tests::new_connection;++ #[test]+ fn select_nvarchar_collation_test() {+ let c1 = new_connection();+ let query = c1.simple_query(+ "select cast(cast(N'cześć' as nvarchar(5)) collate Polish_CI_AI as varchar(5))",+ );+ let mut i = 0;+ {+ let future = query.for_each(|x| {+ let val: &str = x.get(0);+ assert_eq!(val, "cześć");+ i += 1;+ Ok(())+ });+ current_thread::block_on_all(future).unwrap();+ }+ assert_eq!(i, 1);+ }+}+*/diff --git a/vendor/tiberius/src/tds/context.rs b/vendor/tiberius/src/tds/context.rsnew file mode 100644index 0000000000..732bac15cb--- /dev/null+++ b/vendor/tiberius/src/tds/context.rs@@ -0,0 +1,69 @@+use super::codec::*;+use std::sync::Arc;++/// Context, that might be required to make sure we understand and are understood by the server+#[derive(Debug)]+pub(crate) struct Context {+ version: FeatureLevel,+ packet_size: u32,+ packet_id: u8,+ transaction_desc: [u8; 8],+ last_meta: Option<Arc<TokenColMetaData<'static>>>,+ spn: Option<String>,+}++impl Context {+ pub fn new() -> Context {+ Context {+ version: FeatureLevel::SqlServerN,+ packet_size: 4096,+ packet_id: 0,+ transaction_desc: [0; 8],+ last_meta: None,+ spn: None,+ }+ }++ pub fn next_packet_id(&mut self) -> u8 {+ let id = self.packet_id;+ self.packet_id = self.packet_id.wrapping_add(1);+ id+ }++ pub fn set_last_meta(&mut self, meta: Arc<TokenColMetaData<'static>>) {+ self.last_meta.replace(meta);+ }++ pub fn last_meta(&self) -> Option<Arc<TokenColMetaData<'static>>> {+ self.last_meta.clone()+ }++ pub fn packet_size(&self) -> u32 {+ self.packet_size+ }++ pub fn set_packet_size(&mut self, new_size: u32) {+ self.packet_size = new_size;+ }++ pub fn transaction_descriptor(&self) -> [u8; 8] {+ self.transaction_desc+ }++ pub fn set_transaction_descriptor(&mut self, desc: [u8; 8]) {+ self.transaction_desc = desc;+ }++ pub fn version(&self) -> FeatureLevel {+ self.version+ }++ pub fn set_spn(&mut self, host: impl AsRef<str>, port: u16) {+ self.spn = Some(format!("MSSQLSvc/{}:{}", host.as_ref(), port));+ }++ #[cfg(any(windows, all(unix, feature = "integrated-auth-gssapi")))]+ pub fn spn(&self) -> &str {+ self.spn.as_deref().unwrap_or("")+ }+}diff --git a/vendor/tiberius/src/tds/numeric.rs b/vendor/tiberius/src/tds/numeric.rsnew file mode 100644index 0000000000..4f856bebb4--- /dev/null+++ b/vendor/tiberius/src/tds/numeric.rs@@ -0,0 +1,391 @@+//! Representations of numeric types.++use super::codec::Encode;+use crate::{sql_read_bytes::SqlReadBytes, Error};+#[cfg(feature = "bigdecimal")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "bigdecimal")))]+pub use bigdecimal::{num_bigint::BigInt, BigDecimal};+use byteorder::{ByteOrder, LittleEndian};+use bytes::{BufMut, BytesMut};+#[cfg(feature = "rust_decimal")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "rust_decimal")))]+pub use rust_decimal::Decimal;+use std::cmp::{Ordering, PartialEq};+use std::fmt::{self, Debug, Display, Formatter};++/// Represent a sql Decimal / Numeric type. It is stored in a i128 and has a+/// maximum precision of 38 decimals.+///+/// A recommended way of dealing with numeric values is by enabling the+/// `rust_decimal` feature and using its `Decimal` type instead.+#[derive(Copy, Clone)]+pub struct Numeric {+ value: i128,+ scale: u8,+}++impl Numeric {+ /// Creates a new Numeric value.+ ///+ /// # Panic+ /// It will panic if the scale exceed 37.+ pub fn new_with_scale(value: i128, scale: u8) -> Self {+ // scale cannot exceed 37 since a+ // max precision of 38 is possible here.+ assert!(scale < 38);++ Numeric { value, scale }+ }++ /// Extract the decimal part.+ pub fn dec_part(self) -> i128 {+ let scale = self.pow_scale();+ self.value - (self.value / scale) * scale+ }++ /// Extract the integer part.+ pub fn int_part(self) -> i128 {+ self.value / self.pow_scale()+ }++ #[inline]+ fn pow_scale(self) -> i128 {+ 10i128.pow(self.scale as u32)+ }++ /// The scale (where is the decimal point) of the value.+ #[inline]+ pub fn scale(self) -> u8 {+ self.scale+ }++ /// The internal integer value+ #[inline]+ pub fn value(self) -> i128 {+ self.value+ }++ /// The precision of the `Number` as a number of digits.+ pub fn precision(self) -> u8 {+ let mut result = 0;+ let mut n = self.int_part();++ while n != 0 {+ n /= 10;+ result += 1;+ }++ if result == 0 {+ 1 + self.scale()+ } else {+ result + self.scale()+ }+ }++ pub(crate) fn len(self) -> u8 {+ match self.precision() {+ 1..=9 => 5,+ 10..=19 => 9,+ 20..=28 => 13,+ _ => 17,+ }+ }++ pub(crate) async fn decode<R>(src: &mut R, scale: u8) -> crate::Result<Option<Self>>+ where+ R: SqlReadBytes + Unpin,+ {+ fn decode_d128(buf: &[u8]) -> u128 {+ let low_part = LittleEndian::read_u64(&buf[0..]) as u128;++ if !buf[8..].iter().any(|x| *x != 0) {+ return low_part;+ }++ let high_part = match buf.len() {+ 12 => LittleEndian::read_u32(&buf[8..]) as u128,+ 16 => LittleEndian::read_u64(&buf[8..]) as u128,+ _ => unreachable!(),+ };++ // swap high&low for big endian+ #[cfg(target_endian = "big")]+ let (low_part, high_part) = (high_part, low_part);++ let high_part = high_part * (u64::max_value() as u128 + 1);+ low_part + high_part+ }++ let len = src.read_u8().await?;++ if len == 0 {+ Ok(None)+ } else {+ let sign = match src.read_u8().await? {+ 0 => -1i128,+ 1 => 1i128,+ _ => return Err(Error::Protocol("decimal: invalid sign".into())),+ };++ let value = match len {+ 5 => src.read_u32_le().await? as i128 * sign,+ 9 => src.read_u64_le().await? as i128 * sign,+ 13 => {+ let mut bytes = [0u8; 12]; //u96+ for item in &mut bytes {+ *item = src.read_u8().await?;+ }+ decode_d128(&bytes) as i128 * sign+ }+ 17 => {+ let mut bytes = [0u8; 16];+ for item in &mut bytes {+ *item = src.read_u8().await?;+ }+ decode_d128(&bytes) as i128 * sign+ }+ x => {+ return Err(Error::Protocol(+ format!("decimal/numeric: invalid length of {} received", x).into(),+ ))+ }+ };++ Ok(Some(Numeric::new_with_scale(value, scale)))+ }+ }+}++impl Encode<BytesMut> for Numeric {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u8(self.len());++ if self.value < 0 {+ dst.put_u8(0);+ } else {+ dst.put_u8(1);+ }++ let value = self.value().abs();++ match self.len() {+ 5 => dst.put_u32_le(value as u32),+ 9 => dst.put_u64_le(value as u64),+ 13 => {+ dst.put_u64_le(value as u64);+ dst.put_u32_le((value >> 64) as u32)+ }+ _ => dst.put_u128_le(value as u128),+ }++ Ok(())+ }+}++impl Debug for Numeric {+ fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {+ write!(+ f,+ "{}.{:0pad$}",+ self.int_part(),+ self.dec_part(),+ pad = self.scale as usize+ )+ }+}++impl Display for Numeric {+ fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {+ write!(f, "{:?}", self)+ }+}++impl Eq for Numeric {}++impl From<Numeric> for f64 {+ fn from(n: Numeric) -> f64 {+ n.dec_part() as f64 / n.pow_scale() as f64 + n.int_part() as f64+ }+}++impl From<Numeric> for i128 {+ fn from(n: Numeric) -> i128 {+ n.int_part()+ }+}++impl From<Numeric> for u128 {+ fn from(n: Numeric) -> u128 {+ n.int_part() as u128+ }+}++impl PartialEq for Numeric {+ fn eq(&self, other: &Self) -> bool {+ match self.scale.cmp(&other.scale) {+ Ordering::Greater => {+ 10i128.pow((self.scale - other.scale) as u32) * other.value == self.value+ }+ Ordering::Less => {+ 10i128.pow((other.scale - self.scale) as u32) * self.value == other.value+ }+ Ordering::Equal => self.value == other.value,+ }+ }+}++#[cfg(feature = "rust_decimal")]+mod decimal {+ use super::{Decimal, Numeric};+ use crate::ColumnData;++ #[cfg(feature = "tds73")]+ from_sql!(Decimal: ColumnData::Numeric(ref num) => num.map(|num| {+ Decimal::from_i128_with_scale(+ num.value(),+ num.scale() as u32,+ )})+ );++ #[cfg(feature = "tds73")]+ to_sql!(self_,+ Decimal: (ColumnData::Numeric, {+ let unpacked = self_.unpack();++ let mut value = (((unpacked.hi as u128) << 64)+ + ((unpacked.mid as u128) << 32)+ + unpacked.lo as u128) as i128;++ if self_.is_sign_negative() {+ value = -value;+ }++ Numeric::new_with_scale(value, self_.scale() as u8)+ });+ );+}++#[cfg(feature = "bigdecimal")]+mod bigdecimal_ {+ use super::{BigDecimal, BigInt, Numeric};+ use crate::ColumnData;+ use num_traits::ToPrimitive;+ use std::convert::TryFrom;++ #[cfg(feature = "tds73")]+ from_sql!(BigDecimal: ColumnData::Numeric(ref num) => num.map(|num| {+ let int = BigInt::from(num.value());++ BigDecimal::new(int, num.scale() as i64)+ }));++ #[cfg(feature = "tds73")]+ to_sql!(self_,+ BigDecimal: (ColumnData::Numeric, {+ let (int, exp) = self_.as_bigint_and_exponent();+ // SQL Server cannot store negative scales, so we have+ // to convert the number to the correct exponent+ // before storing.+ //+ // E.g. `Decimal(9, -3)` would be stored as+ // `Decimal(9000, 0)`.+ let (int, exp) = if exp < 0 {+ self_.with_scale(0).into_bigint_and_exponent()+ } else {+ (int, exp)+ };++ let value = int.to_i128().expect("Given BigDecimal overflowing the maximum accepted value.");++ let scale = u8::try_from(std::cmp::max(exp, 0))+ .expect("Given BigDecimal exponent overflowing the maximum accepted scale (255).");++ Numeric::new_with_scale(value, scale)+ });+ );++ #[cfg(feature = "tds73")]+ into_sql!(self_,+ BigDecimal: (ColumnData::Numeric, {+ let (int, exp) = self_.as_bigint_and_exponent();+ // SQL Server cannot store negative scales, so we have+ // to convert the number to the correct exponent+ // before storing.+ //+ // E.g. `Decimal(9, -3)` would be stored as+ // `Decimal(9000, 0)`.+ let (int, exp) = if exp < 0 {+ self_.with_scale(0).into_bigint_and_exponent()+ } else {+ (int, exp)+ };+ let value = int.to_i128().expect("Given BigDecimal overflowing the maximum accepted value.");++ let scale = u8::try_from(std::cmp::max(exp, 0))+ .expect("Given BigDecimal exponent overflowing the maximum accepted scale (255).");++ Numeric::new_with_scale(value, scale)+ });+ );+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn numeric_eq() {+ assert_eq!(+ Numeric {+ value: 100501,+ scale: 2+ },+ Numeric {+ value: 1005010,+ scale: 3+ }+ );+ assert!(+ Numeric {+ value: 100501,+ scale: 2+ } != Numeric {+ value: 10050,+ scale: 1+ }+ );+ }++ #[test]+ fn numeric_to_f64() {+ assert_eq!(f64::from(Numeric::new_with_scale(57705, 2)), 577.05);+ }++ #[test]+ fn numeric_to_int_dec_part() {+ let n = Numeric::new_with_scale(57705, 2);+ assert_eq!(n.int_part(), 577);+ assert_eq!(n.dec_part(), 5);+ }++ #[test]+ fn calculates_precision_correctly() {+ let n = Numeric::new_with_scale(57705, 2);+ assert_eq!(5, n.precision());+ }++ #[test]+ #[cfg(feature = "bigdecimal")]+ fn no_overflowing_pow() {+ use crate::{ColumnData, ToSql};+ use bigdecimal::FromPrimitive;++ let dec = BigDecimal::new(BigInt::from_i8(1).unwrap(), -20);+ let res = dec.to_sql();++ assert_eq!(+ ColumnData::Numeric(Some(Numeric::new_with_scale(100000000000000000000i128, 0))),+ res+ );+ }+}diff --git a/vendor/tiberius/src/tds/stream.rs b/vendor/tiberius/src/tds/stream.rsnew file mode 100644index 0000000000..e6454876b7--- /dev/null+++ b/vendor/tiberius/src/tds/stream.rs@@ -0,0 +1,5 @@+mod query;+mod token;++pub use query::*;+pub use token::*;diff --git a/vendor/tiberius/src/tds/stream/query.rs b/vendor/tiberius/src/tds/stream/query.rsnew file mode 100644index 0000000000..0dc694749d--- /dev/null+++ b/vendor/tiberius/src/tds/stream/query.rs@@ -0,0 +1,400 @@+use crate::tds::stream::ReceivedToken;+use crate::{row::ColumnType, Column, Row};+use futures_util::{+ ready,+ stream::{BoxStream, Peekable, Stream, StreamExt, TryStreamExt},+};+use std::{+ fmt::Debug,+ pin::Pin,+ sync::Arc,+ task::{self, Poll},+};++/// A set of `Streams` of [`QueryItem`] values, which can be either result+/// metadata or a row.+///+/// The `QueryStream` needs to be polled empty before sending another query to+/// the [`Client`], failing to do so causes a flush before the next query,+/// slowing it down in an undeterministic way.+///+/// Every stream starts with metadata, describing the structure of the incoming+/// rows, e.g. the columns in the order they are presented in every row.+///+/// If after consuming rows from the stream, another metadata result arrives, it+/// means the stream has multiple results from different queries. This new+/// metadata item will describe the next rows from here forwards.+///+/// If having one set of results in the response, using [`into_row_stream`]+/// might be more convenient to use.+///+/// The struct provides non-streaming APIs with [`into_results`],+/// [`into_first_result`] and [`into_row`].+///+/// # Example+///+/// ```+/// # use tiberius::{Config, QueryItem};+/// # use tokio_util::compat::TokioAsyncWriteCompatExt;+/// # use std::env;+/// # use futures_util::stream::TryStreamExt;+/// # #[tokio::main]+/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {+/// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+/// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+/// # );+/// # let config = Config::from_ado_string(&c_str)?;+/// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+/// # tcp.set_nodelay(true)?;+/// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+/// let mut stream = client+/// .query(+/// "SELECT @P1 AS first; SELECT @P2 AS second",+/// &[&1i32, &2i32],+/// )+/// .await?;+///+/// // The stream consists of four items, in the following order:+/// // - Metadata from `SELECT 1`+/// // - The only resulting row from `SELECT 1`+/// // - Metadata from `SELECT 2`+/// // - The only resulting row from `SELECT 2`+/// while let Some(item) = stream.try_next().await? {+/// match item {+/// // our first item is the column data always+/// QueryItem::Metadata(meta) if meta.result_index() == 0 => {+/// // the first result column info can be handled here+/// }+/// // ... and from there on from 0..N rows+/// QueryItem::Row(row) if row.result_index() == 0 => {+/// assert_eq!(Some(1), row.get(0));+/// }+/// // the second result set returns first another metadata item+/// QueryItem::Metadata(meta) => {+/// // .. handling+/// }+/// // ...and, again, we get rows from the second resultset+/// QueryItem::Row(row) => {+/// assert_eq!(Some(2), row.get(0));+/// }+/// }+/// }+/// # Ok(())+/// # }+/// ```+///+/// [`Client`]: struct.Client.html+/// [`into_row_stream`]: struct.QueryStream.html#method.into_row_stream+/// [`into_results`]: struct.QueryStream.html#method.into_results+/// [`into_first_result`]: struct.QueryStream.html#method.into_first_result+/// [`into_row`]: struct.QueryStream.html#method.into_row+pub struct QueryStream<'a> {+ token_stream: Peekable<BoxStream<'a, crate::Result<ReceivedToken>>>,+ columns: Option<Arc<Vec<Column>>>,+ result_set_index: Option<usize>,+}++impl<'a> Debug for QueryStream<'a> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("QueryStream")+ .field(+ "token_stream",+ &"BoxStream<'a, crate::Result<ReceivedToken>>",+ )+ .finish()+ }+}++impl<'a> QueryStream<'a> {+ pub(crate) fn new(token_stream: BoxStream<'a, crate::Result<ReceivedToken>>) -> Self {+ Self {+ token_stream: token_stream.peekable(),+ columns: None,+ result_set_index: None,+ }+ }++ /// Moves the stream forward until having result metadata, stream end or an+ /// error.+ pub(crate) async fn forward_to_metadata(&mut self) -> crate::Result<()> {+ loop {+ let item = Pin::new(&mut self.token_stream)+ .peek()+ .await+ .map(|r| r.as_ref().map_err(|e| e.clone()))+ .transpose()?;++ match item {+ Some(ReceivedToken::NewResultset(_)) => break,+ Some(_) => {+ self.token_stream.try_next().await?;+ }+ None => break,+ }+ }++ Ok(())+ }++ /// The list of columns either for the current result set, or for the next+ /// one. If the stream is just created, or if the next item in the stream+ /// contains metadata, the metadata will be taken from the stream. Otherwise+ /// the columns will be returned from the cache and reflect on the current+ /// result set.+ ///+ /// # Example+ ///+ /// ```+ /// # use tiberius::Config;+ /// # use tokio_util::compat::TokioAsyncWriteCompatExt;+ /// # use std::env;+ /// # use futures_util::stream::TryStreamExt;+ /// # #[tokio::main]+ /// # async fn main() -> anyhow::Result<()> {+ /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(+ /// # "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),+ /// # );+ /// # let config = Config::from_ado_string(&c_str)?;+ /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;+ /// # tcp.set_nodelay(true)?;+ /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;+ /// let mut stream = client+ /// .query(+ /// "SELECT @P1 AS first; SELECT @P2 AS second",+ /// &[&1i32, &2i32],+ /// )+ /// .await?;+ ///+ /// // Nothing is fetched, the first result set starts.+ /// let cols = stream.columns().await?.unwrap();+ /// assert_eq!("first", cols[0].name());+ ///+ /// // Move over the metadata.+ /// stream.try_next().await?;+ ///+ /// // We're in the first row, seeing the metadata for that set.+ /// let cols = stream.columns().await?.unwrap();+ /// assert_eq!("first", cols[0].name());+ ///+ /// // Move over the only row in the first set.+ /// stream.try_next().await?;+ ///+ /// // End of the first set, getting the metadata by peaking the next item.+ /// let cols = stream.columns().await?.unwrap();+ /// assert_eq!("second", cols[0].name());+ /// # Ok(())+ /// # }+ /// ```+ pub async fn columns(&mut self) -> crate::Result<Option<&[Column]>> {+ use ReceivedToken::*;++ loop {+ let item = Pin::new(&mut self.token_stream)+ .peek()+ .await+ .map(|r| r.as_ref().map_err(|e| e.clone()))+ .transpose()?;++ match item {+ Some(token) => match token {+ NewResultset(metadata) => {+ self.columns = Some(Arc::new(metadata.columns().collect()));+ break;+ }+ Row(_) => {+ break;+ }+ _ => {+ self.token_stream.try_next().await?;+ continue;+ }+ },+ None => {+ break;+ }+ }+ }++ Ok(self.columns.as_ref().map(|c| c.as_slice()))+ }++ /// Collects results from all queries in the stream into memory in the order+ /// of querying.+ pub async fn into_results(mut self) -> crate::Result<Vec<Vec<Row>>> {+ let mut results: Vec<Vec<Row>> = Vec::new();+ let mut result: Option<Vec<Row>> = None;++ while let Some(item) = self.try_next().await? {+ match (item, &mut result) {+ (QueryItem::Row(row), None) => {+ result = Some(vec![row]);+ }+ (QueryItem::Row(row), Some(ref mut result)) => result.push(row),+ (QueryItem::Metadata(_), None) => {+ result = Some(Vec::new());+ }+ (QueryItem::Metadata(_), ref mut previous_result) => {+ results.push(previous_result.take().unwrap());+ result = None;+ }+ }+ }++ if let Some(result) = result {+ results.push(result);+ }++ Ok(results)+ }++ /// Collects the output of the first query, dropping any further+ /// results.+ pub async fn into_first_result(self) -> crate::Result<Vec<Row>> {+ let mut results = self.into_results().await?.into_iter();+ let rows = results.next().unwrap_or_default();++ Ok(rows)+ }++ /// Collects the first row from the output of the first query, dropping any+ /// further rows.+ pub async fn into_row(self) -> crate::Result<Option<Row>> {+ let mut results = self.into_first_result().await?.into_iter();++ Ok(results.next())+ }++ /// Convert the stream into a stream of rows, skipping metadata items.+ pub fn into_row_stream(self) -> BoxStream<'a, crate::Result<Row>> {+ let s = self.try_filter_map(|item| async {+ match item {+ QueryItem::Row(row) => Ok(Some(row)),+ QueryItem::Metadata(_) => Ok(None),+ }+ });++ Box::pin(s)+ }+}++/// Info about the following stream of rows.+#[derive(Debug, Clone)]+pub struct ResultMetadata {+ columns: Arc<Vec<Column>>,+ result_index: usize,+}++impl ResultMetadata {+ /// Column info. The order is the same as in the following rows.+ pub fn columns(&self) -> &[Column] {+ &self.columns+ }++ /// The number of the result set, an incrementing value starting from zero,+ /// which gives an indication of the position of the result set in the+ /// stream.+ pub fn result_index(&self) -> usize {+ self.result_index+ }+}++/// Resulting data from a query.+#[derive(Debug)]+pub enum QueryItem {+ /// A single row of data.+ Row(Row),+ /// Information of the upcoming row data.+ Metadata(ResultMetadata),+}++impl QueryItem {+ pub(crate) fn metadata(columns: Arc<Vec<Column>>, result_index: usize) -> Self {+ Self::Metadata(ResultMetadata {+ columns,+ result_index,+ })+ }++ /// Returns a reference to the metadata, if the item is of a correct variant.+ pub fn as_metadata(&self) -> Option<&ResultMetadata> {+ match self {+ QueryItem::Row(_) => None,+ QueryItem::Metadata(ref metadata) => Some(metadata),+ }+ }++ /// Returns a reference to the row, if the item is of a correct variant.+ pub fn as_row(&self) -> Option<&Row> {+ match self {+ QueryItem::Row(ref row) => Some(row),+ QueryItem::Metadata(_) => None,+ }+ }++ /// Returns the metadata, if the item is of a correct variant.+ pub fn into_metadata(self) -> Option<ResultMetadata> {+ match self {+ QueryItem::Row(_) => None,+ QueryItem::Metadata(metadata) => Some(metadata),+ }+ }++ /// Returns the row, if the item is of a correct variant.+ pub fn into_row(self) -> Option<Row> {+ match self {+ QueryItem::Row(row) => Some(row),+ QueryItem::Metadata(_) => None,+ }+ }+}++impl<'a> Stream for QueryStream<'a> {+ type Item = crate::Result<QueryItem>;++ fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {+ let this = self.get_mut();++ loop {+ let token = match ready!(this.token_stream.poll_next_unpin(cx)) {+ Some(res) => res?,+ None => return Poll::Ready(None),+ };++ return match token {+ ReceivedToken::NewResultset(meta) => {+ let column_meta = meta+ .columns+ .iter()+ .map(|x| Column {+ name: x.col_name.to_string(),+ column_type: ColumnType::from(&x.base.ty),+ })+ .collect::<Vec<_>>();++ let column_meta = Arc::new(column_meta);+ this.columns = Some(column_meta.clone());++ this.result_set_index = this.result_set_index.map(|i| i + 1);++ let query_item =+ QueryItem::metadata(column_meta, *this.result_set_index.get_or_insert(0));++ return Poll::Ready(Some(Ok(query_item)));+ }+ ReceivedToken::Row(data) => {+ let columns = this.columns.as_ref().unwrap().clone();+ let result_index = this.result_set_index.unwrap();++ let row = Row {+ columns,+ data,+ result_index,+ };++ Poll::Ready(Some(Ok(QueryItem::Row(row))))+ }+ _ => continue,+ };+ }+ }+}diff --git a/vendor/tiberius/src/tds/stream/token.rs b/vendor/tiberius/src/tds/stream/token.rsnew file mode 100644index 0000000000..35ce0658b4--- /dev/null+++ b/vendor/tiberius/src/tds/stream/token.rs@@ -0,0 +1,258 @@+use crate::tds::codec::TokenSspi;+use crate::{+ client::Connection,+ tds::codec::{+ TokenColMetaData, TokenDone, TokenEnvChange, TokenError, TokenFeatureExtAck, TokenInfo,+ TokenLoginAck, TokenOrder, TokenReturnValue, TokenRow,+ },+ Error, SqlReadBytes, TokenType,+};+use futures_util::{+ io::{AsyncRead, AsyncWrite},+ stream::{BoxStream, TryStreamExt},+};+use std::{convert::TryFrom, sync::Arc};+use tracing::{event, Level};++#[derive(Debug)]+#[allow(dead_code)]+pub enum ReceivedToken {+ NewResultset(Arc<TokenColMetaData<'static>>),+ Row(TokenRow<'static>),+ Done(TokenDone),+ DoneInProc(TokenDone),+ DoneProc(TokenDone),+ ReturnStatus(u32),+ ReturnValue(TokenReturnValue),+ Order(TokenOrder),+ EnvChange(TokenEnvChange),+ Info(TokenInfo),+ LoginAck(TokenLoginAck),+ Sspi(TokenSspi),+ FeatureExtAck(TokenFeatureExtAck),+ Error(TokenError),+}++pub(crate) struct TokenStream<'a, S: AsyncRead + AsyncWrite + Unpin + Send> {+ conn: &'a mut Connection<S>,+ last_error: Option<Error>,+}++impl<'a, S> TokenStream<'a, S>+where+ S: AsyncRead + AsyncWrite + Unpin + Send,+{+ pub(crate) fn new(conn: &'a mut Connection<S>) -> Self {+ Self {+ conn,+ last_error: None,+ }+ }++ pub(crate) async fn flush_done(self) -> crate::Result<TokenDone> {+ let mut stream = self.try_unfold();+ let mut last_error = None;+ let mut routing = None;++ loop {+ match stream.try_next().await? {+ Some(ReceivedToken::Error(error)) => {+ if last_error.is_none() {+ last_error = Some(error);+ }+ }+ Some(ReceivedToken::Done(token)) => match (last_error, routing) {+ (Some(error), _) => return Err(Error::Server(error)),+ (_, Some(routing)) => return Err(routing),+ (_, _) => return Ok(token),+ },+ Some(ReceivedToken::EnvChange(TokenEnvChange::Routing { host, port })) => {+ routing = Some(Error::Routing { host, port });+ }+ Some(_) => (),+ None => return Err(crate::Error::Protocol("Never got DONE token.".into())),+ }+ }+ }++ #[cfg(any(windows, feature = "integrated-auth-gssapi"))]+ pub(crate) async fn flush_sspi(self) -> crate::Result<TokenSspi> {+ let mut stream = self.try_unfold();+ let mut last_error = None;++ loop {+ match stream.try_next().await? {+ Some(ReceivedToken::Error(error)) => {+ if last_error.is_none() {+ last_error = Some(error);+ }+ }+ Some(ReceivedToken::Sspi(token)) => return Ok(token),+ Some(_) => (),+ None => match last_error {+ Some(err) => return Err(crate::Error::Server(err)),+ None => return Err(crate::Error::Protocol("Never got SSPI token.".into())),+ },+ }+ }+ }++ async fn get_col_metadata(&mut self) -> crate::Result<ReceivedToken> {+ let meta = Arc::new(TokenColMetaData::decode(self.conn).await?);+ self.conn.context_mut().set_last_meta(meta.clone());++ event!(Level::TRACE, ?meta);++ Ok(ReceivedToken::NewResultset(meta))+ }++ async fn get_row(&mut self) -> crate::Result<ReceivedToken> {+ let return_value = TokenRow::decode(self.conn).await?;++ event!(Level::TRACE, message = ?return_value);+ Ok(ReceivedToken::Row(return_value))+ }++ async fn get_nbc_row(&mut self) -> crate::Result<ReceivedToken> {+ let return_value = TokenRow::decode_nbc(self.conn).await?;++ event!(Level::TRACE, message = ?return_value);+ Ok(ReceivedToken::Row(return_value))+ }++ async fn get_return_value(&mut self) -> crate::Result<ReceivedToken> {+ let return_value = TokenReturnValue::decode(self.conn).await?;+ event!(Level::TRACE, message = ?return_value);+ Ok(ReceivedToken::ReturnValue(return_value))+ }++ async fn get_return_status(&mut self) -> crate::Result<ReceivedToken> {+ let status = self.conn.read_u32_le().await?;+ Ok(ReceivedToken::ReturnStatus(status))+ }++ async fn get_error(&mut self) -> crate::Result<ReceivedToken> {+ let err = TokenError::decode(self.conn).await?;++ if self.last_error.is_none() {+ self.last_error = Some(Error::Server(err.clone()));+ }++ event!(Level::ERROR, message = %err.message, code = err.code);+ Ok(ReceivedToken::Error(err))+ }++ async fn get_order(&mut self) -> crate::Result<ReceivedToken> {+ let order = TokenOrder::decode(self.conn).await?;+ event!(Level::TRACE, message = ?order);+ Ok(ReceivedToken::Order(order))+ }++ async fn get_done_value(&mut self) -> crate::Result<ReceivedToken> {+ let done = TokenDone::decode(self.conn).await?;+ event!(Level::TRACE, "{}", done);+ Ok(ReceivedToken::Done(done))+ }++ async fn get_done_proc_value(&mut self) -> crate::Result<ReceivedToken> {+ let done = TokenDone::decode(self.conn).await?;+ event!(Level::TRACE, "{}", done);+ Ok(ReceivedToken::DoneProc(done))+ }++ async fn get_done_in_proc_value(&mut self) -> crate::Result<ReceivedToken> {+ let done = TokenDone::decode(self.conn).await?;+ event!(Level::TRACE, "{}", done);+ Ok(ReceivedToken::DoneInProc(done))+ }++ async fn get_env_change(&mut self) -> crate::Result<ReceivedToken> {+ let change = TokenEnvChange::decode(self.conn).await?;++ match change {+ TokenEnvChange::PacketSize(new_size, _) => {+ self.conn.context_mut().set_packet_size(new_size);+ }+ TokenEnvChange::BeginTransaction(desc) => {+ self.conn.context_mut().set_transaction_descriptor(desc);+ }+ TokenEnvChange::CommitTransaction+ | TokenEnvChange::RollbackTransaction+ | TokenEnvChange::DefectTransaction => {+ self.conn.context_mut().set_transaction_descriptor([0; 8]);+ }+ _ => (),+ }++ event!(Level::INFO, "{}", change);++ Ok(ReceivedToken::EnvChange(change))+ }++ async fn get_info(&mut self) -> crate::Result<ReceivedToken> {+ let info = TokenInfo::decode(self.conn).await?;+ event!(Level::INFO, "{}", info.message);+ Ok(ReceivedToken::Info(info))+ }++ async fn get_login_ack(&mut self) -> crate::Result<ReceivedToken> {+ let ack = TokenLoginAck::decode(self.conn).await?;+ event!(Level::INFO, "{} version {}", ack.prog_name, ack.version);+ Ok(ReceivedToken::LoginAck(ack))+ }++ async fn get_feature_ext_ack(&mut self) -> crate::Result<ReceivedToken> {+ let ack = TokenFeatureExtAck::decode(self.conn).await?;+ event!(+ Level::INFO,+ "FeatureExtAck with {} features",+ ack.features.len()+ );+ Ok(ReceivedToken::FeatureExtAck(ack))+ }++ async fn get_sspi(&mut self) -> crate::Result<ReceivedToken> {+ let sspi = TokenSspi::decode_async(self.conn).await?;+ event!(Level::TRACE, "SSPI response");+ Ok(ReceivedToken::Sspi(sspi))+ }++ pub fn try_unfold(self) -> BoxStream<'a, crate::Result<ReceivedToken>> {+ let stream = futures_util::stream::try_unfold(self, |mut this| async move {+ if this.conn.is_eof() {+ match this.last_error {+ None => return Ok(None),+ Some(error) => return Err(error),+ }+ }++ let ty_byte = this.conn.read_u8().await?;++ let ty = TokenType::try_from(ty_byte)+ .map_err(|_| Error::Protocol(format!("invalid token type {:x}", ty_byte).into()))?;++ let token = match ty {+ TokenType::ReturnStatus => this.get_return_status().await?,+ TokenType::ColMetaData => this.get_col_metadata().await?,+ TokenType::Row => this.get_row().await?,+ TokenType::NbcRow => this.get_nbc_row().await?,+ TokenType::Done => this.get_done_value().await?,+ TokenType::DoneProc => this.get_done_proc_value().await?,+ TokenType::DoneInProc => this.get_done_in_proc_value().await?,+ TokenType::ReturnValue => this.get_return_value().await?,+ TokenType::Error => this.get_error().await?,+ TokenType::Order => this.get_order().await?,+ TokenType::EnvChange => this.get_env_change().await?,+ TokenType::Info => this.get_info().await?,+ TokenType::LoginAck => this.get_login_ack().await?,+ TokenType::Sspi => this.get_sspi().await?,+ TokenType::FeatureExtAck => this.get_feature_ext_ack().await?,+ _ => panic!("Token {:?} unimplemented!", ty),+ };++ Ok(Some((token, this)))+ });++ Box::pin(stream)+ }+}diff --git a/vendor/tiberius/src/tds/time.rs b/vendor/tiberius/src/tds/time.rsnew file mode 100644index 0000000000..05a1c053c2--- /dev/null+++ b/vendor/tiberius/src/tds/time.rs@@ -0,0 +1,436 @@+//! Date and time handling.+//!+//! When using the `tds73` feature flag together with SQL Server 2008 or later,+//! the following [`time`] mappings to and from the database are available:+//!+//! - `Time` -> [`Time`](time/struct.Time.html)+//! - `Date` -> [`Date`]+//! - `DateTime` -> [`PrimitiveDateTime`]+//! - `DateTime2` -> [`PrimitiveDateTime`]+//! - `SmallDateTime` -> [`PrimitiveDateTime`]+//! - `DateTimeOffset` -> [`OffsetDateTime`]+//!+//! With SQL Server 2005 and the `tds73` feature flag disabled, the mapping is+//! different:+//!+//! - `DateTime` -> [`PrimitiveDateTime`]+//! - `SmallDateTime` -> [`PrimitiveDateTime`]+//!+//! [`time`]: time/index.html+//! [`Date`]: time/struct.Date.html+//! [`PrimitiveDateTime`]: time/struct.PrimitiveDateTime.html+//! [`OffsetDateTime`]: time/struct.OffsetDateTime.html++#[cfg(feature = "chrono")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "chrono")))]+pub mod chrono;++#[cfg(feature = "time")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "time")))]+pub mod time;++use crate::{tds::codec::Encode, SqlReadBytes};+#[cfg(feature = "tds73")]+use byteorder::{ByteOrder, LittleEndian};+use bytes::{BufMut, BytesMut};+#[cfg(feature = "tds73")]+use futures_util::io::AsyncReadExt;++/// A presentation of `datetime` type in the server.+///+/// # Warning+///+/// It isn't recommended to use this type directly. For dealing with `datetime`,+/// use the `time` feature of this crate and its `PrimitiveDateTime` type.+#[derive(Copy, Clone, Debug, Eq, PartialEq)]+pub struct DateTime {+ days: i32,+ seconds_fragments: u32,+}++impl DateTime {+ /// Construct a new `DateTime` instance.+ pub fn new(days: i32, seconds_fragments: u32) -> Self {+ Self {+ days,+ seconds_fragments,+ }+ }++ /// Days since 1st of January, 1900 (including the negative range until 1st+ /// of January, 1753).+ pub fn days(self) -> i32 {+ self.days+ }++ /// 1/300 of a second, so a value of 300 equals 1 second (since midnight).+ pub fn seconds_fragments(self) -> u32 {+ self.seconds_fragments+ }++ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let days = src.read_i32_le().await?;+ let seconds_fragments = src.read_u32_le().await?;++ Ok(Self {+ days,+ seconds_fragments,+ })+ }+}++impl Encode<BytesMut> for DateTime {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_i32_le(self.days);+ dst.put_u32_le(self.seconds_fragments);++ Ok(())+ }+}++/// A presentation of `smalldatetime` type in the server.+///+/// # Warning+///+/// It isn't recommended to use this type directly. For dealing with+/// `smalldatetime`, use the `time` feature of this crate and its+/// `PrimitiveDateTime` type.+#[derive(Copy, Clone, Debug, Eq, PartialEq)]+pub struct SmallDateTime {+ days: u16,+ seconds_fragments: u16,+}++impl SmallDateTime {+ /// Construct a new `SmallDateTime` instance.+ pub fn new(days: u16, seconds_fragments: u16) -> Self {+ Self {+ days,+ seconds_fragments,+ }+ }+ /// Days since 1st of January, 1900.+ pub fn days(self) -> u16 {+ self.days+ }++ /// 1/300 of a second, so a value of 300 equals 1 second (since midnight)+ pub fn seconds_fragments(self) -> u16 {+ self.seconds_fragments+ }++ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let days = src.read_u16_le().await?;+ let seconds_fragments = src.read_u16_le().await?;++ Ok(Self {+ days,+ seconds_fragments,+ })+ }+}++impl Encode<BytesMut> for SmallDateTime {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ dst.put_u16_le(self.days);+ dst.put_u16_le(self.seconds_fragments);++ Ok(())+ }+}++/// A presentation of `date` type in the server.+///+/// # Warning+///+/// It isn't recommended to use this type directly. If you want to deal with+/// `date`, use the `time` feature of this crate and its `Date` type.+#[derive(Copy, Clone, Debug, Eq, PartialEq)]+#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+pub struct Date(u32);++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl Date {+ #[inline]+ /// Construct a new `Date`+ ///+ /// # Panics+ /// max value of 3 bytes (`u32::max_value() > 8`)+ pub fn new(days: u32) -> Date {+ assert_eq!(days >> 24, 0);+ Date(days)+ }++ #[inline]+ /// The number of days from 1st of January, year 1.+ pub fn days(self) -> u32 {+ self.0+ }++ pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let mut bytes = [0u8; 4];+ src.read_exact(&mut bytes[..3]).await?;+ Ok(Self::new(LittleEndian::read_u32(&bytes)))+ }+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl Encode<BytesMut> for Date {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ let mut tmp = [0u8; 4];+ LittleEndian::write_u32(&mut tmp, self.days());+ assert_eq!(tmp[3], 0);+ dst.extend_from_slice(&tmp[0..3]);++ Ok(())+ }+}++/// A presentation of `time` type in the server.+///+/// # Warning+///+/// It isn't recommended to use this type directly. If you want to deal with+/// `time`, use the `time` feature of this crate and its `Time` type.+#[derive(Copy, Clone, Debug)]+#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+pub struct Time {+ increments: u64,+ scale: u8,+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl PartialEq for Time {+ fn eq(&self, t: &Time) -> bool {+ self.increments as f64 / 10f64.powi(self.scale as i32)+ == t.increments as f64 / 10f64.powi(t.scale as i32)+ }+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl Time {+ /// Construct a new `Time`+ pub fn new(increments: u64, scale: u8) -> Self {+ Self { increments, scale }+ }++ #[inline]+ /// Number of 10^-n second increments since midnight, where `n` is defined+ /// in [`scale`].+ ///+ /// [`scale`]: #method.scale+ pub fn increments(self) -> u64 {+ self.increments+ }++ #[inline]+ /// The accuracy of the increments.+ pub fn scale(self) -> u8 {+ self.scale+ }++ #[inline]+ /// Length of the field in number of bytes.+ pub(crate) fn len(self) -> crate::Result<u8> {+ Ok(match self.scale {+ 0..=2 => 3,+ 3..=4 => 4,+ 5..=7 => 5,+ _ => {+ return Err(crate::Error::Protocol(+ format!("timen: invalid scale {}", self.scale).into(),+ ))+ }+ })+ }++ pub(crate) async fn decode<R>(src: &mut R, n: usize, rlen: usize) -> crate::Result<Time>+ where+ R: SqlReadBytes + Unpin,+ {+ let val = match (n, rlen) {+ (0..=2, 3) => {+ let hi = src.read_u16_le().await? as u64;+ let lo = src.read_u8().await? as u64;++ hi | lo << 16+ }+ (3..=4, 4) => src.read_u32_le().await? as u64,+ (5..=7, 5) => {+ let hi = src.read_u32_le().await? as u64;+ let lo = src.read_u8().await? as u64;++ hi | lo << 32+ }+ _ => {+ return Err(crate::Error::Protocol(+ format!("timen: invalid length {}", n).into(),+ ))+ }+ };++ Ok(Time {+ increments: val,+ scale: n as u8,+ })+ }+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl Encode<BytesMut> for Time {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ match self.len()? {+ 3 => {+ assert_eq!(self.increments >> 24, 0);+ dst.put_u16_le(self.increments as u16);+ dst.put_u8((self.increments >> 16) as u8);+ }+ 4 => {+ assert_eq!(self.increments >> 32, 0);+ dst.put_u32_le(self.increments as u32);+ }+ 5 => {+ assert_eq!(self.increments >> 40, 0);+ dst.put_u32_le(self.increments as u32);+ dst.put_u8((self.increments >> 32) as u8);+ }+ _ => unreachable!(),+ }++ Ok(())+ }+}++#[derive(Copy, Clone, Debug, PartialEq)]+#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+/// A presentation of `datetime2` type in the server.+///+/// # Warning+///+/// It isn't recommended to use this type directly. For dealing with+/// `datetime2`, use the `time` feature of this crate and its `PrimitiveDateTime`+/// type.+pub struct DateTime2 {+ date: Date,+ time: Time,+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl DateTime2 {+ /// Construct a new `DateTime2` from the date and time components.+ pub fn new(date: Date, time: Time) -> Self {+ Self { date, time }+ }++ /// The date component.+ pub fn date(self) -> Date {+ self.date+ }++ /// The time component.+ pub fn time(self) -> Time {+ self.time+ }++ pub(crate) async fn decode<R>(src: &mut R, n: usize, rlen: usize) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let time = Time::decode(src, n, rlen).await?;++ let mut bytes = [0u8; 4];+ src.read_exact(&mut bytes[..3]).await?;+ let date = Date::new(LittleEndian::read_u32(&bytes));++ Ok(Self::new(date, time))+ }+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl Encode<BytesMut> for DateTime2 {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ self.time.encode(dst)?;++ let mut tmp = [0u8; 4];+ LittleEndian::write_u32(&mut tmp, self.date.days());+ assert_eq!(tmp[3], 0);+ dst.extend_from_slice(&tmp[0..3]);++ Ok(())+ }+}++#[derive(Copy, Clone, Debug, PartialEq)]+#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+/// A presentation of `datetimeoffset` type in the server.+///+/// # Warning+///+/// It isn't recommended to use this type directly. For dealing with+/// `datetimeoffset`, use the `time` feature of this crate and its `OffsetDateTime`+/// type with the correct timezone.+pub struct DateTimeOffset {+ datetime2: DateTime2,+ offset: i16,+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl DateTimeOffset {+ /// Construct a new `DateTimeOffset` from a `datetime2`, offset marking+ /// number of minutes from UTC.+ pub fn new(datetime2: DateTime2, offset: i16) -> Self {+ Self { datetime2, offset }+ }++ /// The date and time part.+ pub fn datetime2(self) -> DateTime2 {+ self.datetime2+ }++ /// Number of minutes from UTC.+ pub fn offset(self) -> i16 {+ self.offset+ }++ pub(crate) async fn decode<R>(src: &mut R, n: usize, rlen: u8) -> crate::Result<Self>+ where+ R: SqlReadBytes + Unpin,+ {+ let datetime2 = DateTime2::decode(src, n, rlen as usize).await?;+ let offset = src.read_i16_le().await?;++ Ok(Self { datetime2, offset })+ }+}++#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+impl Encode<BytesMut> for DateTimeOffset {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ self.datetime2.encode(dst)?;+ dst.put_i16_le(self.offset);++ Ok(())+ }+}diff --git a/vendor/tiberius/src/tds/time/chrono.rs b/vendor/tiberius/src/tds/time/chrono.rsnew file mode 100644index 0000000000..f6de500122--- /dev/null+++ b/vendor/tiberius/src/tds/time/chrono.rs@@ -0,0 +1,243 @@+//! Mappings between TDS and and Chrono types (with `chrono` feature flag+//! enabled).+//!+//! The chrono library offers better ergonomy, but is known to hold certain+//! security vulnerabilities. The code here is for legacy purposes, please use+//! `time` crate for greenfield projects.++#[cfg(not(feature = "tds73"))]+use super::DateTime as DateTime1;+#[cfg(feature = "tds73")]+use super::{Date, DateTime2, DateTimeOffset, Time};+use crate::tds::codec::ColumnData;+#[cfg(feature = "tds73")]+#[cfg_attr(feature = "docs", doc(cfg(feature = "tds73")))]+pub use chrono::offset::{FixedOffset, Utc};+pub use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};+#[cfg(feature = "tds73")]+use std::ops::Sub;++#[inline]+fn from_days(days: i64, start_year: i32) -> NaiveDate {+ NaiveDate::from_ymd_opt(start_year, 1, 1).unwrap() + chrono::Duration::days(days)+}++#[inline]+fn from_sec_fragments(sec_fragments: i64) -> NaiveTime {+ NaiveTime::from_hms_opt(0, 0, 0).unwrap()+ + chrono::Duration::nanoseconds(sec_fragments * (1e9 as i64) / 300)+}++#[inline]+#[cfg(feature = "tds73")]+fn from_mins(mins: u32) -> NaiveTime {+ NaiveTime::from_num_seconds_from_midnight_opt(mins, 0).unwrap()+}++#[inline]+fn to_days(date: NaiveDate, start_year: i32) -> i64 {+ date.signed_duration_since(NaiveDate::from_ymd_opt(start_year, 1, 1).unwrap())+ .num_days()+}++#[inline]+#[cfg(not(feature = "tds73"))]+fn to_sec_fragments(time: NaiveTime) -> i64 {+ time.signed_duration_since(NaiveTime::from_hms_opt(0, 0, 0).unwrap())+ .num_nanoseconds()+ .unwrap()+ * 300+ / (1e9 as i64)+}++#[cfg(feature = "tds73")]+from_sql!(+ NaiveDateTime:+ ColumnData::SmallDateTime(ref dt) => dt.map(|dt| NaiveDateTime::new(+ from_days(dt.days as i64, 1900),+ from_mins(dt.seconds_fragments as u32 * 60),+ )),+ ColumnData::DateTime2(ref dt) => dt.map(|dt| NaiveDateTime::new(+ from_days(dt.date.days() as i64, 1),+ NaiveTime::from_hms_opt(0,0,0).unwrap() + chrono::Duration::nanoseconds(dt.time.increments as i64 * 10i64.pow(9 - dt.time.scale as u32))+ )),+ ColumnData::DateTime(ref dt) => dt.map(|dt| NaiveDateTime::new(+ from_days(dt.days as i64, 1900),+ from_sec_fragments(dt.seconds_fragments as i64)+ ));+ NaiveTime:+ ColumnData::Time(ref time) => time.map(|time| {+ let ns = time.increments as i64 * 10i64.pow(9 - time.scale as u32);+ NaiveTime::from_hms_opt(0,0,0).unwrap() + chrono::Duration::nanoseconds(ns)+ });+ NaiveDate:+ ColumnData::Date(ref date) => date.map(|date| from_days(date.days() as i64, 1));+ chrono::DateTime<Utc>:+ ColumnData::DateTimeOffset(ref dto) => dto.map(|dto| {+ let date = from_days(dto.datetime2.date.days() as i64, 1);+ let ns = dto.datetime2.time.increments as i64 * 10i64.pow(9 - dto.datetime2.time.scale as u32);+ let time = NaiveTime::from_hms_opt(0,0,0).unwrap() + chrono::Duration::nanoseconds(ns);++ let offset = chrono::Duration::minutes(dto.offset as i64);+ let naive = NaiveDateTime::new(date, time).sub(offset);++ chrono::DateTime::from_naive_utc_and_offset(naive, Utc)+ }),+ ColumnData::DateTime2(ref dt2) => dt2.map(|dt2| {+ let date = from_days(dt2.date.days() as i64, 1);+ let ns = dt2.time.increments as i64 * 10i64.pow(9 - dt2.time.scale as u32);+ let time = NaiveTime::from_hms_opt(0,0,0).unwrap() + chrono::Duration::nanoseconds(ns);+ let naive = NaiveDateTime::new(date, time);++ chrono::DateTime::from_naive_utc_and_offset(naive, Utc)+ });+ chrono::DateTime<FixedOffset>: ColumnData::DateTimeOffset(ref dto) => dto.map(|dto| {+ let date = from_days(dto.datetime2.date.days() as i64, 1);+ let ns = dto.datetime2.time.increments as i64 * 10i64.pow(9 - dto.datetime2.time.scale as u32);+ let time = NaiveTime::from_hms_opt(0,0,0).unwrap() + chrono::Duration::nanoseconds(ns);++ let offset = FixedOffset::east_opt((dto.offset as i32) * 60).unwrap();+ let naive = NaiveDateTime::new(date, time);++ chrono::DateTime::from_naive_utc_and_offset(naive, offset)+ })+);++#[cfg(feature = "tds73")]+to_sql!(self_,+ NaiveDate: (ColumnData::Date, Date::new(to_days(*self_, 1) as u32));+ NaiveTime: (ColumnData::Time, {+ use chrono::Timelike;++ let nanos = self_.num_seconds_from_midnight() as u64 * 1e9 as u64 + self_.nanosecond() as u64;+ let increments = nanos / 100;++ Time {increments, scale: 7}+ });+ NaiveDateTime: (ColumnData::DateTime2, {+ use chrono::Timelike;++ let time = self_.time();+ let nanos = time.num_seconds_from_midnight() as u64 * 1e9 as u64 + time.nanosecond() as u64;+ let increments = nanos / 100;++ let date = Date::new(to_days(self_.date(), 1) as u32);+ let time = Time {increments, scale: 7};++ DateTime2::new(date, time)+ });+ chrono::DateTime<Utc>: (ColumnData::DateTime2, {+ use chrono::Timelike;++ let naive = self_.naive_utc();+ let time = naive.time();+ let nanos = time.num_seconds_from_midnight() as u64 * 1e9 as u64 + time.nanosecond() as u64;++ let date = Date::new(to_days(naive.date(), 1) as u32);+ let time = Time {increments: nanos / 100, scale: 7};++ DateTime2::new(date, time)+ });+ chrono::DateTime<FixedOffset>: (ColumnData::DateTimeOffset, {+ use chrono::Timelike;++ let naive = self_.naive_utc();+ let time = naive.time();+ let nanos = time.num_seconds_from_midnight() as u64 * 1e9 as u64 + time.nanosecond() as u64;++ let date = Date::new(to_days(naive.date(), 1) as u32);+ let time = Time { increments: nanos / 100, scale: 7 };++ let tz = self_.timezone();+ let offset = (tz.local_minus_utc() / 60) as i16;++ DateTimeOffset::new(DateTime2::new(date, time), offset)+ });+);++#[cfg(feature = "tds73")]+into_sql!(self_,+ NaiveDate: (ColumnData::Date, Date::new(to_days(self_, 1) as u32));+ NaiveTime: (ColumnData::Time, {+ use chrono::Timelike;++ let nanos = self_.num_seconds_from_midnight() as u64 * 1e9 as u64 + self_.nanosecond() as u64;+ let increments = nanos / 100;++ Time {increments, scale: 7}+ });+ NaiveDateTime: (ColumnData::DateTime2, {+ use chrono::Timelike;++ let time = self_.time();+ let nanos = time.num_seconds_from_midnight() as u64 * 1e9 as u64 + time.nanosecond() as u64;+ let increments = nanos / 100;++ let date = Date::new(to_days(self_.date(), 1) as u32);+ let time = Time {increments, scale: 7};++ DateTime2::new(date, time)+ });+ chrono::DateTime<Utc>: (ColumnData::DateTime2, {+ use chrono::Timelike;++ let naive = self_.naive_utc();+ let time = naive.time();+ let nanos = time.num_seconds_from_midnight() as u64 * 1e9 as u64 + time.nanosecond() as u64;++ let date = Date::new(to_days(naive.date(), 1) as u32);+ let time = Time {increments: nanos / 100, scale: 7};++ DateTime2::new(date, time)+ });+ chrono::DateTime<FixedOffset>: (ColumnData::DateTimeOffset, {+ use chrono::Timelike;++ let naive = self_.naive_utc();+ let time = naive.time();+ let nanos = time.num_seconds_from_midnight() as u64 * 1e9 as u64 + time.nanosecond() as u64;++ let date = Date::new(to_days(naive.date(), 1) as u32);+ let time = Time { increments: nanos / 100, scale: 7 };++ let tz = self_.timezone();+ let offset = (tz.local_minus_utc() / 60) as i16;++ DateTimeOffset::new(DateTime2::new(date, time), offset)+ });+);++#[cfg(not(feature = "tds73"))]+to_sql!(self_,+ NaiveDateTime: (ColumnData::DateTime, {+ let date = self_.date();+ let time = self_.time();++ let days = to_days(date, 1900) as i32;+ let seconds_fragments = to_sec_fragments(time);++ DateTime1::new(days, seconds_fragments as u32)+ });+);++#[cfg(not(feature = "tds73"))]+into_sql!(self_,+ NaiveDateTime: (ColumnData::DateTime, {+ let date = self_.date();+ let time = self_.time();++ let days = to_days(date, 1900) as i32;+ let seconds_fragments = to_sec_fragments(time);++ DateTime1::new(days, seconds_fragments as u32)+ });+);++#[cfg(not(feature = "tds73"))]+from_sql!(+ NaiveDateTime:+ ColumnData::DateTime(ref dt) => dt.map(|dt| NaiveDateTime::new(+ from_days(dt.days as i64, 1900),+ from_sec_fragments(dt.seconds_fragments as i64)+ ))+);diff --git a/vendor/tiberius/src/tds/time/time.rs b/vendor/tiberius/src/tds/time/time.rsnew file mode 100644index 0000000000..5a2b1cfaa6--- /dev/null+++ b/vendor/tiberius/src/tds/time/time.rs@@ -0,0 +1,134 @@+//! Mappings between TDS and and time crate types (with `time` feature flag+//! enabled).+//!+//! The time library offers better ergonomy and are highly recommended if+//! needing to modify and deal with date and time in SQL Server.++use std::time::Duration;+pub use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};++use crate::tds::codec::ColumnData;++#[inline]+fn from_days(days: u64, start_year: i32) -> Date {+ Date::from_calendar_date(start_year, Month::January, 1).unwrap()+ + Duration::from_secs(60 * 60 * 24 * days)+}++#[inline]+#[cfg(feature = "tds73")]+fn from_secs(secs: u64) -> Time {+ Time::from_hms(0, 0, 0).unwrap() + Duration::from_secs(secs)+}++#[inline]+fn from_sec_fragments(sec_fragments: u64) -> Time {+ Time::from_hms(0, 0, 0).unwrap() + Duration::from_nanos(sec_fragments * (1e9 as u64) / 300)+}++#[inline]+fn to_days(date: Date, start_year: i32) -> i64 {+ (date - Date::from_calendar_date(start_year, Month::January, 1).unwrap()).whole_days()+}++#[inline]+#[cfg(not(feature = "tds73"))]+fn to_sec_fragments(from: Time) -> i64 {+ let nanos: i64 = (from - Time::from_hms(0, 0, 0).unwrap())+ .whole_nanoseconds()+ .try_into()+ .unwrap();++ nanos * 300 / (1e9 as i64)+}++#[cfg(feature = "tds73")]+from_sql!(+ PrimitiveDateTime:+ ColumnData::SmallDateTime(ref dt) => dt.map(|dt| PrimitiveDateTime::new(+ from_days(dt.days as u64, 1900),+ from_secs(dt.seconds_fragments as u64 * 60),+ )),+ ColumnData::DateTime2(ref dt) => dt.map(|dt| PrimitiveDateTime::new(+ from_days(dt.date.days() as u64, 1),+ Time::from_hms(0,0,0).unwrap() + Duration::from_nanos(dt.time.increments * 10u64.pow(9 - dt.time.scale as u32))+ )),+ ColumnData::DateTime(ref dt) => dt.map(|dt| PrimitiveDateTime::new(+ from_days(dt.days as u64, 1900),+ from_sec_fragments(dt.seconds_fragments as u64)+ ));+ Time:+ ColumnData::Time(ref time) => time.map(|time| {+ let ns = time.increments * 10u64.pow(9 - time.scale as u32);+ Time::from_hms(0,0,0).unwrap() + Duration::from_nanos(ns)+ });+ Date:+ ColumnData::Date(ref date) => date.map(|date| from_days(date.days() as u64, 1));+ OffsetDateTime:+ ColumnData::DateTimeOffset(ref dto) => dto.map(|dto| {+ let date = from_days(dto.datetime2.date.days() as u64, 1);+ let dt = dto.datetime2;++ let time = Time::from_hms(0,0,0).unwrap()+ + Duration::from_nanos(dt.time.increments * 10u64.pow(9 - dt.time.scale as u32));++ let offset = UtcOffset::from_whole_seconds(dto.offset as i32 * 60).unwrap();++ date.with_time(time).assume_utc().to_offset(offset)+ })+);++#[cfg(feature = "tds73")]+to_sql!(self_,+ Date: (ColumnData::Date, super::Date::new(to_days(*self_, 1) as u32));+ Time: (ColumnData::Time, {+ let nanos: u64 = (*self_ - Time::from_hms(0, 0, 0).unwrap()).whole_nanoseconds().try_into().unwrap();+ let increments = nanos / 100;++ super::Time {increments, scale: 7}+ });+ PrimitiveDateTime: (ColumnData::DateTime2, {+ let time = self_.time();+ let nanos: u64 = (time - Time::from_hms(0, 0, 0).unwrap()).whole_nanoseconds().try_into().unwrap();+ let increments = nanos / 100;++ let date = super::Date::new(to_days(self_.date(), 1) as u32);+ let time = super::Time {increments, scale: 7};++ super::DateTime2::new(date, time)+ });+ OffsetDateTime: (ColumnData::DateTimeOffset, {+ let tz = self_.offset();+ let offset = (tz.whole_seconds() / 60) as i16;++ let utc_date = self_.to_offset(UtcOffset::UTC);++ let nanos: u64 = (utc_date.time() - Time::from_hms(0, 0, 0).unwrap()).whole_nanoseconds().try_into().unwrap();++ let date = super::Date::new(to_days(utc_date.date(), 1) as u32);+ let time = super::Time { increments: nanos / 100, scale: 7 };++ super::DateTimeOffset::new(super::DateTime2::new(date, time), offset)+ });+);++#[cfg(not(feature = "tds73"))]+to_sql!(self_,+ PrimitiveDateTime: (ColumnData::DateTime, {+ let date = self_.date();+ let time = self_.time();++ let days = to_days(date, 1900) as i32;+ let seconds_fragments = to_sec_fragments(time);++ super::DateTime::new(days, seconds_fragments as u32)+ });+);++#[cfg(not(feature = "tds73"))]+from_sql!(+ PrimitiveDateTime:+ ColumnData::DateTime(ref dt) => dt.map(|dt| {+ from_days(dt.days as u64, 1900).with_time(from_sec_fragments(dt.seconds_fragments as u64))+ })+);diff --git a/vendor/tiberius/src/tds/xml.rs b/vendor/tiberius/src/tds/xml.rsnew file mode 100644index 0000000000..242be05f35--- /dev/null+++ b/vendor/tiberius/src/tds/xml.rs@@ -0,0 +1,117 @@+//! The XML containers+use super::codec::Encode;+use bytes::{BufMut, BytesMut};+use std::borrow::BorrowMut;+use std::sync::Arc;++/// Provides information of the location for the schema.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct XmlSchema {+ db_name: String,+ owner: String,+ collection: String,+}++impl XmlSchema {+ pub(crate) fn new(+ db_name: impl ToString,+ owner: impl ToString,+ collection: impl ToString,+ ) -> Self {+ Self {+ db_name: db_name.to_string(),+ owner: owner.to_string(),+ collection: collection.to_string(),+ }+ }++ /// Specifies the name of the database where the schema collection is defined.+ pub fn db_name(&self) -> &str {+ &self.db_name+ }++ /// Specifies the name of the relational schema containing the schema collection.+ pub fn owner(&self) -> &str {+ &self.owner+ }++ /// Specifies the name of the XML schema collection to which the type is+ /// bound.+ pub fn collection(&self) -> &str {+ &self.collection+ }+}++/// A representation of XML data in TDS. Holds the data as a UTF-8 string and+/// and optional information about the schema.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct XmlData {+ data: String,+ schema: Option<Arc<XmlSchema>>,+}++impl XmlData {+ /// Create a new XmlData with the given string. Validation of the XML data+ /// happens in the database.+ pub fn new(data: impl ToString) -> Self {+ Self {+ data: data.to_string(),+ schema: None,+ }+ }++ pub(crate) fn set_schema(&mut self, schema: Arc<XmlSchema>) {+ self.schema = Some(schema);+ }++ /// Returns information about the schema of the XML file, if existing.+ #[allow(clippy::option_as_ref_deref)]+ pub fn schema(&self) -> Option<&XmlSchema> {+ self.schema.as_ref().map(|s| &**s)+ }++ /// Takes the XML string out from the struct.+ pub fn into_string(self) -> String {+ self.data+ }+}++impl std::fmt::Display for XmlData {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.data)+ }+}++impl AsRef<str> for XmlData {+ fn as_ref(&self) -> &str {+ self.data.as_ref()+ }+}++impl Encode<BytesMut> for XmlData {+ fn encode(self, dst: &mut BytesMut) -> crate::Result<()> {+ // unknown size+ dst.put_u64_le(0xfffffffffffffffe_u64);++ // first blob+ let mut length = 0u32;+ let len_pos = dst.len();++ // writing the length later+ dst.put_u32_le(length);++ for chr in self.data.encode_utf16() {+ length += 1;+ dst.put_u16_le(chr);+ }++ // PLP_TERMINATOR, no next blobs+ dst.put_u32_le(0);++ let dst: &mut [u8] = dst.borrow_mut();+ let mut dst = &mut dst[len_pos..];+ dst.put_u32_le(length * 2);++ Ok(())+ }+}diff --git a/vendor/tiberius/src/to_sql.rs b/vendor/tiberius/src/to_sql.rsnew file mode 100644index 0000000000..cde353cd1d--- /dev/null+++ b/vendor/tiberius/src/to_sql.rs@@ -0,0 +1,201 @@+use crate::{+ tds::{codec::ColumnData, Numeric},+ xml::XmlData,+};+use std::borrow::Cow;+use uuid::Uuid;++/// A conversion trait to a TDS type.+///+/// A `ToSql` implementation for a Rust type is needed for using it as a+/// parameter in the [`Client#query`] or [`Client#execute`] methods. The+/// following Rust types are already implemented to match the given server+/// types:+///+/// |Rust type|Server type|+/// |--------|--------|+/// |`u8`|`tinyint`|+/// |`i16`|`smallint`|+/// |`i32`|`int`|+/// |`i64`|`bigint`|+/// |`f32`|`float(24)`|+/// |`f64`|`float(53)`|+/// |`bool`|`bit`|+/// |`String`/`&str` (< 4000 characters)|`nvarchar(4000)`|+/// |`String`/`&str`|`nvarchar(max)`|+/// |`Vec<u8>`/`&[u8]` (< 8000 bytes)|`varbinary(8000)`|+/// |`Vec<u8>`/`&[u8]`|`varbinary(max)`|+/// |[`Uuid`]|`uniqueidentifier`|+/// |[`Numeric`]|`numeric`/`decimal`|+/// |[`Decimal`] (with feature flag `rust_decimal`)|`numeric`/`decimal`|+/// |[`BigDecimal`] (with feature flag `bigdecimal`)|`numeric`/`decimal`|+/// |[`XmlData`]|`xml`|+/// |[`NaiveDate`] (with `chrono` feature, TDS 7.3 >)|`date`|+/// |[`NaiveTime`] (with `chrono` feature, TDS 7.3 >)|`time`|+/// |[`DateTime`] (with `chrono` feature, TDS 7.3 >)|`datetimeoffset`|+/// |[`NaiveDateTime`] (with `chrono` feature, TDS 7.3 >)|`datetime2`|+/// |[`NaiveDateTime`] (with `chrono` feature, TDS 7.2)|`datetime`|+///+/// It is possible to use some of the types to write into columns that are not+/// of the same type. For example on systems following the TDS 7.3 standard (SQL+/// Server 2008 and later), the chrono type `NaiveDateTime` can also be used to+/// write to `datetime`, `datetime2` and `smalldatetime` columns. All string+/// types can also be used with `ntext`, `text`, `varchar`, `nchar` and `char`+/// columns. All binary types can also be used with `binary` and `image`+/// columns.+///+/// See the [`time`] module for more information about the date and time structs.+///+/// [`Client#query`]: struct.Client.html#method.query+/// [`Client#execute`]: struct.Client.html#method.execute+/// [`time`]: time/index.html+/// [`Uuid`]: struct.Uuid.html+/// [`Numeric`]: numeric/struct.Numeric.html+/// [`Decimal`]: numeric/struct.Decimal.html+/// [`BigDecimal`]: numeric/struct.BigDecimal.html+/// [`XmlData`]: xml/struct.XmlData.html+/// [`NaiveDateTime`]: time/chrono/struct.NaiveDateTime.html+/// [`NaiveDate`]: time/chrono/struct.NaiveDate.html+/// [`NaiveTime`]: time/chrono/struct.NaiveTime.html+/// [`DateTime`]: time/chrono/struct.DateTime.html+pub trait ToSql: Send + Sync {+ /// Convert to a value understood by the SQL Server. Conversion+ /// by-reference.+ fn to_sql(&self) -> ColumnData<'_>;+}++/// A by-value conversion trait to a TDS type.+pub trait IntoSql<'a>: Send + Sync {+ /// Convert to a value understood by the SQL Server. Conversion by-value.+ fn into_sql(self) -> ColumnData<'a>;+}++impl<'a> IntoSql<'a> for &'a str {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::String(Some(Cow::Borrowed(self)))+ }+}++impl<'a> IntoSql<'a> for Option<&'a str> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::String(self.map(Cow::Borrowed))+ }+}++impl<'a> IntoSql<'a> for &'a String {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::String(Some(Cow::Borrowed(self)))+ }+}++impl<'a> IntoSql<'a> for Option<&'a String> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::String(self.map(Cow::from))+ }+}++impl<'a> IntoSql<'a> for &'a [u8] {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Binary(Some(Cow::Borrowed(self)))+ }+}++impl<'a> IntoSql<'a> for Option<&'a [u8]> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Binary(self.map(Cow::Borrowed))+ }+}++impl<'a> IntoSql<'a> for &'a Vec<u8> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Binary(Some(Cow::from(self)))+ }+}++impl<'a> IntoSql<'a> for Option<&'a Vec<u8>> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Binary(self.map(Cow::from))+ }+}++impl<'a> IntoSql<'a> for Cow<'a, str> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::String(Some(self))+ }+}++impl<'a> IntoSql<'a> for Option<Cow<'a, str>> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::String(self)+ }+}++impl<'a> IntoSql<'a> for Cow<'a, [u8]> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Binary(Some(self))+ }+}++impl<'a> IntoSql<'a> for Option<Cow<'a, [u8]>> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Binary(self)+ }+}++impl<'a> IntoSql<'a> for &'a XmlData {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Xml(Some(Cow::Borrowed(self)))+ }+}++impl<'a> IntoSql<'a> for Option<&'a XmlData> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Xml(self.map(Cow::Borrowed))+ }+}++impl<'a> IntoSql<'a> for &'a Uuid {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Guid(Some(*self))+ }+}++impl<'a> IntoSql<'a> for Option<&'a Uuid> {+ fn into_sql(self) -> ColumnData<'a> {+ ColumnData::Guid(self.copied())+ }+}++into_sql!(self_,+ String: (ColumnData::String, Cow::from(self_));+ Vec<u8>: (ColumnData::Binary, Cow::from(self_));+ Numeric: (ColumnData::Numeric, self_);+ XmlData: (ColumnData::Xml, Cow::Owned(self_));+ Uuid: (ColumnData::Guid, self_);+ bool: (ColumnData::Bit, self_);+ u8: (ColumnData::U8, self_);+ i16: (ColumnData::I16, self_);+ i32: (ColumnData::I32, self_);+ i64: (ColumnData::I64, self_);+ f32: (ColumnData::F32, self_);+ f64: (ColumnData::F64, self_);+);++to_sql!(self_,+ bool: (ColumnData::Bit, *self_);+ u8: (ColumnData::U8, *self_);+ i16: (ColumnData::I16, *self_);+ i32: (ColumnData::I32, *self_);+ i64: (ColumnData::I64, *self_);+ f32: (ColumnData::F32, *self_);+ f64: (ColumnData::F64, *self_);+ &str: (ColumnData::String, Cow::from(*self_));+ String: (ColumnData::String, Cow::from(self_));+ Cow<'_, str>: (ColumnData::String, self_.clone());+ &[u8]: (ColumnData::Binary, Cow::from(*self_));+ Cow<'_, [u8]>: (ColumnData::Binary, self_.clone());+ Vec<u8>: (ColumnData::Binary, Cow::from(self_));+ Numeric: (ColumnData::Numeric, *self_);+ XmlData: (ColumnData::Xml, Cow::Borrowed(self_));+ Uuid: (ColumnData::Guid, *self_);+);