diff --git a/Cargo.lock b/Cargo.lock index a51c073..e15f9d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3537,8 +3537,6 @@ dependencies = [ [[package]] name = "sqlx-core" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" dependencies = [ "base64", "bytes", diff --git a/Cargo.toml b/Cargo.toml index a1a9acc..8c67836 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,8 +18,12 @@ members = [ "crates/crank-adapter-rest", "crates/crank-artifacts", ] +exclude = ["vendor/sqlx-core"] resolver = "3" +[patch.crates-io] +sqlx-core = { path = "vendor/sqlx-core" } + [workspace.package] edition = "2024" license = "AGPL-3.0-only" diff --git a/docs/dependency-patches/sqlx-core-0.9.0.md b/docs/dependency-patches/sqlx-core-0.9.0.md new file mode 100644 index 0000000..e8e0488 --- /dev/null +++ b/docs/dependency-patches/sqlx-core-0.9.0.md @@ -0,0 +1,268 @@ +# SQLx-core 0.9.0: bounded maintenance и упорядочивание публикации idle + +Этот документ описывает единственный отслеживаемый патч стороннего крейта в +репозитории: `sqlx-core` 0.9.0. Относительно архива crates.io меняется только +код `src/pool/inner.rs` (два private seam, детерминированные regression-тесты и +modification notice); дополнительно два файла лицензий восстановлены полным +текстом с закреплённого upstream-тега. Публичный API, feature-набор, таймауты и +семантика пула не меняются. + +## Provenance + +- Package: `sqlx-core` версии `0.9.0`. +- Лицензия в манифесте: `MIT OR Apache-2.0`. +- Источник vendoring: `index.crates.io-1949cf8c6b5b557f/sqlx-core-0.9.0.crate`. +- SHA-256 архива: `05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb`. + Совпадает с checksum в исходном `Cargo.lock` до патча. +- Размещение: `vendor/sqlx-core/` (безопасное извлечение архива целиком). +- `LICENSE-MIT` и `LICENSE-APACHE` в опубликованном крейте — текстовые заглушки + `../LICENSE-MIT` / `../LICENSE-APACHE`. При vendoring они восстановлены полным + оригинальным текстом с закреплённого upstream-тега (см. «Лицензии» ниже). +- Метаданные registry-кэша (`.cargo-checksum.json`) не добавлялись. +- Нормализованный upstream-манифест `vendor/sqlx-core/Cargo.toml` не + переписывался; version, features и зависимости не менялись. + +### Подключение + +В корневом `Cargo.toml`: + +```toml +[workspace] +exclude = ["vendor/sqlx-core"] + +[patch.crates-io] +sqlx-core = { path = "vendor/sqlx-core" } +``` + +В `Cargo.lock` запись `sqlx-core` перестаёт быть registry-пакетом: удаляются +строки `source = "registry+..."` и `checksum = "..."`, пакет становится path. +Других изменений в `Cargo.lock` нет. + +### Изменённые относительно архива файлы + +`diff -rq` против распакованного архива `sqlx-core-0.9.0.crate` даёт ровно три +отличия: + +- `src/pool/inner.rs` — единственный изменённый **код** (seams, regression-тесты, + modification notice); +- `LICENSE-MIT` и `LICENSE-APACHE` — восстановлены из upstream-тега. + +Остальные файлы архива (включая `Cargo.toml`, `Cargo.toml.orig`, `Cargo.lock`, +`.cargo_vcs_info.json` и весь остальной `src/`) побайтово не менялись. + +### Лицензии + +Полные тексты взяты из закреплённого upstream-тега `v0.9.0`: + +- `LICENSE-MIT` — , + SHA-256 `5abbdd842310c8f1650fcde3a5a51a3e09412b9e5a6eea87519e0db9e32b339d`; +- `LICENSE-APACHE` — , + SHA-256 `c8f5453612253e8ea8bad241617fe74c4a6d5d592ba64ff881668c211b50ac99`. + +Копирайт- и лицензионные уведомления upstream не удалялись и не переписывались. + +## Наблюдавшийся дефект + +При повторном полном gate на ревизии `1b9f7f66f9f89dcfed8d4d2efa71986063741ca0` +существовавший integration-тест `community_access_usage` повторно уходил в +sustained Tokio CPU busy loop. Собрано 100 userspace instruction-pointer +samples; среди них присутствуют: + +- `sqlx_core::pool::inner::spawn_maintenance_tasks::{{closure}}::{{closure}}` + на `src/pool/inner.rs:549`; +- `PoolInner::try_acquire` (`inner.rs:182`) и `PoolInner::release`; +- `crossbeam_queue::array_queue::ArrayQueue::pop`, + `core::sync::atomic::Atomic::fetch_sub/fetch_add`. + +Важная оговорка: **live-значения `num_idle`/`MAX` не снимались**. Захват +samples показывает hotspot, но не доказывает, что в проде наблюдался именно +`usize::MAX`. Считаем наблюдаемым только сам hot loop; MAX-сценарий +демонстрируется отдельно, принудительным interleaving в unit-тесте. + +### Достижимая гонка в исходнике + +В upstream `release()` соединение публикуется в `idle_conns`, затем +отпускается permit, и только потом увеличивается `num_idle`: + +```rust +if self.idle_conns.push(idle).is_err() { /* panic */ } +guard.release_permit(); +self.num_idle.fetch_add(1, Ordering::AcqRel); +``` + +Параллельный `try_acquire()` может выполнить `pop_idle()` в окне между +`push`/`release_permit` и `fetch_add`. Тогда `num_idle.fetch_sub(1)` при +исходном нуле временно уходит в underflow (`0 - 1` → `usize::MAX`), а +последующий `fetch_add(1)` возвращает счётчик к нулю. В этом окне maintenance +task читает `num_idle` и выполняет `for _ in 0..pool.num_idle()` — без +ограничения сверху, то есть потенциально огромный диапазон. + +## Патч + +Полные unified diff лежат в evidence рядом с completion-отчётом: +[`docs/epic-1-completion/evidence/sqlx-red.patch`](../epic-1-completion/evidence/sqlx-red.patch) +(исходное RED-состояние) и +[`docs/epic-1-completion/evidence/sqlx-accepted.patch`](../epic-1-completion/evidence/sqlx-accepted.patch) +(принятая версия). SHA-256 патчей зафиксированы в metadata. Ниже — суть +принятого изменения. + +### 1. Bounded maintenance batch + +Новый private helper, используемый реальным for-loop в +`spawn_maintenance_tasks`: + +```rust +fn maintenance_batch_size(num_idle: usize, capacity: usize) -> usize { + cmp::min(num_idle, capacity) +} +``` + +```rust +let batch_size = maintenance_batch_size( + pool.num_idle(), + pool.options.max_connections as usize, +); +for _ in 0..batch_size { + if let Some(conn) = pool.try_acquire() { /* ... */ } +} +``` + +`num_idle` не может легитимно превышать capacity; ограничение не отключает +maintenance и не меняет период/таймауты. + +### 2. Резервирование idle-счётчика до публикации + +`release()` теперь публикует через helper, который увеличивает `num_idle` до +вызова публикующего callback и откатывает изменение при ошибке: + +```rust +fn publish_idle_connection(num_idle: &AtomicUsize, publish: F) -> Result<(), E> +where + F: FnOnce() -> Result<(), E>, +{ + num_idle.fetch_add(1, Ordering::AcqRel); + + if let Err(error) = publish() { + num_idle.fetch_sub(1, Ordering::AcqRel); + return Err(error); + } + + Ok(()) +} +``` + +Callback естественно возвращает ошибку push как `Result<(), Idle>`: + +```rust +let published = publish_idle_connection(&self.num_idle, move || { + // NOTE: permit отпускается только после удачного push + self.idle_conns + .push(idle) + .map(|()| guard.release_permit()) +}); + +if published.is_err() { + panic!("BUG: connection queue overflow in release()"); +} +``` + +`guard.release_permit()` вызывается только при удачном push, то есть порядок +push-before-release-permit сохранён. Существующий +`panic!("BUG: connection queue overflow in release()")` сохранён, но вынесен +**наружу** `publish_idle_connection` и срабатывает уже после отката резерва. +Поэтому ветка отката — реальный production-путь (переполнение очереди), а не +защитная недостижимая ветка. + +Важно: `maintenance_batch_size` ограничивает только объём maintenance-скана по +capacity. Это **не** защита от переполнения `idle_conns` — это разные инварианты, +и один не подменяет другой. + +### Регрессионные тесты + +Тесты используют фактический private helper, применяемый в `release()`, а не +проверку текста исходника: + +- `maintenance_batch_size_bounds_scan_by_capacity` — оракул для `0`, `1`, + `capacity`, `capacity + 1`, `usize::MAX`; ожидается ограничение capacity при + сохранении нормальных значений. MAX проверяется без запуска цикла на + `usize::MAX`. +- `publish_reserves_idle_counter_before_connection_is_visible` — детерминированная + модель гонки: `ArrayQueue` + `AtomicUsize` + две фазы `Barrier` в двух + потоках. Producer публикует соединение, затем сигналит consumer и ждёт его + `pop` до возврата из callback. Consumer записывает *предыдущее* значение + `fetch_sub` и не утверждает его до второго barrier/join, чтобы RED не + превратился в deadlock. Ожидается `previous == 1` и финальный счётчик `0`. + В исходном порядке наблюдается `previous == 0` (даже если поздний + wrapping-`fetch_add` возвращает `0`). +- `publish_rolls_back_idle_counter_when_publication_fails` — при `Err` из + callback счётчик не должен «утечь». Production `release()` возвращает именно + ошибку push (`Idle`); тест использует строковую ошибку, чтобы проверить + тот же контракт helper без конструирования подключения к БД. + +Никаких test-only sleep, mock DB, файлов или сети; все утверждения +детерминированы и ограничены. + +## Evidence + +Команда запускалась напрямую по манифесту vendored-крейта как самостоятельного +пакета: + +```text +cargo test --manifest-path vendor/sqlx-core/Cargo.toml --locked --lib +``` + +Запуск использовал изолированные `CARGO_HOME` и `CARGO_TARGET_DIR`, поэтому +отслеживаемый `Cargo.lock` крейта и глобальный cargo cache не изменялись; +конкретные пути машины здесь не приводятся. + +RED (`sqlx-red.log`, exit `101`): + +```text +test pool::inner::tests::maintenance_batch_size_bounds_scan_by_capacity ... FAILED +test pool::inner::tests::publish_reserves_idle_counter_before_connection_is_visible ... FAILED +test pool::inner::tests::publish_rolls_back_idle_counter_when_publication_fails ... ok +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 2 filtered out +``` + +Падения RED: `left: 9, right: 8` (не ограничено capacity) и +`idle counter must be reserved before the connection is visible, saw 0` +(подтверждён `previous == 0`). Deadlock не возник, потому что проверка +отложена до join. + +GREEN (`sqlx-green.log`, exit `0`): + +```text +test io::read_buf::test_read_buf_bytes_mut ... ok +test pool::assert_pool_traits ... ok +test pool::inner::tests::maintenance_batch_size_bounds_scan_by_capacity ... ok +test pool::inner::tests::publish_reserves_idle_counter_before_connection_is_visible ... ok +test pool::inner::tests::publish_rolls_back_idle_counter_when_publication_fails ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +Существующие upstream-тесты (`pool::assert_pool_traits`, +`io::read_buf::test_read_buf_bytes_mut`) не отключены и проходят. + +Принятая версия (после follow-up правок: natural `Result<(), Idle>` с +panic снаружи helper, восстановленные лицензии, modification notice) повторно +прогнана тем же `cargo test --manifest-path vendor/sqlx-core/Cargo.toml --locked --lib` +с результатом `5 passed; 0 failed` (полный лог — `sqlx-accepted.log`). + +Дополнительно на принятой версии: + +- `cargo check -p crank-registry -p admin-api` (`SQLX_OFFLINE=true`, `--offline`) — успешно; +- `cargo deny --locked check advisories bans licenses sources` — + `advisories ok, bans ok, licenses ok, sources ok`; +- `rustfmt --edition 2021 --check vendor/sqlx-core/src/pool/inner.rs` — чисто. + +## Ограничения и maintenance burden + +- Unit-тесты моделируют достижимое interleaving, но **не доказывают, что в + production наблюдался `usize::MAX`**. Наблюдаемым фактом остаются hot loop и + цепочка maintenance/try_acquire/release по samples. +- Это отслеживаемый source patch сторонней зависимости. Он требует ручного + переприменения/rebase при обновлении `sqlx-core` и должен быть удалён, как + только подтверждённый upstream-fix войдёт в используемую версию. +- Публичный API, схемы, feature-набор и таймауты не менялись; maintenance не + отключался. +- Тесты не отключались; глобальный cargo cache не редактировался. diff --git a/vendor/sqlx-core/.cargo_vcs_info.json b/vendor/sqlx-core/.cargo_vcs_info.json new file mode 100644 index 0000000..94853d3 --- /dev/null +++ b/vendor/sqlx-core/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "003b698e99e024f3621b8043a2426fde5b741171" + }, + "path_in_vcs": "sqlx-core" +} \ No newline at end of file diff --git a/vendor/sqlx-core/Cargo.lock b/vendor/sqlx-core/Cargo.lock new file mode 100644 index 0000000..0d78623 --- /dev/null +++ b/vendor/sqlx-core/Cargo.lock @@ -0,0 +1,2675 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "version_check", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-fs" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" +dependencies = [ + "async-lock", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-global-executor" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" +dependencies = [ + "async-channel 2.5.0", + "async-executor", + "async-io", + "async-lock", + "blocking", + "futures-lite", + "once_cell", +] + +[[package]] +name = "async-global-executor" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13f937e26114b93193065fd44f507aa2e9169ad0cdabbb996920b1fe1ddea7ba" +dependencies = [ + "async-channel 2.5.0", + "async-executor", + "async-io", + "async-lock", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener 5.4.1", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-net" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" +dependencies = [ + "async-io", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel 2.5.0", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener 5.4.1", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-std" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" +dependencies = [ + "async-channel 1.9.0", + "async-global-executor 2.4.1", + "async-io", + "async-lock", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "aws-lc-rs" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec6fb3fe69024a75fa7e1bfb48aa6cf59706a101658ea01bfd33b2b248a038f" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bigdecimal" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel 2.5.0", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "bstr" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytecheck" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" +dependencies = [ + "bytecheck_derive", + "ptr_meta", + "simdutf8", +] + +[[package]] +name = "bytecheck_derive" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener 5.4.1", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[package]] +name = "hashlink" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", + "serde", + "serde_core", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "ipnetwork" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf370abdafd54d13e54a620e8c3e1145f28e46cc9d704bc6d94414559df41763" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1840c94c045fbcf8ba2812c95db44499f7c64910a912551aaaa541decebcacf" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +dependencies = [ + "value-bag", +] + +[[package]] +name = "mac_address" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303" +dependencies = [ + "nix", + "winapi", +] + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl" +version = "0.10.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38c4372413cdaaf3cc79dd92d29d7d9f5ab09b51b10dded508fb90bb70b9222" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13ce1245cd07fcc4cfdb438f7507b0c7e4f3849a69fd84d52374c66d83741bb6" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.117", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.11+spec-1.1.0", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "ptr_meta" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" +dependencies = [ + "ptr_meta_derive", +] + +[[package]] +name = "ptr_meta_derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rend" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" +dependencies = [ + "bytecheck", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rkyv" +version = "0.7.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1" +dependencies = [ + "bitvec", + "bytecheck", + "bytes", + "hashbrown 0.12.3", + "ptr_meta", + "rend", + "rkyv_derive", + "seahash", + "tinyvec", + "uuid", +] + +[[package]] +name = "rkyv_derive" +version = "0.7.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "rust_decimal" +version = "1.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ce901f9a19d251159075a4c37af514c3b8ef99c22e02dd8c19161cf397ee94a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand", + "rkyv", + "serde", + "serde_json", + "wasm-bindgen", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "aws-lc-rs", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "seahash" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "smol" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33bd3e260892199c3ccfc487c88b2da2265080acb316cd920da72fdfd7c599f" +dependencies = [ + "async-channel 2.5.0", + "async-executor", + "async-fs", + "async-io", + "async-lock", + "async-net", + "async-process", + "blocking", + "futures-lite", +] + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sqlx-core" +version = "0.9.0" +dependencies = [ + "async-fs", + "async-global-executor 3.1.0", + "async-io", + "async-std", + "async-task", + "base64", + "bigdecimal", + "bit-vec", + "bstr", + "bytes", + "cfg-if", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener 5.4.1", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", + "indexmap", + "ipnet", + "ipnetwork", + "log", + "mac_address", + "memchr", + "native-tls", + "percent-encoding", + "rust_decimal", + "rustls", + "rustls-native-certs", + "serde", + "serde_json", + "sha2", + "smallvec", + "smol", + "thiserror", + "time", + "tokio", + "tokio-stream", + "toml", + "tracing", + "url", + "uuid", + "webpki-roots", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.11+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" +dependencies = [ + "indexmap", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.2", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.2", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "value-bag" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df52b6d9b87e0c74c9edfa1eb2d9bf85e5d63515474513aa50fa181b3c4f5db1" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.70" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af934872acec734c2d80e6617bbb5ff4f12b052dd8e6332b0817bce889516084" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b1041f495fb322e64aca85f5756b2172e35cd459376e67f2a6c9dffcedb103" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dcd0ff20416988a18ac686d4d4d0f6aae9ebf08a389ff5d29012b05af2a1b41" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.117", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.120" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49757b3c82ebf16c57d69365a142940b384176c24df52a087fb748e2085359ea" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.117", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.117", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/vendor/sqlx-core/Cargo.toml b/vendor/sqlx-core/Cargo.toml new file mode 100644 index 0000000..3090e17 --- /dev/null +++ b/vendor/sqlx-core/Cargo.toml @@ -0,0 +1,331 @@ +# 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] +edition = "2021" +rust-version = "1.94.0" +name = "sqlx-core" +version = "0.9.0" +authors = [ + "Ryan Leckey ", + "Austin Bonander ", + "Chloe Ross ", + "Daniel Akhterov ", +] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Core of SQLx, the rust SQL toolkit. Not intended to be used directly." +readme = false +license = "MIT OR Apache-2.0" +repository = "https://github.com/launchbadge/sqlx" + +[package.metadata.docs.rs] +features = ["offline"] + +[features] +_rt-async-global-executor = [ + "async-global-executor", + "_rt-async-io", + "_rt-async-task", +] +_rt-async-io = [ + "async-io", + "async-fs", +] +_rt-async-std = [ + "async-std", + "_rt-async-io", +] +_rt-async-task = ["async-task"] +_rt-smol = [ + "smol", + "_rt-async-io", + "_rt-async-task", +] +_rt-tokio = [ + "tokio", + "tokio-stream", +] +_tls-native-tls = ["native-tls"] +_tls-none = [] +_tls-rustls = ["rustls"] +_tls-rustls-aws-lc-rs = [ + "_tls-rustls", + "rustls/aws-lc-rs", + "webpki-roots", +] +_tls-rustls-ring-native-roots = [ + "_tls-rustls", + "rustls/ring", + "rustls-native-certs", +] +_tls-rustls-ring-webpki = [ + "_tls-rustls", + "rustls/ring", + "webpki-roots", +] +_unstable-doc = ["sqlx-toml"] +any = [] +default = [] +json = [ + "serde", + "serde_json", +] +migrate = [ + "sha2", + "crc", +] +offline = [ + "serde", + "either/serde", +] +sqlx-toml = [ + "serde", + "toml/parse", +] + +[lib] +name = "sqlx_core" +path = "src/lib.rs" + +[dependencies.async-fs] +version = "2.1" +optional = true + +[dependencies.async-global-executor] +version = "3.1" +features = ["async-io"] +optional = true +default-features = false + +[dependencies.async-io] +version = "2.4.1" +optional = true + +[dependencies.async-std] +version = "1.13" +optional = true + +[dependencies.async-task] +version = "4.7.1" +optional = true + +[dependencies.base64] +version = "0.22.1" +features = ["alloc"] +default-features = false + +[dependencies.bigdecimal] +version = "0.4.0" +optional = true + +[dependencies.bit-vec] +version = "0.8" +optional = true + +[dependencies.bstr] +version = "1.0.1" +features = ["std"] +optional = true +default-features = false + +[dependencies.bytes] +version = "1.2.0" + +[dependencies.cfg-if] +version = "1.0.0" + +[dependencies.chrono] +version = "0.4.34" +features = [ + "std", + "clock", +] +optional = true +default-features = false + +[dependencies.crc] +version = "3" +optional = true + +[dependencies.crossbeam-queue] +version = "0.3.2" + +[dependencies.either] +version = "1.6.1" + +[dependencies.event-listener] +version = "5.2.0" + +[dependencies.futures-core] +version = "0.3.32" +default-features = false + +[dependencies.futures-intrusive] +version = "0.5.0" + +[dependencies.futures-io] +version = "0.3.32" + +[dependencies.futures-util] +version = "0.3.32" +features = [ + "alloc", + "sink", + "io", +] +default-features = false + +[dependencies.hashbrown] +version = "0.16.0" + +[dependencies.hashlink] +version = "0.11.0" + +[dependencies.indexmap] +version = "2.0" + +[dependencies.ipnet] +version = "2.3.0" +optional = true + +[dependencies.ipnetwork] +version = "0.21.1" +optional = true + +[dependencies.log] +version = "0.4.18" +default-features = false + +[dependencies.mac_address] +version = "1.1.5" +optional = true + +[dependencies.memchr] +version = "2.5.0" +default-features = false + +[dependencies.native-tls] +version = "0.2.10" +optional = true + +[dependencies.percent-encoding] +version = "2.3.0" + +[dependencies.rust_decimal] +version = "1.36.0" +features = ["std"] +optional = true +default-features = false + +[dependencies.rustls] +version = "0.23.24" +features = [ + "std", + "tls12", +] +optional = true +default-features = false + +[dependencies.rustls-native-certs] +version = "0.8.0" +optional = true + +[dependencies.serde] +version = "1.0.219" +features = [ + "derive", + "rc", +] +optional = true + +[dependencies.serde_json] +version = "1.0.142" +features = ["raw_value"] +optional = true + +[dependencies.sha2] +version = "0.10.0" +optional = true +default-features = false + +[dependencies.smallvec] +version = "1.13.1" + +[dependencies.smol] +version = "2.0" +optional = true +default-features = false + +[dependencies.thiserror] +version = "2.0.18" +features = ["std"] +default-features = false + +[dependencies.time] +version = "0.3.47" +features = [ + "formatting", + "parsing", + "macros", +] +optional = true + +[dependencies.tokio] +version = "1.25.0" +features = [ + "time", + "net", + "sync", + "fs", + "io-util", + "rt", +] +optional = true +default-features = false + +[dependencies.tokio-stream] +version = "0.1.8" +features = ["fs"] +optional = true + +[dependencies.toml] +version = "0.8.16" +optional = true + +[dependencies.tracing] +version = "0.1.37" +features = ["log"] + +[dependencies.url] +version = "2.2.2" + +[dependencies.uuid] +version = "1.12.1" +optional = true + +[dependencies.webpki-roots] +version = "1" +optional = true + +[dev-dependencies.tokio] +version = "1.25.0" +features = ["rt"] + +[lints.clippy] +cast_possible_truncation = "deny" +cast_possible_wrap = "deny" +cast_sign_loss = "deny" +disallowed_methods = "deny" diff --git a/vendor/sqlx-core/Cargo.toml.orig b/vendor/sqlx-core/Cargo.toml.orig new file mode 100755 index 0000000..5c20bad --- /dev/null +++ b/vendor/sqlx-core/Cargo.toml.orig @@ -0,0 +1,119 @@ +[package] +name = "sqlx-core" +description = "Core of SQLx, the rust SQL toolkit. Not intended to be used directly." +version.workspace = true +license.workspace = true +edition.workspace = true +authors.workspace = true +repository.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +features = ["offline"] + +[features] +default = [] +migrate = ["sha2", "crc"] + +any = [] + +json = ["serde", "serde_json"] + +# for conditional compilation +_rt-async-global-executor = ["async-global-executor", "_rt-async-io", "_rt-async-task"] +_rt-async-io = ["async-io", "async-fs"] # see note at async-fs declaration +_rt-async-std = ["async-std", "_rt-async-io"] +_rt-async-task = ["async-task"] +_rt-smol = ["smol", "_rt-async-io", "_rt-async-task"] +_rt-tokio = ["tokio", "tokio-stream"] + +_tls-native-tls = ["native-tls"] +_tls-rustls-aws-lc-rs = ["_tls-rustls", "rustls/aws-lc-rs", "webpki-roots"] +_tls-rustls-ring-webpki = ["_tls-rustls", "rustls/ring", "webpki-roots"] +_tls-rustls-ring-native-roots = ["_tls-rustls", "rustls/ring", "rustls-native-certs"] +_tls-rustls = ["rustls"] +_tls-none = [] + +# support offline/decoupled building (enables serialization of `Describe`) +offline = ["serde", "either/serde"] + +# Enable parsing of `sqlx.toml`. +# For simplicity, the `config` module is always enabled, +# but disabling this disables the `serde` derives and the `toml` crate, +# which is a good bit less code to compile if the feature isn't being used. +sqlx-toml = ["serde", "toml/parse"] + +_unstable-doc = ["sqlx-toml"] + +[dependencies] +# Runtimes +async-global-executor = { workspace = true, optional = true } +async-std = { workspace = true, optional = true } +smol = { workspace = true, optional = true } +tokio = { workspace = true, optional = true } + +# TLS +native-tls = { version = "0.2.10", optional = true } + +rustls = { version = "0.23.24", default-features = false, features = ["std", "tls12"], optional = true } +webpki-roots = { version = "1", optional = true } +rustls-native-certs = { version = "0.8.0", optional = true } + +# Type Integrations +bit-vec = { workspace = true, optional = true } +bigdecimal = { workspace = true, optional = true } +chrono = { workspace = true, optional = true } +rust_decimal = { workspace = true, optional = true } +time = { workspace = true, optional = true } +ipnet = { workspace = true, optional = true } +ipnetwork = { workspace = true, optional = true } +mac_address = { workspace = true, optional = true } +uuid = { workspace = true, optional = true } + +# work around bug in async-fs 2.0.0, which references futures-lite dependency wrongly, see https://github.com/launchbadge/sqlx/pull/3791#issuecomment-3043363281 +async-fs = { version = "2.1", optional = true } +async-io = { version = "2.4.1", optional = true } +async-task = { version = "4.7.1", optional = true } + +base64.workspace = true +bytes = "1.2.0" +cfg-if = { workspace = true } +crc = { version = "3", optional = true } +crossbeam-queue = "0.3.2" +either = "1.6.1" +futures-core = { version = "0.3.32", default-features = false } +futures-io = "0.3.32" +futures-intrusive = "0.5.0" +futures-util = { version = "0.3.32", default-features = false, features = ["alloc", "sink", "io"] } +log = { version = "0.4.18", default-features = false } +memchr = { version = "2.5.0", default-features = false } +percent-encoding = "2.3.0" +serde = { version = "1.0.219", features = ["derive", "rc"], optional = true } +serde_json = { version = "1.0.142", features = ["raw_value"], optional = true } +toml = { version = "0.8.16", optional = true } +sha2 = { version = "0.10.0", default-features = false, optional = true } +#sqlformat = "0.2.0" +tokio-stream = { version = "0.1.8", features = ["fs"], optional = true } +tracing = { version = "0.1.37", features = ["log"] } +smallvec = "1.13.1" +url = { version = "2.2.2" } +bstr = { version = "1.0.1", default-features = false, features = ["std"], optional = true } +hashlink = "0.11.0" +indexmap = "2.0" +event-listener = "5.2.0" +hashbrown = "0.16.0" + +thiserror.workspace = true + +[dev-dependencies] +tokio = { version = "1.25.0", features = ["rt"] } + +[dev-dependencies.sqlx] +# FIXME: https://github.com/rust-lang/cargo/issues/15622 +# workspace = true +path = ".." +default-features = false +features = ["postgres", "sqlite", "mysql", "migrate", "macros", "time", "uuid"] + +[lints] +workspace = true diff --git a/vendor/sqlx-core/LICENSE-APACHE b/vendor/sqlx-core/LICENSE-APACHE new file mode 100755 index 0000000..e14699f --- /dev/null +++ b/vendor/sqlx-core/LICENSE-APACHE @@ -0,0 +1,202 @@ +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 (C) SQLx Contributors +Portions of this work Copyright (C) LaunchBadge, LLC + +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/sqlx-core/LICENSE-MIT b/vendor/sqlx-core/LICENSE-MIT new file mode 100755 index 0000000..6fe828e --- /dev/null +++ b/vendor/sqlx-core/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (C) SQLx Contributors +Portions of this work Copyright (C) LaunchBadge, LLC + +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/sqlx-core/src/acquire.rs b/vendor/sqlx-core/src/acquire.rs new file mode 100755 index 0000000..d7105f0 --- /dev/null +++ b/vendor/sqlx-core/src/acquire.rs @@ -0,0 +1,125 @@ +use crate::database::Database; +use crate::error::Error; +use crate::pool::{MaybePoolConnection, Pool, PoolConnection}; + +use crate::transaction::Transaction; +use futures_core::future::BoxFuture; +use std::ops::{Deref, DerefMut}; + +/// Acquire connections or transactions from a database in a generic way. +/// +/// If you want to accept generic database connections that implement +/// [`Acquire`] which then allows you to [`acquire`][`Acquire::acquire`] a +/// connection or [`begin`][`Acquire::begin`] a transaction, then you can do it +/// like that: +/// +/// ```rust,ignore +/// # use sqlx::{Acquire, postgres::Postgres, error::BoxDynError}; +/// async fn run_query<'a, A>(conn: A) -> Result<(), BoxDynError> +/// where +/// A: Acquire<'a, Database = Postgres>, +/// { +/// let mut conn = conn.acquire().await?; +/// +/// sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?; +/// sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?; +/// +/// Ok(()) +/// } +/// ``` +/// +/// If you run into a lifetime error about "implementation of `sqlx::Acquire` is +/// not general enough", the [workaround] looks like this: +/// +/// ```rust,ignore +/// # use std::future::Future; +/// # use sqlx::{Acquire, postgres::Postgres, error::BoxDynError}; +/// fn run_query<'a, 'c, A>(conn: A) -> impl Future> + Send + 'a +/// where +/// A: Acquire<'c, Database = Postgres> + Send + 'a, +/// { +/// async move { +/// let mut conn = conn.acquire().await?; +/// +/// sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?; +/// sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?; +/// +/// Ok(()) +/// } +/// } +/// ``` +/// +/// However, if you really just want to accept both, a transaction or a +/// connection as an argument to a function, then it's easier to just accept a +/// mutable reference to a database connection like so: +/// +/// ```rust,ignore +/// # use sqlx::{postgres::PgConnection, error::BoxDynError}; +/// async fn run_query(conn: &mut PgConnection) -> Result<(), BoxDynError> { +/// sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?; +/// sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?; +/// +/// Ok(()) +/// } +/// ``` +/// +/// The downside of this approach is that you have to `acquire` a connection +/// from a pool first and can't directly pass the pool as argument. +/// +/// [workaround]: https://github.com/launchbadge/sqlx/issues/1015#issuecomment-767787777 +pub trait Acquire<'c> { + type Database: Database; + + type Connection: Deref::Connection> + DerefMut + Send; + + fn acquire(self) -> BoxFuture<'c, Result>; + + fn begin(self) -> BoxFuture<'c, Result, Error>>; +} + +impl<'a, DB: Database> Acquire<'a> for &'_ Pool { + type Database = DB; + + type Connection = PoolConnection; + + fn acquire(self) -> BoxFuture<'static, Result> { + Box::pin(self.acquire()) + } + + fn begin(self) -> BoxFuture<'static, Result, Error>> { + let conn = self.acquire(); + + Box::pin(async move { + Transaction::begin(MaybePoolConnection::PoolConnection(conn.await?), None).await + }) + } +} + +#[macro_export] +macro_rules! impl_acquire { + ($DB:ident, $C:ident) => { + impl<'c> $crate::acquire::Acquire<'c> for &'c mut $C { + type Database = $DB; + + type Connection = &'c mut <$DB as $crate::database::Database>::Connection; + + #[inline] + fn acquire( + self, + ) -> futures_core::future::BoxFuture<'c, Result> + { + Box::pin(std::future::ready(Ok(self))) + } + + #[inline] + fn begin( + self, + ) -> futures_core::future::BoxFuture< + 'c, + Result<$crate::transaction::Transaction<'c, $DB>, $crate::error::Error>, + > { + $crate::transaction::Transaction::begin(self, None) + } + } + }; +} diff --git a/vendor/sqlx-core/src/any/arguments.rs b/vendor/sqlx-core/src/any/arguments.rs new file mode 100755 index 0000000..59d6f4d --- /dev/null +++ b/vendor/sqlx-core/src/any/arguments.rs @@ -0,0 +1,87 @@ +use crate::any::value::AnyValueKind; +use crate::any::{Any, AnyTypeInfoKind}; +use crate::arguments::Arguments; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; +use std::sync::Arc; + +#[derive(Default)] +pub struct AnyArguments { + #[doc(hidden)] + pub values: AnyArgumentBuffer, +} + +impl Arguments for AnyArguments { + type Database = Any; + + fn reserve(&mut self, additional: usize, _size: usize) { + self.values.0.reserve(additional); + } + + fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError> + where + T: Encode<'t, Self::Database> + Type, + { + let _: IsNull = value.encode(&mut self.values)?; + Ok(()) + } + + fn len(&self) -> usize { + self.values.0.len() + } +} + +#[derive(Default)] +pub struct AnyArgumentBuffer(#[doc(hidden)] pub Vec); + +impl AnyArguments { + #[doc(hidden)] + pub fn convert_into<'a, A: Arguments>(self) -> Result + where + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option: Type + Encode<'a, A::Database>, + Option>: Type + Encode<'a, A::Database>, + bool: Type + Encode<'a, A::Database>, + i16: Type + Encode<'a, A::Database>, + i32: Type + Encode<'a, A::Database>, + i64: Type + Encode<'a, A::Database>, + f32: Type + Encode<'a, A::Database>, + f64: Type + Encode<'a, A::Database>, + Arc: Type + Encode<'a, A::Database>, + Arc: Type + Encode<'a, A::Database>, + Arc>: Type + Encode<'a, A::Database>, + { + let mut out = A::default(); + + for arg in self.values.0 { + match arg { + AnyValueKind::Null(AnyTypeInfoKind::Null) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::Bool) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::SmallInt) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::Integer) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::BigInt) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::Real) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::Double) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::Text) => out.add(Option::::None), + AnyValueKind::Null(AnyTypeInfoKind::Blob) => out.add(Option::>::None), + AnyValueKind::Bool(b) => out.add(b), + AnyValueKind::SmallInt(i) => out.add(i), + AnyValueKind::Integer(i) => out.add(i), + AnyValueKind::BigInt(i) => out.add(i), + AnyValueKind::Real(r) => out.add(r), + AnyValueKind::Double(d) => out.add(d), + AnyValueKind::Text(t) => out.add(t), + AnyValueKind::TextSlice(t) => out.add(t), + AnyValueKind::Blob(b) => out.add(b), + }? + } + Ok(out) + } +} diff --git a/vendor/sqlx-core/src/any/column.rs b/vendor/sqlx-core/src/any/column.rs new file mode 100755 index 0000000..bb885e6 --- /dev/null +++ b/vendor/sqlx-core/src/any/column.rs @@ -0,0 +1,31 @@ +use crate::any::{Any, AnyTypeInfo}; +use crate::column::Column; +use crate::ext::ustr::UStr; + +#[derive(Debug, Clone)] +pub struct AnyColumn { + // NOTE: these fields are semver-exempt. See crate root docs for details. + #[doc(hidden)] + pub ordinal: usize, + + #[doc(hidden)] + pub name: UStr, + + #[doc(hidden)] + pub type_info: AnyTypeInfo, +} +impl Column for AnyColumn { + type Database = Any; + + fn ordinal(&self) -> usize { + self.ordinal + } + + fn name(&self) -> &str { + &self.name + } + + fn type_info(&self) -> &AnyTypeInfo { + &self.type_info + } +} diff --git a/vendor/sqlx-core/src/any/connection/backend.rs b/vendor/sqlx-core/src/any/connection/backend.rs new file mode 100755 index 0000000..1ee743a --- /dev/null +++ b/vendor/sqlx-core/src/any/connection/backend.rs @@ -0,0 +1,121 @@ +use crate::any::{AnyArguments, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo}; +use crate::sql_str::SqlStr; +use either::Either; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; +use std::fmt::Debug; + +pub trait AnyConnectionBackend: std::any::Any + Debug + Send + 'static { + /// The backend name. + fn name(&self) -> &str; + + /// Explicitly close this database connection. + /// + /// This method is **not required** for safe and consistent operation. However, it is + /// recommended to call it instead of letting a connection `drop` as the database backend + /// will be faster at cleaning up resources. + fn close(self: Box) -> BoxFuture<'static, crate::Result<()>>; + + /// Immediately close the connection without sending a graceful shutdown. + /// + /// This should still at least send a TCP `FIN` frame to let the server know we're dying. + #[doc(hidden)] + fn close_hard(self: Box) -> BoxFuture<'static, crate::Result<()>>; + + /// Checks if a connection to the database is still valid. + fn ping(&mut self) -> BoxFuture<'_, crate::Result<()>>; + + /// Begin a new transaction or establish a savepoint within the active transaction. + /// + /// If this is a new transaction, `statement` may be used instead of the + /// default "BEGIN" statement. + /// + /// If we are already inside a transaction and `statement.is_some()`, then + /// `Error::InvalidSavePoint` is returned without running any statements. + fn begin(&mut self, statement: Option) -> BoxFuture<'_, crate::Result<()>>; + + fn commit(&mut self) -> BoxFuture<'_, crate::Result<()>>; + + fn rollback(&mut self) -> BoxFuture<'_, crate::Result<()>>; + + fn start_rollback(&mut self); + + /// Returns the current transaction depth. + /// + /// Transaction depth indicates the level of nested transactions: + /// - Level 0: No active transaction. + /// - Level 1: A transaction is active. + /// - Level 2 or higher: A transaction is active and one or more SAVEPOINTs have been created within it. + fn get_transaction_depth(&self) -> usize { + unimplemented!("get_transaction_depth() is not implemented for this backend. This is a provided method to avoid a breaking change, but it will become a required method in version 0.9 and later."); + } + + /// Checks if the connection is currently in a transaction. + /// + /// This method returns `true` if the current transaction depth is greater than 0, + /// indicating that a transaction is active. It returns `false` if the transaction depth is 0, + /// meaning no transaction is active. + #[inline] + fn is_in_transaction(&self) -> bool { + self.get_transaction_depth() != 0 + } + + /// The number of statements currently cached in the connection. + fn cached_statements_size(&self) -> usize { + 0 + } + + /// Removes all statements from the cache, closing them on the server if + /// needed. + fn clear_cached_statements(&mut self) -> BoxFuture<'_, crate::Result<()>> { + Box::pin(async move { Ok(()) }) + } + + /// Forward to [`Connection::shrink_buffers()`]. + /// + /// [`Connection::shrink_buffers()`]: method@crate::connection::Connection::shrink_buffers + fn shrink_buffers(&mut self); + + #[doc(hidden)] + fn flush(&mut self) -> BoxFuture<'_, crate::Result<()>>; + + #[doc(hidden)] + fn should_flush(&self) -> bool; + + #[cfg(feature = "migrate")] + fn as_migrate(&mut self) -> crate::Result<&mut (dyn crate::migrate::Migrate + Send + 'static)> { + Err(crate::Error::Configuration( + format!( + "{} driver does not support migrations or `migrate` feature was not enabled", + self.name() + ) + .into(), + )) + } + + fn fetch_many( + &mut self, + query: SqlStr, + persistent: bool, + arguments: Option, + ) -> BoxStream<'_, crate::Result>>; + + fn fetch_optional( + &mut self, + query: SqlStr, + persistent: bool, + arguments: Option, + ) -> BoxFuture<'_, crate::Result>>; + + fn prepare_with<'c, 'q: 'c>( + &'c mut self, + sql: SqlStr, + parameters: &[AnyTypeInfo], + ) -> BoxFuture<'c, crate::Result>; + + #[cfg(feature = "offline")] + fn describe( + &mut self, + sql: SqlStr, + ) -> BoxFuture<'_, crate::Result>>; +} diff --git a/vendor/sqlx-core/src/any/connection/executor.rs b/vendor/sqlx-core/src/any/connection/executor.rs new file mode 100755 index 0000000..8893766 --- /dev/null +++ b/vendor/sqlx-core/src/any/connection/executor.rs @@ -0,0 +1,68 @@ +use crate::any::{Any, AnyConnection, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo}; +use crate::error::Error; +use crate::executor::{Execute, Executor}; +use crate::sql_str::SqlStr; +use either::Either; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; +use futures_util::{stream, FutureExt, StreamExt}; +use std::future; + +impl<'c> Executor<'c> for &'c mut AnyConnection { + type Database = Any; + + fn fetch_many<'e, 'q: 'e, E>( + self, + mut query: E, + ) -> BoxStream<'e, Result, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Any>, + { + let arguments = match query.take_arguments().map_err(Error::Encode) { + Ok(arguments) => arguments, + Err(error) => return stream::once(future::ready(Err(error))).boxed(), + }; + let persistent = query.persistent(); + self.backend.fetch_many(query.sql(), persistent, arguments) + } + + fn fetch_optional<'e, 'q: 'e, E>( + self, + mut query: E, + ) -> BoxFuture<'e, Result, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>, + { + let arguments = match query.take_arguments().map_err(Error::Encode) { + Ok(arguments) => arguments, + Err(error) => return future::ready(Err(error)).boxed(), + }; + let persistent = query.persistent(); + self.backend + .fetch_optional(query.sql(), persistent, arguments) + } + + fn prepare_with<'e>( + self, + sql: SqlStr, + parameters: &[AnyTypeInfo], + ) -> BoxFuture<'e, Result> + where + 'c: 'e, + { + self.backend.prepare_with(sql, parameters) + } + + #[cfg(feature = "offline")] + fn describe<'e>( + self, + sql: SqlStr, + ) -> BoxFuture<'e, Result, Error>> + where + 'c: 'e, + { + self.backend.describe(sql) + } +} diff --git a/vendor/sqlx-core/src/any/connection/mod.rs b/vendor/sqlx-core/src/any/connection/mod.rs new file mode 100755 index 0000000..894b109 --- /dev/null +++ b/vendor/sqlx-core/src/any/connection/mod.rs @@ -0,0 +1,151 @@ +use futures_core::future::BoxFuture; +use std::future::Future; + +use crate::any::{Any, AnyConnectOptions}; +use crate::connection::{ConnectOptions, Connection}; +use crate::error::Error; + +use crate::config; +use crate::database::Database; +use crate::sql_str::SqlSafeStr; +use crate::transaction::Transaction; +pub use backend::AnyConnectionBackend; + +mod backend; +mod executor; + +/// A connection to _any_ SQLx database. +/// +/// The database driver used is determined by the scheme +/// of the connection url. +/// +/// ```text +/// postgres://postgres@localhost/test +/// sqlite://a.sqlite +/// ``` +#[derive(Debug)] +pub struct AnyConnection { + pub(crate) backend: Box, +} + +impl AnyConnection { + /// Returns the name of the database backend in use (e.g. PostgreSQL, MySQL, SQLite, etc.) + pub fn backend_name(&self) -> &str { + self.backend.name() + } + + pub(crate) fn connect(options: &AnyConnectOptions) -> BoxFuture<'_, crate::Result> { + Box::pin(async { + let driver = crate::any::driver::from_url(&options.database_url)?; + (*driver.connect)(options, None).await + }) + } + + /// UNSTABLE: for use with `sqlx-cli` + /// + /// Connect to the database, and instruct the nested driver to + /// read options from the sqlx.toml file as appropriate. + #[doc(hidden)] + pub async fn connect_with_driver_config( + url: &str, + driver_config: &config::drivers::Config, + ) -> Result + where + Self: Sized, + { + let options: AnyConnectOptions = url.parse()?; + + let driver = crate::any::driver::from_url(&options.database_url)?; + (*driver.connect)(&options, Some(driver_config)).await + } + + pub(crate) fn connect_with_db<'a, DB: Database>( + options: &'a AnyConnectOptions, + driver_config: Option<&'a config::drivers::Config>, + ) -> BoxFuture<'a, crate::Result> + where + DB::Connection: AnyConnectionBackend, + ::Options: + for<'b> TryFrom<&'b AnyConnectOptions, Error = Error>, + { + let res = TryFrom::try_from(options); + + Box::pin(async move { + let mut options: ::Options = res?; + + if let Some(config) = driver_config { + options = options.__unstable_apply_driver_config(config)?; + } + + Ok(AnyConnection { + backend: Box::new(options.connect().await?), + }) + }) + } + + #[cfg(feature = "migrate")] + pub(crate) fn get_migrate( + &mut self, + ) -> crate::Result<&mut (dyn crate::migrate::Migrate + Send + 'static)> { + self.backend.as_migrate() + } +} + +impl Connection for AnyConnection { + type Database = Any; + + type Options = AnyConnectOptions; + + fn close(self) -> impl Future> + Send + 'static { + self.backend.close() + } + + fn close_hard(self) -> impl Future> + Send + 'static { + self.backend.close() + } + + fn ping(&mut self) -> impl Future> + Send + '_ { + self.backend.ping() + } + + fn begin( + &mut self, + ) -> impl Future, Error>> + Send + '_ + where + Self: Sized, + { + Transaction::begin(self, None) + } + + fn begin_with( + &mut self, + statement: impl SqlSafeStr, + ) -> impl Future, Error>> + Send + '_ + where + Self: Sized, + { + Transaction::begin(self, Some(statement.into_sql_str())) + } + + fn cached_statements_size(&self) -> usize { + self.backend.cached_statements_size() + } + + fn clear_cached_statements(&mut self) -> impl Future> + Send + '_ { + self.backend.clear_cached_statements() + } + + fn shrink_buffers(&mut self) { + self.backend.shrink_buffers() + } + + #[doc(hidden)] + fn flush(&mut self) -> impl Future> + Send + '_ { + self.backend.flush() + } + + #[doc(hidden)] + fn should_flush(&self) -> bool { + self.backend.should_flush() + } +} diff --git a/vendor/sqlx-core/src/any/database.rs b/vendor/sqlx-core/src/any/database.rs new file mode 100755 index 0000000..6dd4700 --- /dev/null +++ b/vendor/sqlx-core/src/any/database.rs @@ -0,0 +1,39 @@ +use crate::any::{ + AnyArgumentBuffer, AnyArguments, AnyColumn, AnyConnection, AnyQueryResult, AnyRow, + AnyStatement, AnyTransactionManager, AnyTypeInfo, AnyValue, AnyValueRef, +}; +use crate::database::{Database, HasStatementCache}; + +/// Opaque database driver. Capable of being used in place of any SQLx database driver. The actual +/// driver used will be selected at runtime, from the connection url. +#[derive(Debug)] +pub struct Any; + +impl Database for Any { + type Connection = AnyConnection; + + type TransactionManager = AnyTransactionManager; + + type Row = AnyRow; + + type QueryResult = AnyQueryResult; + + type Column = AnyColumn; + + type TypeInfo = AnyTypeInfo; + + type Value = AnyValue; + type ValueRef<'r> = AnyValueRef<'r>; + + type Arguments = AnyArguments; + type ArgumentBuffer = AnyArgumentBuffer; + + type Statement = AnyStatement; + + const NAME: &'static str = "Any"; + + const URL_SCHEMES: &'static [&'static str] = &[]; +} + +// This _may_ be true, depending on the selected database +impl HasStatementCache for Any {} diff --git a/vendor/sqlx-core/src/any/driver.rs b/vendor/sqlx-core/src/any/driver.rs new file mode 100755 index 0000000..58294fa --- /dev/null +++ b/vendor/sqlx-core/src/any/driver.rs @@ -0,0 +1,155 @@ +use crate::any::connection::AnyConnectionBackend; +use crate::any::{AnyConnectOptions, AnyConnection}; +use crate::common::DebugFn; +use crate::connection::Connection; +use crate::database::Database; +use crate::{config, Error}; +use futures_core::future::BoxFuture; +use std::fmt::{Debug, Formatter}; +use std::sync::OnceLock; +use url::Url; + +static DRIVERS: OnceLock<&'static [AnyDriver]> = OnceLock::new(); + +#[macro_export] +macro_rules! declare_driver_with_optional_migrate { + ($name:ident = $db:path) => { + #[cfg(feature = "migrate")] + pub const $name: $crate::any::driver::AnyDriver = + $crate::any::driver::AnyDriver::with_migrate::<$db>(); + + #[cfg(not(feature = "migrate"))] + pub const $name: $crate::any::driver::AnyDriver = + $crate::any::driver::AnyDriver::without_migrate::<$db>(); + }; +} + +#[non_exhaustive] +pub struct AnyDriver { + pub(crate) name: &'static str, + pub(crate) url_schemes: &'static [&'static str], + pub(crate) connect: DebugFn< + for<'a> fn( + &'a AnyConnectOptions, + Option<&'a config::drivers::Config>, + ) -> BoxFuture<'a, crate::Result>, + >, + pub(crate) migrate_database: Option, +} + +impl AnyDriver { + pub const fn without_migrate() -> Self + where + DB::Connection: AnyConnectionBackend, + ::Options: + for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>, + { + Self { + name: DB::NAME, + url_schemes: DB::URL_SCHEMES, + connect: DebugFn(AnyConnection::connect_with_db::), + migrate_database: None, + } + } + + #[cfg(not(feature = "migrate"))] + pub const fn with_migrate() -> Self + where + DB::Connection: AnyConnectionBackend, + ::Options: + for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>, + { + Self::without_migrate::() + } + + #[cfg(feature = "migrate")] + pub const fn with_migrate() -> Self + where + DB::Connection: AnyConnectionBackend, + ::Options: + for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>, + { + Self { + migrate_database: Some(AnyMigrateDatabase { + create_database: DebugFn(|url| Box::pin(DB::create_database(url))), + database_exists: DebugFn(|url| Box::pin(DB::database_exists(url))), + drop_database: DebugFn(|url| Box::pin(DB::drop_database(url))), + force_drop_database: DebugFn(|url| Box::pin(DB::force_drop_database(url))), + }), + ..Self::without_migrate::() + } + } + + pub fn get_migrate_database(&self) -> crate::Result<&AnyMigrateDatabase> { + self.migrate_database.as_ref() + .ok_or_else(|| Error::Configuration(format!("{} driver does not support migrations or the `migrate` feature was not enabled for it", self.name).into())) + } +} + +impl Debug for AnyDriver { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AnyDriver") + .field("name", &self.name) + .field("url_schemes", &self.url_schemes) + .finish() + } +} + +pub struct AnyMigrateDatabase { + create_database: DebugFn BoxFuture<'_, crate::Result<()>>>, + database_exists: DebugFn BoxFuture<'_, crate::Result>>, + drop_database: DebugFn BoxFuture<'_, crate::Result<()>>>, + force_drop_database: DebugFn BoxFuture<'_, crate::Result<()>>>, +} + +impl AnyMigrateDatabase { + pub fn create_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> { + (self.create_database)(url) + } + + pub fn database_exists<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result> { + (self.database_exists)(url) + } + + pub fn drop_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> { + (self.drop_database)(url) + } + + pub fn force_drop_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> { + (self.force_drop_database)(url) + } +} + +/// Install the list of drivers for [`AnyConnection`] to use. +/// +/// Must be called before an `AnyConnection` or `AnyPool` can be connected. +/// +/// ### Errors +/// If called more than once. +pub fn install_drivers( + drivers: &'static [AnyDriver], +) -> Result<(), Box> { + DRIVERS + .set(drivers) + .map_err(|_| "drivers already installed".into()) +} + +#[cfg(feature = "migrate")] +pub(crate) fn from_url_str(url: &str) -> crate::Result<&'static AnyDriver> { + from_url(&url.parse().map_err(Error::config)?) +} + +pub(crate) fn from_url(url: &Url) -> crate::Result<&'static AnyDriver> { + let scheme = url.scheme(); + + let drivers: &[AnyDriver] = DRIVERS + .get() + .expect("No drivers installed. Please see the documentation in `sqlx::any` for details."); + + drivers + .iter() + .find(|driver| driver.url_schemes.contains(&url.scheme())) + .ok_or_else(|| { + Error::Configuration(format!("no driver found for URL scheme {scheme:?}").into()) + }) +} diff --git a/vendor/sqlx-core/src/any/error.rs b/vendor/sqlx-core/src/any/error.rs new file mode 100755 index 0000000..7d4a5f1 --- /dev/null +++ b/vendor/sqlx-core/src/any/error.rs @@ -0,0 +1,16 @@ +use std::any::type_name; + +use crate::any::type_info::AnyTypeInfo; +use crate::any::Any; +use crate::error::BoxDynError; +use crate::type_info::TypeInfo; +use crate::types::Type; + +pub(super) fn mismatched_types>(ty: &AnyTypeInfo) -> BoxDynError { + format!( + "mismatched types; Rust type `{}` is not compatible with SQL type `{}`", + type_name::(), + ty.name() + ) + .into() +} diff --git a/vendor/sqlx-core/src/any/kind.rs b/vendor/sqlx-core/src/any/kind.rs new file mode 100755 index 0000000..60397c0 --- /dev/null +++ b/vendor/sqlx-core/src/any/kind.rs @@ -0,0 +1,74 @@ +// Annoying how deprecation warnings trigger in the same module as the deprecated item. +#![allow(deprecated)] +// Cargo features are broken in this file. +// `AnyKind` may return at some point but it won't be a simple enum. +#![allow(unexpected_cfgs)] + +use crate::error::Error; +use std::str::FromStr; + +#[deprecated = "not used or returned by any API"] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum AnyKind { + #[cfg(feature = "postgres")] + Postgres, + + #[cfg(feature = "mysql")] + MySql, + + #[cfg(feature = "_sqlite")] + Sqlite, + + #[cfg(feature = "mssql")] + Mssql, +} + +impl FromStr for AnyKind { + type Err = Error; + + fn from_str(url: &str) -> Result { + match url { + #[cfg(feature = "postgres")] + _ if url.starts_with("postgres:") || url.starts_with("postgresql:") => { + Ok(AnyKind::Postgres) + } + + #[cfg(not(feature = "postgres"))] + _ if url.starts_with("postgres:") || url.starts_with("postgresql:") => { + Err(Error::Configuration("database URL has the scheme of a PostgreSQL database but the `postgres` feature is not enabled".into())) + } + + #[cfg(feature = "mysql")] + _ if url.starts_with("mysql:") || url.starts_with("mariadb:") => { + Ok(AnyKind::MySql) + } + + #[cfg(not(feature = "mysql"))] + _ if url.starts_with("mysql:") || url.starts_with("mariadb:") => { + Err(Error::Configuration("database URL has the scheme of a MySQL database but the `mysql` feature is not enabled".into())) + } + + #[cfg(feature = "_sqlite")] + _ if url.starts_with("sqlite:") => { + Ok(AnyKind::Sqlite) + } + + #[cfg(not(feature = "_sqlite"))] + _ if url.starts_with("sqlite:") => { + Err(Error::Configuration("database URL has the scheme of a SQLite database but the `sqlite` feature is not enabled".into())) + } + + #[cfg(feature = "mssql")] + _ if url.starts_with("mssql:") || url.starts_with("sqlserver:") => { + Ok(AnyKind::Mssql) + } + + #[cfg(not(feature = "mssql"))] + _ if url.starts_with("mssql:") || url.starts_with("sqlserver:") => { + Err(Error::Configuration("database URL has the scheme of a MSSQL database but the `mssql` feature is not enabled".into())) + } + + _ => Err(Error::Configuration(format!("unrecognized database url: {url:?}").into())) + } + } +} diff --git a/vendor/sqlx-core/src/any/migrate.rs b/vendor/sqlx-core/src/any/migrate.rs new file mode 100755 index 0000000..deca501 --- /dev/null +++ b/vendor/sqlx-core/src/any/migrate.rs @@ -0,0 +1,110 @@ +use crate::any::driver; +use crate::any::{Any, AnyConnection}; +use crate::error::Error; +use crate::migrate::{AppliedMigration, Migrate, MigrateDatabase, MigrateError, Migration}; +use futures_core::future::BoxFuture; +use std::time::Duration; + +impl MigrateDatabase for Any { + async fn create_database(url: &str) -> Result<(), Error> { + driver::from_url_str(url)? + .get_migrate_database()? + .create_database(url) + .await + } + + async fn database_exists(url: &str) -> Result { + driver::from_url_str(url)? + .get_migrate_database()? + .database_exists(url) + .await + } + + async fn drop_database(url: &str) -> Result<(), Error> { + driver::from_url_str(url)? + .get_migrate_database()? + .drop_database(url) + .await + } + + async fn force_drop_database(url: &str) -> Result<(), Error> { + driver::from_url_str(url)? + .get_migrate_database()? + .force_drop_database(url) + .await + } +} + +impl Migrate for AnyConnection { + fn create_schema_if_not_exists<'e>( + &'e mut self, + schema_name: &'e str, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async { + self.get_migrate()? + .create_schema_if_not_exists(schema_name) + .await + }) + } + + fn ensure_migrations_table<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async { + self.get_migrate()? + .ensure_migrations_table(table_name) + .await + }) + } + + fn dirty_version<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result, MigrateError>> { + Box::pin(async { self.get_migrate()?.dirty_version(table_name).await }) + } + + fn list_applied_migrations<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result, MigrateError>> { + Box::pin(async { + self.get_migrate()? + .list_applied_migrations(table_name) + .await + }) + } + + fn lock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> { + Box::pin(async { self.get_migrate()?.lock().await }) + } + + fn unlock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> { + Box::pin(async { self.get_migrate()?.unlock().await }) + } + + fn apply<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result> { + Box::pin(async { self.get_migrate()?.apply(table_name, migration).await }) + } + + fn revert<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result> { + Box::pin(async { self.get_migrate()?.revert(table_name, migration).await }) + } + + fn skip<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async { self.get_migrate()?.skip(table_name, migration).await }) + } +} diff --git a/vendor/sqlx-core/src/any/mod.rs b/vendor/sqlx-core/src/any/mod.rs new file mode 100755 index 0000000..9d37bbf --- /dev/null +++ b/vendor/sqlx-core/src/any/mod.rs @@ -0,0 +1,83 @@ +//! **SEE DOCUMENTATION BEFORE USE**. Generic database driver with the specific driver selected at runtime. +//! +//! The underlying database drivers are chosen at runtime from the list set via +//! [`install_drivers`][self::driver::install_drivers]. Any use of `AnyConnection` or `AnyPool` +//! without this will panic. +use crate::executor::Executor; + +mod arguments; +pub(crate) mod column; +mod connection; +mod database; +mod error; +mod kind; +mod options; +mod query_result; +pub(crate) mod row; +mod statement; +mod transaction; +pub(crate) mod type_info; +pub mod types; +pub(crate) mod value; + +pub mod driver; + +#[cfg(feature = "migrate")] +mod migrate; + +pub use arguments::{AnyArgumentBuffer, AnyArguments}; +pub use column::AnyColumn; +pub use connection::AnyConnection; +// Used internally in `sqlx-macros` + +use crate::encode::Encode; +pub use connection::AnyConnectionBackend; +pub use database::Any; +#[allow(deprecated)] +pub use kind::AnyKind; +pub use options::AnyConnectOptions; +pub use query_result::AnyQueryResult; +pub use row::AnyRow; +pub use statement::AnyStatement; +pub use transaction::AnyTransactionManager; +pub use type_info::{AnyTypeInfo, AnyTypeInfoKind}; +pub use value::{AnyValue, AnyValueRef}; + +use crate::types::Type; +#[doc(hidden)] +pub use value::AnyValueKind; + +pub type AnyPool = crate::pool::Pool; + +pub type AnyPoolOptions = crate::pool::PoolOptions; + +/// An alias for [`Executor<'_, Database = Any>`][Executor]. +pub trait AnyExecutor<'c>: Executor<'c, Database = Any> {} +impl<'c, T: Executor<'c, Database = Any>> AnyExecutor<'c> for T {} + +// NOTE: required due to the lack of lazy normalization +impl_into_arguments_for_arguments!(AnyArguments); +// impl_executor_for_pool_connection!(Any, AnyConnection, AnyRow); +// impl_executor_for_transaction!(Any, AnyRow); +impl_acquire!(Any, AnyConnection); +impl_column_index_for_row!(AnyRow); +impl_column_index_for_statement!(AnyStatement); +// impl_into_maybe_pool!(Any, AnyConnection); + +// required because some databases have a different handling of NULL +impl<'q, T> Encode<'q, Any> for Option +where + T: Encode<'q, Any> + 'q + Type, +{ + fn encode_by_ref( + &self, + buf: &mut AnyArgumentBuffer, + ) -> Result { + if let Some(value) = self { + value.encode_by_ref(buf) + } else { + buf.0.push(AnyValueKind::Null(T::type_info().kind)); + Ok(crate::encode::IsNull::Yes) + } + } +} diff --git a/vendor/sqlx-core/src/any/options.rs b/vendor/sqlx-core/src/any/options.rs new file mode 100755 index 0000000..724060f --- /dev/null +++ b/vendor/sqlx-core/src/any/options.rs @@ -0,0 +1,67 @@ +use crate::any::AnyConnection; +use crate::connection::{ConnectOptions, LogSettings}; +use crate::error::Error; +use log::LevelFilter; +use std::future::Future; +use std::str::FromStr; +use std::time::Duration; +use url::Url; + +/// Opaque options for connecting to a database. These may only be constructed by parsing from +/// a connection url. +/// +/// ```text +/// postgres://postgres:password@localhost/database +/// mysql://root:password@localhost/database +/// ``` +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct AnyConnectOptions { + pub database_url: Url, + pub log_settings: LogSettings, +} +impl FromStr for AnyConnectOptions { + type Err = Error; + + fn from_str(url: &str) -> Result { + Ok(AnyConnectOptions { + database_url: url + .parse::() + .map_err(|e| Error::Configuration(e.into()))?, + log_settings: LogSettings::default(), + }) + } +} + +impl ConnectOptions for AnyConnectOptions { + type Connection = AnyConnection; + + fn from_url(url: &Url) -> Result { + Ok(AnyConnectOptions { + database_url: url.clone(), + log_settings: LogSettings::default(), + }) + } + + fn to_url_lossy(&self) -> Url { + self.database_url.clone() + } + + #[inline] + fn connect(&self) -> impl Future> + Send + '_ { + AnyConnection::connect(self) + } + + fn log_statements(mut self, level: LevelFilter) -> Self { + self.log_settings.statements_level = level; + self + } + + fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self { + self.log_settings.slow_statements_level = level; + self.log_settings.slow_statements_duration = duration; + self + } +} + +impl AnyConnectOptions {} diff --git a/vendor/sqlx-core/src/any/query_result.rs b/vendor/sqlx-core/src/any/query_result.rs new file mode 100755 index 0000000..f594e06 --- /dev/null +++ b/vendor/sqlx-core/src/any/query_result.rs @@ -0,0 +1,28 @@ +use std::iter::{Extend, IntoIterator}; + +#[derive(Debug, Default)] +pub struct AnyQueryResult { + #[doc(hidden)] + pub rows_affected: u64, + #[doc(hidden)] + pub last_insert_id: Option, +} + +impl AnyQueryResult { + pub fn rows_affected(&self) -> u64 { + self.rows_affected + } + + pub fn last_insert_id(&self) -> Option { + self.last_insert_id + } +} + +impl Extend for AnyQueryResult { + fn extend>(&mut self, iter: T) { + for elem in iter { + self.rows_affected += elem.rows_affected; + self.last_insert_id = elem.last_insert_id; + } + } +} diff --git a/vendor/sqlx-core/src/any/row.rs b/vendor/sqlx-core/src/any/row.rs new file mode 100755 index 0000000..57b8590 --- /dev/null +++ b/vendor/sqlx-core/src/any/row.rs @@ -0,0 +1,144 @@ +use crate::any::error::mismatched_types; +use crate::any::{Any, AnyColumn, AnyTypeInfo, AnyTypeInfoKind, AnyValue, AnyValueKind}; +use crate::column::{Column, ColumnIndex}; +use crate::database::Database; +use crate::decode::Decode; +use crate::error::Error; +use crate::ext::ustr::UStr; +use crate::row::Row; +use crate::type_info::TypeInfo; +use crate::types::Type; +use crate::value::{Value, ValueRef}; +use std::sync::Arc; + +#[derive(Clone)] +pub struct AnyRow { + #[doc(hidden)] + pub column_names: Arc>, + #[doc(hidden)] + pub columns: Vec, + #[doc(hidden)] + pub values: Vec, +} + +impl Row for AnyRow { + type Database = Any; + + fn columns(&self) -> &[AnyColumn] { + &self.columns + } + + fn try_get_raw(&self, index: I) -> Result<::ValueRef<'_>, Error> + where + I: ColumnIndex, + { + let index = index.index(self)?; + Ok(self + .values + .get(index) + .ok_or_else(|| Error::ColumnIndexOutOfBounds { + index, + len: self.columns.len(), + })? + .as_ref()) + } + + fn try_get<'r, T, I>(&'r self, index: I) -> Result + where + I: ColumnIndex, + T: Decode<'r, Self::Database> + Type, + { + let value = self.try_get_raw(&index)?; + let ty = value.type_info(); + + if !value.is_null() && !ty.is_null() && !T::compatible(&ty) { + Err(mismatched_types::(&ty)) + } else { + T::decode(value) + } + .map_err(|source| Error::ColumnDecode { + index: format!("{index:?}"), + source, + }) + } +} + +impl ColumnIndex for &'_ str { + fn index(&self, row: &AnyRow) -> Result { + row.column_names + .get(*self) + .copied() + .ok_or_else(|| Error::ColumnNotFound(self.to_string())) + } +} + +impl AnyRow { + // This is not a `TryFrom` impl because trait impls are easy for users to accidentally + // become reliant upon, even if hidden, but we want to be able to change the bounds + // on this function as the `Any` driver gains support for more types. + // + // Also `column_names` needs to be passed by the driver to avoid making deep copies. + #[doc(hidden)] + pub fn map_from<'a, R: Row>( + row: &'a R, + column_names: Arc>, + ) -> Result + where + usize: ColumnIndex, + AnyTypeInfo: for<'b> TryFrom<&'b ::TypeInfo, Error = Error>, + AnyColumn: for<'b> TryFrom<&'b ::Column, Error = Error>, + bool: Type + Decode<'a, R::Database>, + i16: Type + Decode<'a, R::Database>, + i32: Type + Decode<'a, R::Database>, + i64: Type + Decode<'a, R::Database>, + f32: Type + Decode<'a, R::Database>, + f64: Type + Decode<'a, R::Database>, + String: Type + Decode<'a, R::Database>, + Vec: Type + Decode<'a, R::Database>, + { + let mut row_out = AnyRow { + column_names, + columns: Vec::with_capacity(row.columns().len()), + values: Vec::with_capacity(row.columns().len()), + }; + + for col in row.columns() { + let i = col.ordinal(); + + let any_col = AnyColumn::try_from(col)?; + + let value = row.try_get_raw(i)?; + + // Map based on the _value_ type info, not the column type info. + let type_info = + AnyTypeInfo::try_from(&value.type_info()).map_err(|e| Error::ColumnDecode { + index: col.ordinal().to_string(), + source: e.into(), + })?; + + let value_kind = match type_info.kind { + k if value.is_null() => AnyValueKind::Null(k), + AnyTypeInfoKind::Null => AnyValueKind::Null(AnyTypeInfoKind::Null), + AnyTypeInfoKind::Bool => AnyValueKind::Bool(decode(value)?), + AnyTypeInfoKind::SmallInt => AnyValueKind::SmallInt(decode(value)?), + AnyTypeInfoKind::Integer => AnyValueKind::Integer(decode(value)?), + AnyTypeInfoKind::BigInt => AnyValueKind::BigInt(decode(value)?), + AnyTypeInfoKind::Real => AnyValueKind::Real(decode(value)?), + AnyTypeInfoKind::Double => AnyValueKind::Double(decode(value)?), + AnyTypeInfoKind::Blob => AnyValueKind::Blob(decode::<_, Vec>(value)?.into()), + AnyTypeInfoKind::Text => AnyValueKind::Text(decode::<_, String>(value)?.into()), + }; + + row_out.columns.push(any_col); + row_out.values.push(AnyValue { kind: value_kind }); + } + + Ok(row_out) + } +} + +fn decode<'r, DB: Database, T: Decode<'r, DB>>( + valueref: ::ValueRef<'r>, +) -> crate::Result { + Decode::decode(valueref).map_err(Error::decode) +} diff --git a/vendor/sqlx-core/src/any/statement.rs b/vendor/sqlx-core/src/any/statement.rs new file mode 100755 index 0000000..42c7255 --- /dev/null +++ b/vendor/sqlx-core/src/any/statement.rs @@ -0,0 +1,95 @@ +use crate::any::{Any, AnyArguments, AnyColumn, AnyTypeInfo}; +use crate::column::ColumnIndex; +use crate::database::Database; +use crate::error::Error; +use crate::ext::ustr::UStr; +use crate::sql_str::SqlStr; +use crate::statement::Statement; +use crate::HashMap; +use either::Either; +use std::sync::Arc; + +#[derive(Clone)] +pub struct AnyStatement { + #[doc(hidden)] + pub sql: SqlStr, + #[doc(hidden)] + pub parameters: Option, usize>>, + #[doc(hidden)] + pub column_names: Arc>, + #[doc(hidden)] + pub columns: Vec, +} + +impl Statement for AnyStatement { + type Database = Any; + + fn into_sql(self) -> SqlStr { + self.sql + } + + fn sql(&self) -> &SqlStr { + &self.sql + } + + fn parameters(&self) -> Option> { + match &self.parameters { + Some(Either::Left(types)) => Some(Either::Left(types)), + Some(Either::Right(count)) => Some(Either::Right(*count)), + None => None, + } + } + + fn columns(&self) -> &[AnyColumn] { + &self.columns + } + + impl_statement_query!(AnyArguments); +} + +impl ColumnIndex for &'_ str { + fn index(&self, statement: &AnyStatement) -> Result { + statement + .column_names + .get(*self) + .ok_or_else(|| Error::ColumnNotFound((*self).into())) + .copied() + } +} + +impl AnyStatement { + #[doc(hidden)] + pub fn try_from_statement( + statement: S, + column_names: Arc>, + ) -> crate::Result + where + S: Statement, + AnyTypeInfo: for<'a> TryFrom<&'a ::TypeInfo, Error = Error>, + AnyColumn: for<'a> TryFrom<&'a ::Column, Error = Error>, + { + let parameters = match statement.parameters() { + Some(Either::Left(parameters)) => Some(Either::Left( + parameters + .iter() + .map(AnyTypeInfo::try_from) + .collect::, _>>()?, + )), + Some(Either::Right(count)) => Some(Either::Right(count)), + None => None, + }; + + let columns = statement + .columns() + .iter() + .map(AnyColumn::try_from) + .collect::, _>>()?; + + Ok(Self { + sql: statement.into_sql(), + columns, + column_names, + parameters, + }) + } +} diff --git a/vendor/sqlx-core/src/any/transaction.rs b/vendor/sqlx-core/src/any/transaction.rs new file mode 100755 index 0000000..c803e97 --- /dev/null +++ b/vendor/sqlx-core/src/any/transaction.rs @@ -0,0 +1,36 @@ +use std::future::Future; + +use crate::any::{Any, AnyConnection}; +use crate::database::Database; +use crate::error::Error; +use crate::sql_str::SqlStr; +use crate::transaction::TransactionManager; + +pub struct AnyTransactionManager; + +impl TransactionManager for AnyTransactionManager { + type Database = Any; + + fn begin( + conn: &mut AnyConnection, + statement: Option, + ) -> impl Future> + Send + '_ { + conn.backend.begin(statement) + } + + fn commit(conn: &mut AnyConnection) -> impl Future> + Send + '_ { + conn.backend.commit() + } + + fn rollback(conn: &mut AnyConnection) -> impl Future> + Send + '_ { + conn.backend.rollback() + } + + fn start_rollback(conn: &mut AnyConnection) { + conn.backend.start_rollback() + } + + fn get_transaction_depth(conn: &::Connection) -> usize { + conn.backend.get_transaction_depth() + } +} diff --git a/vendor/sqlx-core/src/any/type_info.rs b/vendor/sqlx-core/src/any/type_info.rs new file mode 100755 index 0000000..0879b33 --- /dev/null +++ b/vendor/sqlx-core/src/any/type_info.rs @@ -0,0 +1,64 @@ +use std::fmt::{self, Display, Formatter}; + +use crate::type_info::TypeInfo; + +use AnyTypeInfoKind::*; + +#[derive(Debug, Clone, PartialEq)] +pub struct AnyTypeInfo { + #[doc(hidden)] + pub kind: AnyTypeInfoKind, +} + +impl AnyTypeInfo { + pub fn kind(&self) -> AnyTypeInfoKind { + self.kind + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AnyTypeInfoKind { + Null, + Bool, + SmallInt, + Integer, + BigInt, + Real, + Double, + Text, + Blob, +} + +impl TypeInfo for AnyTypeInfo { + fn is_null(&self) -> bool { + self.kind == Null + } + + fn name(&self) -> &str { + use AnyTypeInfoKind::*; + + match self.kind { + Bool => "BOOLEAN", + SmallInt => "SMALLINT", + Integer => "INTEGER", + BigInt => "BIGINT", + Real => "REAL", + Double => "DOUBLE", + Text => "TEXT", + Blob => "BLOB", + Null => "NULL", + } + } +} + +impl Display for AnyTypeInfo { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +impl AnyTypeInfoKind { + pub fn is_integer(&self) -> bool { + matches!(self, SmallInt | Integer | BigInt) + } +} diff --git a/vendor/sqlx-core/src/any/types/blob.rs b/vendor/sqlx-core/src/any/types/blob.rs new file mode 100755 index 0000000..c6c82dd --- /dev/null +++ b/vendor/sqlx-core/src/any/types/blob.rs @@ -0,0 +1,59 @@ +use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind}; +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; +use std::sync::Arc; + +impl Type for [u8] { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::Blob, + } + } +} + +impl<'q> Encode<'q, Any> for &'q [u8] { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::Blob(Arc::new(self.to_vec()))); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for &'r [u8] { + fn decode(value: ::ValueRef<'r>) -> Result { + match value.kind { + AnyValueKind::Blob(blob) => Ok(blob.as_slice()), + other => other.unexpected(), + } + } +} + +impl Type for Vec { + fn type_info() -> AnyTypeInfo { + <[u8] as Type>::type_info() + } +} + +impl Encode<'_, Any> for Vec { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::Blob(Arc::new(self.clone()))); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for Vec { + fn decode(value: ::ValueRef<'r>) -> Result { + match value.kind { + AnyValueKind::Blob(blob) => Ok(blob.as_ref().clone()), + other => other.unexpected(), + } + } +} diff --git a/vendor/sqlx-core/src/any/types/bool.rs b/vendor/sqlx-core/src/any/types/bool.rs new file mode 100755 index 0000000..bc143e9 --- /dev/null +++ b/vendor/sqlx-core/src/any/types/bool.rs @@ -0,0 +1,33 @@ +use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind}; +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; + +impl Type for bool { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::Bool, + } + } +} + +impl Encode<'_, Any> for bool { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::Bool(*self)); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for bool { + fn decode(value: ::ValueRef<'r>) -> Result { + match value.kind { + AnyValueKind::Bool(b) => Ok(*b), + other => other.unexpected(), + } + } +} diff --git a/vendor/sqlx-core/src/any/types/float.rs b/vendor/sqlx-core/src/any/types/float.rs new file mode 100755 index 0000000..119e5ca --- /dev/null +++ b/vendor/sqlx-core/src/any/types/float.rs @@ -0,0 +1,59 @@ +use crate::any::{Any, AnyArgumentBuffer, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind, AnyValueRef}; +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; + +impl Type for f32 { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::Real, + } + } +} + +impl Encode<'_, Any> for f32 { + fn encode_by_ref(&self, buf: &mut AnyArgumentBuffer) -> Result { + buf.0.push(AnyValueKind::Real(*self)); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for f32 { + fn decode(value: AnyValueRef<'r>) -> Result { + match value.kind { + AnyValueKind::Real(r) => Ok(*r), + other => other.unexpected(), + } + } +} + +impl Type for f64 { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::Double, + } + } +} + +impl Encode<'_, Any> for f64 { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::Double(*self)); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for f64 { + fn decode(value: ::ValueRef<'r>) -> Result { + match value.kind { + // Widening is safe + AnyValueKind::Real(r) => Ok(*r as f64), + AnyValueKind::Double(d) => Ok(*d), + other => other.unexpected(), + } + } +} diff --git a/vendor/sqlx-core/src/any/types/int.rs b/vendor/sqlx-core/src/any/types/int.rs new file mode 100755 index 0000000..e2bb432 --- /dev/null +++ b/vendor/sqlx-core/src/any/types/int.rs @@ -0,0 +1,90 @@ +use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind}; +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; + +impl Type for i16 { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::SmallInt, + } + } + + fn compatible(ty: &AnyTypeInfo) -> bool { + ty.kind().is_integer() + } +} + +impl Encode<'_, Any> for i16 { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::SmallInt(*self)); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for i16 { + fn decode(value: ::ValueRef<'r>) -> Result { + value.kind.try_integer() + } +} + +impl Type for i32 { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::Integer, + } + } + + fn compatible(ty: &AnyTypeInfo) -> bool { + ty.kind().is_integer() + } +} + +impl Encode<'_, Any> for i32 { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::Integer(*self)); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for i32 { + fn decode(value: ::ValueRef<'r>) -> Result { + value.kind.try_integer() + } +} + +impl Type for i64 { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::BigInt, + } + } + + fn compatible(ty: &AnyTypeInfo) -> bool { + ty.kind().is_integer() + } +} + +impl Encode<'_, Any> for i64 { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::BigInt(*self)); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for i64 { + fn decode(value: ::ValueRef<'r>) -> Result { + value.kind.try_integer() + } +} diff --git a/vendor/sqlx-core/src/any/types/mod.rs b/vendor/sqlx-core/src/any/types/mod.rs new file mode 100755 index 0000000..a0ae551 --- /dev/null +++ b/vendor/sqlx-core/src/any/types/mod.rs @@ -0,0 +1,53 @@ +//! Conversions between Rust and standard **SQL** types. +//! +//! # Types +//! +//! | Rust type | SQL type(s) | +//! |---------------------------------------|------------------------------------------------------| +//! | `bool` | BOOLEAN | +//! | `i16` | SMALLINT | +//! | `i32` | INT | +//! | `i64` | BIGINT | +//! | `f32` | FLOAT | +//! | `f64` | DOUBLE | +//! | `&str`, [`String`] | VARCHAR, CHAR, TEXT | +//! +//! # Nullable +//! +//! In addition, `Option` is supported where `T` implements `Type`. An `Option` represents +//! a potentially `NULL` value from SQL. + +mod blob; +mod bool; +mod float; +mod int; +mod str; + +#[test] +fn test_type_impls() { + use crate::any::Any; + use crate::decode::Decode; + use crate::encode::Encode; + use crate::types::Type; + + fn has_type() + where + T: Type, + for<'a> T: Encode<'a, Any>, + for<'a> T: Decode<'a, Any>, + { + } + + has_type::(); + + has_type::(); + has_type::(); + has_type::(); + + has_type::(); + has_type::(); + + // These imply that there are also impls for the equivalent slice types. + has_type::>(); + has_type::(); +} diff --git a/vendor/sqlx-core/src/any/types/str.rs b/vendor/sqlx-core/src/any/types/str.rs new file mode 100755 index 0000000..6202624 --- /dev/null +++ b/vendor/sqlx-core/src/any/types/str.rs @@ -0,0 +1,72 @@ +use crate::any::types::str; +use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind}; +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; +use std::sync::Arc; + +impl Type for str { + fn type_info() -> AnyTypeInfo { + AnyTypeInfo { + kind: AnyTypeInfoKind::Text, + } + } +} + +impl<'a> Encode<'a, Any> for &'a str { + fn encode(self, buf: &mut ::ArgumentBuffer) -> Result + where + Self: Sized, + { + buf.0.push(AnyValueKind::Text(Arc::new(self.into()))); + Ok(IsNull::No) + } + + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + (*self).encode(buf) + } +} + +impl<'a> Decode<'a, Any> for &'a str { + fn decode(value: ::ValueRef<'a>) -> Result { + match value.kind { + AnyValueKind::Text(text) => Ok(text.as_str()), + other => other.unexpected(), + } + } +} + +impl Type for String { + fn type_info() -> AnyTypeInfo { + >::type_info() + } +} + +impl Encode<'_, Any> for String { + fn encode(self, buf: &mut ::ArgumentBuffer) -> Result { + buf.0.push(AnyValueKind::Text(Arc::new(self))); + Ok(IsNull::No) + } + + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + buf.0.push(AnyValueKind::Text(Arc::new(self.clone()))); + Ok(IsNull::No) + } +} + +impl<'r> Decode<'r, Any> for String { + fn decode(value: ::ValueRef<'r>) -> Result { + match value.kind { + AnyValueKind::Text(text) => Ok(text.to_string()), + other => other.unexpected(), + } + } +} diff --git a/vendor/sqlx-core/src/any/value.rs b/vendor/sqlx-core/src/any/value.rs new file mode 100755 index 0000000..a85c1dc --- /dev/null +++ b/vendor/sqlx-core/src/any/value.rs @@ -0,0 +1,105 @@ +use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind}; +use crate::database::Database; +use crate::error::BoxDynError; +use crate::types::Type; +use crate::value::{Value, ValueRef}; +use std::borrow::Cow; +use std::sync::Arc; + +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum AnyValueKind { + Null(AnyTypeInfoKind), + Bool(bool), + SmallInt(i16), + Integer(i32), + BigInt(i64), + Real(f32), + Double(f64), + Text(Arc), + TextSlice(Arc), + Blob(Arc>), +} + +impl AnyValueKind { + fn type_info(&self) -> AnyTypeInfo { + AnyTypeInfo { + kind: match self { + AnyValueKind::Null(_) => AnyTypeInfoKind::Null, + AnyValueKind::Bool(_) => AnyTypeInfoKind::Bool, + AnyValueKind::SmallInt(_) => AnyTypeInfoKind::SmallInt, + AnyValueKind::Integer(_) => AnyTypeInfoKind::Integer, + AnyValueKind::BigInt(_) => AnyTypeInfoKind::BigInt, + AnyValueKind::Real(_) => AnyTypeInfoKind::Real, + AnyValueKind::Double(_) => AnyTypeInfoKind::Double, + AnyValueKind::Text(_) => AnyTypeInfoKind::Text, + AnyValueKind::TextSlice(_) => AnyTypeInfoKind::Text, + AnyValueKind::Blob(_) => AnyTypeInfoKind::Blob, + }, + } + } + + pub(in crate::any) fn unexpected>(&self) -> Result { + Err(format!("expected {}, got {:?}", Expected::type_info(), self).into()) + } + + pub(in crate::any) fn try_integer(&self) -> Result + where + T: Type + TryFrom + TryFrom + TryFrom, + BoxDynError: From<>::Error>, + BoxDynError: From<>::Error>, + BoxDynError: From<>::Error>, + { + Ok(match self { + AnyValueKind::SmallInt(i) => (*i).try_into()?, + AnyValueKind::Integer(i) => (*i).try_into()?, + AnyValueKind::BigInt(i) => (*i).try_into()?, + _ => return self.unexpected(), + }) + } +} + +#[derive(Clone, Debug)] +pub struct AnyValue { + #[doc(hidden)] + pub kind: AnyValueKind, +} + +#[derive(Clone, Debug)] +pub struct AnyValueRef<'a> { + pub(crate) kind: &'a AnyValueKind, +} + +impl Value for AnyValue { + type Database = Any; + + fn as_ref(&self) -> ::ValueRef<'_> { + AnyValueRef { kind: &self.kind } + } + + fn type_info(&self) -> Cow<'_, ::TypeInfo> { + Cow::Owned(self.kind.type_info()) + } + + fn is_null(&self) -> bool { + matches!(self.kind, AnyValueKind::Null(_)) + } +} + +impl<'a> ValueRef<'a> for AnyValueRef<'a> { + type Database = Any; + + fn to_owned(&self) -> ::Value { + AnyValue { + kind: self.kind.clone(), + } + } + + fn type_info(&self) -> Cow<'_, ::TypeInfo> { + Cow::Owned(self.kind.type_info()) + } + + fn is_null(&self) -> bool { + matches!(self.kind, AnyValueKind::Null(_)) + } +} diff --git a/vendor/sqlx-core/src/arguments.rs b/vendor/sqlx-core/src/arguments.rs new file mode 100755 index 0000000..7b9da60 --- /dev/null +++ b/vendor/sqlx-core/src/arguments.rs @@ -0,0 +1,58 @@ +//! Types and traits for passing arguments to SQL queries. + +use crate::database::Database; +use crate::encode::Encode; +use crate::error::BoxDynError; +use crate::types::Type; +use std::fmt::{self, Write}; + +/// A tuple of arguments to be sent to the database. +// This lint is designed for general collections, but `Arguments` is not meant to be as such. +#[allow(clippy::len_without_is_empty)] +pub trait Arguments: Send + Sized + Default { + type Database: Database; + + /// Reserves the capacity for at least `additional` more values (of `size` total bytes) to + /// be added to the arguments without a reallocation. + fn reserve(&mut self, additional: usize, size: usize); + + /// Add the value to the end of the arguments. + fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError> + where + T: Encode<'t, Self::Database> + Type; + + /// The number of arguments that were already added. + fn len(&self) -> usize; + + fn format_placeholder(&self, writer: &mut W) -> fmt::Result { + writer.write_str("?") + } +} + +pub trait IntoArguments: Sized + Send { + fn into_arguments(self) -> ::Arguments; +} + +// NOTE: required due to lack of lazy normalization +#[macro_export] +macro_rules! impl_into_arguments_for_arguments { + ($Arguments:path) => { + impl + $crate::arguments::IntoArguments<<$Arguments as $crate::arguments::Arguments>::Database> + for $Arguments + { + fn into_arguments(self) -> $Arguments { + self + } + } + }; +} + +/// used by the query macros to prevent supernumerary `.bind()` calls +pub struct ImmutableArguments(pub ::Arguments); + +impl IntoArguments for ImmutableArguments { + fn into_arguments(self) -> ::Arguments { + self.0 + } +} diff --git a/vendor/sqlx-core/src/column.rs b/vendor/sqlx-core/src/column.rs new file mode 100755 index 0000000..e9b6aec --- /dev/null +++ b/vendor/sqlx-core/src/column.rs @@ -0,0 +1,145 @@ +use crate::database::Database; +use crate::error::Error; + +use std::fmt::Debug; +use std::sync::Arc; + +pub trait Column: 'static + Send + Sync + Debug { + type Database: Database; + + /// Gets the column ordinal. + /// + /// This can be used to unambiguously refer to this column within a row in case more than + /// one column have the same name + fn ordinal(&self) -> usize; + + /// Gets the column name or alias. + /// + /// The column name is unreliable (and can change between database minor versions) if this + /// column is an expression that has not been aliased. + fn name(&self) -> &str; + + /// Gets the type information for the column. + fn type_info(&self) -> &::TypeInfo; + + /// If this column comes from a table, return the table and original column name. + /// + /// Returns [`ColumnOrigin::Expression`] if the column is the result of an expression + /// or else the source table could not be determined. + /// + /// Returns [`ColumnOrigin::Unknown`] if the database driver does not have that information, + /// or has not overridden this method. + // This method returns an owned value instead of a reference, + // to give the implementor more flexibility. + fn origin(&self) -> ColumnOrigin { + ColumnOrigin::Unknown + } +} + +/// A [`Column`] that originates from a table. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] +pub struct TableColumn { + /// The name of the table (optionally schema-qualified) that the column comes from. + pub table: Arc, + /// The original name of the column. + pub name: Arc, +} + +/// The possible statuses for our knowledge of the origin of a [`Column`]. +#[derive(Debug, Clone, Default)] +#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] +pub enum ColumnOrigin { + /// The column is known to originate from a table. + /// + /// Included is the table name and original column name. + Table(TableColumn), + /// The column originates from an expression, or else its origin could not be determined. + Expression, + /// The database driver does not know the column origin at this time. + /// + /// This may happen if: + /// * The connection is in the middle of executing a query, + /// and cannot query the catalog to fetch this information. + /// * The connection does not have access to the database catalog. + /// * The implementation of [`Column`] did not override [`Column::origin()`]. + #[default] + Unknown, +} + +impl ColumnOrigin { + /// Returns the true column origin, if known. + pub fn table_column(&self) -> Option<&TableColumn> { + if let Self::Table(table_column) = self { + Some(table_column) + } else { + None + } + } +} + +/// A type that can be used to index into a [`Row`] or [`Statement`]. +/// +/// The [`get`] and [`try_get`] methods of [`Row`] accept any type that implements `ColumnIndex`. +/// This trait is implemented for strings which are used to look up a column by name, and for +/// `usize` which is used as a positional index into the row. +/// +/// *Caution*: The column index may differ between a [`Statement`] and a [`Row`] returned by the +/// statement. This can happen with some databases if, for example, the schema changes between +/// prepare and execute or if the database does not provide column information when the statement +/// is prepared. +/// +/// [`Row`]: crate::row::Row +/// [`Statement`]: crate::statement::Statement +/// [`get`]: crate::row::Row::get +/// [`try_get`]: crate::row::Row::try_get +/// +pub trait ColumnIndex: Debug { + /// Returns a valid positional index into the row or statement, [`ColumnIndexOutOfBounds`], or, + /// [`ColumnNotFound`]. + /// + /// [`ColumnNotFound`]: Error::ColumnNotFound + /// [`ColumnIndexOutOfBounds`]: Error::ColumnIndexOutOfBounds + fn index(&self, container: &T) -> Result; +} + +impl + ?Sized> ColumnIndex for &'_ I { + #[inline] + fn index(&self, row: &T) -> Result { + (**self).index(row) + } +} + +#[macro_export] +macro_rules! impl_column_index_for_row { + ($R:ident) => { + impl $crate::column::ColumnIndex<$R> for usize { + fn index(&self, row: &$R) -> Result { + let len = $crate::row::Row::len(row); + + if *self >= len { + return Err($crate::error::Error::ColumnIndexOutOfBounds { len, index: *self }); + } + + Ok(*self) + } + } + }; +} + +#[macro_export] +macro_rules! impl_column_index_for_statement { + ($S:ident) => { + impl $crate::column::ColumnIndex<$S> for usize { + fn index(&self, statement: &$S) -> Result { + let len = $crate::statement::Statement::columns(statement).len(); + + if *self >= len { + return Err($crate::error::Error::ColumnIndexOutOfBounds { len, index: *self }); + } + + Ok(*self) + } + } + }; +} diff --git a/vendor/sqlx-core/src/common/mod.rs b/vendor/sqlx-core/src/common/mod.rs new file mode 100755 index 0000000..7940071 --- /dev/null +++ b/vendor/sqlx-core/src/common/mod.rs @@ -0,0 +1,28 @@ +mod statement_cache; + +pub use statement_cache::StatementCache; +use std::fmt::{Debug, Formatter}; +use std::ops::{Deref, DerefMut}; + +/// A wrapper for `Fn`s that provides a debug impl that just says "Function" +pub struct DebugFn(pub F); + +impl Deref for DebugFn { + type Target = F; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for DebugFn { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl Debug for DebugFn { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Function").finish() + } +} diff --git a/vendor/sqlx-core/src/common/statement_cache.rs b/vendor/sqlx-core/src/common/statement_cache.rs new file mode 100755 index 0000000..eb800ca --- /dev/null +++ b/vendor/sqlx-core/src/common/statement_cache.rs @@ -0,0 +1,75 @@ +use hashlink::lru_cache::LruCache; + +/// A cache for prepared statements. When full, the least recently used +/// statement gets removed. +#[derive(Debug)] +pub struct StatementCache { + inner: LruCache, +} + +impl StatementCache { + /// Create a new cache with the given capacity. + pub fn new(capacity: usize) -> Self { + Self { + inner: LruCache::new(capacity), + } + } + + /// Returns a mutable reference to the value corresponding to the given key + /// in the cache, if any. + pub fn get_mut(&mut self, k: &str) -> Option<&mut T> { + self.inner.get_mut(k) + } + + /// Inserts a new statement to the cache, returning the least recently used + /// statement id if the cache is full, or if inserting with an existing key, + /// the replaced existing statement. + pub fn insert(&mut self, k: &str, v: T) -> Option { + let mut lru_item = None; + + if self.capacity() == self.len() && !self.contains_key(k) { + lru_item = self.remove_lru(); + } else if self.contains_key(k) { + lru_item = self.inner.remove(k); + } + + self.inner.insert(k.into(), v); + + lru_item + } + + /// The number of statements in the cache. + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + /// Removes the least recently used item from the cache. + pub fn remove_lru(&mut self) -> Option { + self.inner.remove_lru().map(|(_, v)| v) + } + + /// Clear all cached statements from the cache. + pub fn clear(&mut self) { + self.inner.clear(); + } + + /// True if cache has a value for the given key. + pub fn contains_key(&mut self, k: &str) -> bool { + self.inner.contains_key(k) + } + + /// Returns the maximum number of statements the cache can hold. + pub fn capacity(&self) -> usize { + self.inner.capacity() + } + + /// Returns true if the cache capacity is more than 0. + #[allow(dead_code)] // Only used for some `cfg`s + pub fn is_enabled(&self) -> bool { + self.capacity() > 0 + } +} diff --git a/vendor/sqlx-core/src/config/common.rs b/vendor/sqlx-core/src/config/common.rs new file mode 100755 index 0000000..2d5342d --- /dev/null +++ b/vendor/sqlx-core/src/config/common.rs @@ -0,0 +1,49 @@ +/// Configuration shared by multiple components. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct Config { + /// Override the database URL environment variable. + /// + /// This is used by both the macros and `sqlx-cli`. + /// + /// Case-sensitive. Defaults to `DATABASE_URL`. + /// + /// Example: Multi-Database Project + /// ------- + /// You can use multiple databases in the same project by breaking it up into multiple crates, + /// then using a different environment variable for each. + /// + /// For example, with two crates in the workspace named `foo` and `bar`: + /// + /// #### `foo/sqlx.toml` + /// ```toml + /// [common] + /// database-url-var = "FOO_DATABASE_URL" + /// ``` + /// + /// #### `bar/sqlx.toml` + /// ```toml + /// [common] + /// database-url-var = "BAR_DATABASE_URL" + /// ``` + /// + /// #### `.env` + /// ```text + /// FOO_DATABASE_URL=postgres://postgres@localhost:5432/foo + /// BAR_DATABASE_URL=postgres://postgres@localhost:5432/bar + /// ``` + /// + /// The query macros used in `foo` will use `FOO_DATABASE_URL`, + /// and the ones used in `bar` will use `BAR_DATABASE_URL`. + pub database_url_var: Option, +} + +impl Config { + pub fn database_url_var(&self) -> &str { + self.database_url_var.as_deref().unwrap_or("DATABASE_URL") + } +} diff --git a/vendor/sqlx-core/src/config/drivers.rs b/vendor/sqlx-core/src/config/drivers.rs new file mode 100755 index 0000000..c341654 --- /dev/null +++ b/vendor/sqlx-core/src/config/drivers.rs @@ -0,0 +1,152 @@ +use std::error::Error; + +/// Configuration for specific database drivers (**applies to macros and `sqlx-cli` only**). +/// +/// # Note: Does Not Apply at Application Run-Time +/// As of writing, these configuration parameters do *not* have any bearing on +/// the runtime configuration of SQLx database drivers. +/// +/// Any parameters which overlap with runtime configuration +/// (e.g. [`drivers.sqlite.unsafe-load-extensions`][SqliteConfig::unsafe_load_extensions]) +/// _must_ be configured their normal ways at runtime (e.g. `SqliteConnectOptions::extension()`). +/// +/// See the documentation of individual fields for details. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct Config { + /// Configuration for the MySQL database driver. + /// + /// See [`MySqlConfig`] for details. + pub mysql: MySqlConfig, + + /// Configuration for the Postgres database driver. + /// + /// See [`PgConfig`] for details. + pub postgres: PgConfig, + + /// Configuration for the SQLite database driver. + /// + /// See [`SqliteConfig`] for details. + pub sqlite: SqliteConfig, + + /// Configuration for external database drivers. + /// + /// See [`ExternalDriverConfig`] for details. + pub external: ExternalDriverConfig, +} + +/// Configuration for the MySQL database driver. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct MySqlConfig { + // No fields implemented yet. This key is only used to validate parsing. +} + +/// Configuration for the Postgres database driver. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct PgConfig { + // No fields implemented yet. This key is only used to validate parsing. +} + +/// Configuration for the SQLite database driver. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct SqliteConfig { + /// Specify extensions to load, either by name or by path. + /// + /// Paths should be relative to the workspace root. + /// + /// See [Loading an Extension](https://www.sqlite.org/loadext.html#loading_an_extension) + /// in the SQLite manual for details. + /// + /// The `sqlite-load-extension` feature must be enabled and SQLite must be built + /// _without_ [`SQLITE_OMIT_LOAD_EXTENSION`] enabled. + /// + /// [`SQLITE_OMIT_LOAD_EXTENSION`]: https://www.sqlite.org/compile.html#omit_load_extension + /// + /// # Note: Does Not Configure Runtime Extension Loading + /// Extensions to be loaded at runtime *must* be separately configured with + /// `SqliteConnectOptions::extension()` or `SqliteConnectOptions::extension_with_entrypoint()`. + /// + /// # Safety + /// This causes arbitrary DLLs on the filesystem to be loaded at execution time, + /// which can easily result in undefined behavior, memory corruption, + /// or exploitable vulnerabilities if misused. + /// + /// It is not possible to provide a truly safe version of this API. + /// + /// Use this field with care, and only load extensions that you trust. + /// + /// # Example + /// Load the `uuid` and `vsv` extensions from [`sqlean`](https://github.com/nalgeon/sqlean). + /// + /// `sqlx.toml`: + /// ```toml + /// [common.drivers.sqlite] + /// unsafe-load-extensions = ["uuid", "vsv"] + /// ``` + pub unsafe_load_extensions: Vec, +} + +/// Extension for the SQLite database driver. +#[derive(Debug, PartialEq)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(untagged, deny_unknown_fields) +)] +pub enum SqliteExtension { + Path(String), + PathWithEntrypoint { path: String, entrypoint: String }, +} + +/// Configuration for external database drivers. +#[derive(Debug, Default)] +#[cfg_attr(feature = "sqlx-toml", derive(serde::Deserialize), serde(transparent))] +pub struct ExternalDriverConfig { + #[cfg(feature = "sqlx-toml")] + by_name: std::collections::BTreeMap, +} + +/// Type-erased [`toml::de::Error`]. +pub type TryParseError = Box; + +impl ExternalDriverConfig { + /// Try to parse the config for a given driver name, returning `Ok(None)` if it does not exist. + #[cfg(feature = "sqlx-toml")] + pub fn try_parse( + &self, + name: &str, + ) -> Result, TryParseError> { + let Some(config) = self.by_name.get(name) else { + return Ok(None); + }; + + // What's really baffling is that `toml` doesn't provide any way to deserialize + // from a `&Table` or `&Value`, only owned variants, so cloning is unavoidable here. + Ok(Some(config.clone().try_into()?)) + } + + /// Try to parse the config for a given driver name, returning `Ok(None)` if it does not exist. + #[cfg(not(feature = "sqlx-toml"))] + pub fn try_parse(&self, _name: &str) -> Result, TryParseError> { + Ok(None) + } +} diff --git a/vendor/sqlx-core/src/config/macros.rs b/vendor/sqlx-core/src/config/macros.rs new file mode 100755 index 0000000..6d08aa3 --- /dev/null +++ b/vendor/sqlx-core/src/config/macros.rs @@ -0,0 +1,418 @@ +use std::collections::BTreeMap; + +/// Configuration for the `query!()` family of macros. +/// +/// See also [`common::Config`][crate::config::common::Config] for renaming `DATABASE_URL`. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct Config { + /// Specify which crates' types to use when types from multiple crates apply. + /// + /// See [`PreferredCrates`] for details. + pub preferred_crates: PreferredCrates, + + /// Specify global overrides for mapping SQL type names to Rust type names. + /// + /// Default type mappings are defined by the database driver. + /// Refer to the `sqlx::types` module for details. + /// + /// ## Note: Case-Sensitive + /// Currently, the case of the type name MUST match the name SQLx knows it by. + /// Built-in types are spelled in all-uppercase to match SQL convention. + /// + /// However, user-created types in Postgres are all-lowercase unless quoted. + /// + /// ## Note: Orthogonal to Nullability + /// These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>` + /// or not. They only override the inner type used. + /// + /// ## Note: Schema Qualification (Postgres) + /// Type names may be schema-qualified in Postgres. If so, the schema should be part + /// of the type string, e.g. `'foo.bar'` to reference type `bar` in schema `foo`. + /// + /// The schema and/or type name may additionally be quoted in the string + /// for a quoted identifier (see next section). + /// + /// Schema qualification should not be used for types in the search path. + /// + /// ## Note: Quoted Identifiers (Postgres) + /// Type names using [quoted identifiers in Postgres] must also be specified with quotes here. + /// + /// Note, however, that the TOML format parses way the outer pair of quotes, + /// so for quoted names in Postgres, double-quoting is necessary, + /// e.g. `'"Foo"'` for SQL type `"Foo"`. + /// + /// To reference a schema-qualified type with a quoted name, use double-quotes after the + /// dot, e.g. `'foo."Bar"'` to reference type `"Bar"` of schema `foo`, and vice versa for + /// quoted schema names. + /// + /// We recommend wrapping all type names in single quotes, as shown below, + /// to avoid confusion. + /// + /// MySQL/MariaDB and SQLite do not support custom types, so quoting type names should + /// never be necessary. + /// + /// [quoted identifiers in Postgres]: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS + // Note: we wanted to be able to handle this intelligently, + // but the `toml` crate authors weren't interested: https://github.com/toml-rs/toml/issues/761 + // + // We decided to just encourage always quoting type names instead. + /// Example: Custom Wrapper Types + /// ------- + /// Does SQLx not support a type that you need? Do you want additional semantics not + /// implemented on the built-in types? You can create a custom wrapper, + /// or use an external crate. + /// + /// #### `sqlx.toml` + /// ```toml + /// [macros.type-overrides] + /// # Override a built-in type + /// 'UUID' = "crate::types::MyUuid" + /// + /// # Support an external or custom wrapper type (e.g. from the `isn` Postgres extension) + /// # (NOTE: FOR DOCUMENTATION PURPOSES ONLY; THIS CRATE/TYPE DOES NOT EXIST AS OF WRITING) + /// 'isbn13' = "isn_rs::sqlx::ISBN13" + /// ``` + /// + /// Example: Custom Types in Postgres + /// ------- + /// If you have a custom type in Postgres that you want to map without needing to use + /// the type override syntax in `sqlx::query!()` every time, you can specify a global + /// override here. + /// + /// For example, a custom enum type `foo`: + /// + /// #### Migration or Setup SQL (e.g. `migrations/0_setup.sql`) + /// ```sql + /// CREATE TYPE foo AS ENUM ('Bar', 'Baz'); + /// ``` + /// + /// #### `src/types.rs` + /// ```rust,no_run + /// #[derive(sqlx::Type)] + /// pub enum Foo { + /// Bar, + /// Baz + /// } + /// ``` + /// + /// If you're not using `PascalCase` in your enum variants then you'll want to use + /// `#[sqlx(rename_all = "")]` on your enum. + /// See [`Type`][crate::type::Type] for details. + /// + /// #### `sqlx.toml` + /// ```toml + /// [macros.type-overrides] + /// # Map SQL type `foo` to `crate::types::Foo` + /// 'foo' = "crate::types::Foo" + /// ``` + /// + /// Example: Schema-Qualified Types + /// ------- + /// (See `Note` section above for details.) + /// + /// ```toml + /// [macros.type-overrides] + /// # Map SQL type `foo.foo` to `crate::types::Foo` + /// 'foo.foo' = "crate::types::Foo" + /// ``` + /// + /// Example: Quoted Identifiers + /// ------- + /// If a type or schema uses quoted identifiers, + /// it must be wrapped in quotes _twice_ for SQLx to know the difference: + /// + /// ```toml + /// [macros.type-overrides] + /// # `"Foo"` in SQLx + /// '"Foo"' = "crate::types::Foo" + /// # **NOT** `"Foo"` in SQLx (parses as just `Foo`) + /// "Foo" = "crate::types::Foo" + /// + /// # Schema-qualified + /// '"foo".foo' = "crate::types::Foo" + /// 'foo."Foo"' = "crate::types::Foo" + /// '"foo"."Foo"' = "crate::types::Foo" + /// ``` + /// + /// (See `Note` section above for details.) + // TODO: allow specifying different types for input vs output + // e.g. to accept `&[T]` on input but output `Vec` + pub type_overrides: BTreeMap, + + /// Specify per-table and per-column overrides for mapping SQL types to Rust types. + /// + /// Default type mappings are defined by the database driver. + /// Refer to the `sqlx::types` module for details. + /// + /// The supported syntax is similar to [`type_overrides`][Self::type_overrides], + /// (with the same caveat for quoted names!) but column names must be qualified + /// by a separately quoted table name, which may optionally be schema-qualified. + /// + /// Multiple columns for the same SQL table may be written in the same table in TOML + /// (see examples below). + /// + /// ## Note: Orthogonal to Nullability + /// These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>` + /// or not. They only override the inner type used. + /// + /// ## Note: Schema Qualification + /// Table names may be schema-qualified. If so, the schema should be part + /// of the table name string, e.g. `'foo.bar'` to reference table `bar` in schema `foo`. + /// + /// The schema and/or type name may additionally be quoted in the string + /// for a quoted identifier (see next section). + /// + /// Postgres users: schema qualification should not be used for tables in the search path. + /// + /// ## Note: Quoted Identifiers + /// Schema, table, or column names using quoted identifiers ([MySQL], [Postgres], [SQLite]) + /// in SQL must also be specified with quotes here. + /// + /// Postgres and SQLite use double-quotes (`"Foo"`) while MySQL uses backticks (`\`Foo\`). + /// + /// Note, however, that the TOML format parses way the outer pair of quotes, + /// so for quoted names in Postgres, double-quoting is necessary, + /// e.g. `'"Foo"'` for SQL name `"Foo"`. + /// + /// To reference a schema-qualified table with a quoted name, use the appropriate quotation + /// characters after the dot, e.g. `'foo."Bar"'` to reference table `"Bar"` of schema `foo`, + /// and vice versa for quoted schema names. + /// + /// We recommend wrapping all table and column names in single quotes, as shown below, + /// to avoid confusion. + /// + /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/identifiers.html + /// [Postgres]: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS + /// [SQLite]: https://sqlite.org/lang_keywords.html + // Note: we wanted to be able to handle this intelligently, + // but the `toml` crate authors weren't interested: https://github.com/toml-rs/toml/issues/761 + // + // We decided to just encourage always quoting type names instead. + /// + /// Example + /// ------- + /// + /// #### `sqlx.toml` + /// ```toml + /// [macros.table-overrides.'foo'] + /// # Map column `bar` of table `foo` to Rust type `crate::types::Foo`: + /// 'bar' = "crate::types::Bar" + /// + /// # Quoted column name + /// # Note: same quoting requirements as `macros.type_overrides` + /// '"Bar"' = "crate::types::Bar" + /// + /// # Note: will NOT work (parses as `Bar`) + /// # "Bar" = "crate::types::Bar" + /// + /// # Table name may be quoted (note the wrapping single-quotes) + /// [macros.table-overrides.'"Foo"'] + /// 'bar' = "crate::types::Bar" + /// '"Bar"' = "crate::types::Bar" + /// + /// # Table name may also be schema-qualified. + /// # Note how the dot is inside the quotes. + /// [macros.table-overrides.'my_schema.my_table'] + /// 'my_column' = "crate::types::MyType" + /// + /// # Quoted schema, table, and column names + /// [macros.table-overrides.'"My Schema"."My Table"'] + /// '"My Column"' = "crate::types::MyType" + /// ``` + pub table_overrides: BTreeMap>, +} + +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case") +)] +pub struct PreferredCrates { + /// Specify the crate to use for mapping date/time types to Rust. + /// + /// The default behavior is to use whatever crate is enabled, + /// [`chrono`] or [`time`] (the latter takes precedent). + /// + /// [`chrono`]: crate::types::chrono + /// [`time`]: crate::types::time + /// + /// Example: Always Use Chrono + /// ------- + /// Thanks to Cargo's [feature unification], a crate in the dependency graph may enable + /// the `time` feature of SQLx which will force it on for all crates using SQLx, + /// which will result in problems if your crate wants to use types from [`chrono`]. + /// + /// You can use the type override syntax (see `sqlx::query!` for details), + /// or you can force an override globally by setting this option. + /// + /// #### `sqlx.toml` + /// ```toml + /// [macros.preferred-crates] + /// date-time = "chrono" + /// ``` + /// + /// [feature unification]: https://doc.rust-lang.org/cargo/reference/features.html#feature-unification + pub date_time: DateTimeCrate, + + /// Specify the crate to use for mapping `NUMERIC` types to Rust. + /// + /// The default behavior is to use whatever crate is enabled, + /// [`bigdecimal`] or [`rust_decimal`] (the latter takes precedent). + /// + /// [`bigdecimal`]: crate::types::bigdecimal + /// [`rust_decimal`]: crate::types::rust_decimal + /// + /// Example: Always Use `bigdecimal` + /// ------- + /// Thanks to Cargo's [feature unification], a crate in the dependency graph may enable + /// the `rust_decimal` feature of SQLx which will force it on for all crates using SQLx, + /// which will result in problems if your crate wants to use types from [`bigdecimal`]. + /// + /// You can use the type override syntax (see `sqlx::query!` for details), + /// or you can force an override globally by setting this option. + /// + /// #### `sqlx.toml` + /// ```toml + /// [macros.preferred-crates] + /// numeric = "bigdecimal" + /// ``` + /// + /// [feature unification]: https://doc.rust-lang.org/cargo/reference/features.html#feature-unification + pub numeric: NumericCrate, +} + +/// The preferred crate to use for mapping date/time types to Rust. +#[derive(Debug, Default, PartialEq, Eq)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(rename_all = "snake_case") +)] +pub enum DateTimeCrate { + /// Use whichever crate is enabled (`time` then `chrono`). + #[default] + Inferred, + + /// Always use types from [`chrono`][crate::types::chrono]. + /// + /// ```toml + /// [macros.preferred-crates] + /// date-time = "chrono" + /// ``` + Chrono, + + /// Always use types from [`time`][crate::types::time]. + /// + /// ```toml + /// [macros.preferred-crates] + /// date-time = "time" + /// ``` + Time, +} + +/// The preferred crate to use for mapping `NUMERIC` types to Rust. +#[derive(Debug, Default, PartialEq, Eq)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(rename_all = "snake_case") +)] +pub enum NumericCrate { + /// Use whichever crate is enabled (`rust_decimal` then `bigdecimal`). + #[default] + Inferred, + + /// Always use types from [`bigdecimal`][crate::types::bigdecimal]. + /// + /// ```toml + /// [macros.preferred-crates] + /// numeric = "bigdecimal" + /// ``` + #[cfg_attr(feature = "sqlx-toml", serde(rename = "bigdecimal"))] + BigDecimal, + + /// Always use types from [`rust_decimal`][crate::types::rust_decimal]. + /// + /// ```toml + /// [macros.preferred-crates] + /// numeric = "rust_decimal" + /// ``` + RustDecimal, +} + +/// A SQL type name; may optionally be schema-qualified. +/// +/// See [`macros.type-overrides`][Config::type_overrides] for usages. +pub type SqlType = Box; + +/// A SQL table name; may optionally be schema-qualified. +/// +/// See [`macros.table-overrides`][Config::table_overrides] for usages. +pub type TableName = Box; + +/// A column in a SQL table. +/// +/// See [`macros.table-overrides`][Config::table_overrides] for usages. +pub type ColumnName = Box; + +/// A Rust type name or path. +/// +/// Should be a global path (not relative). +pub type RustType = Box; + +/// Internal getter methods. +impl Config { + /// Get the override for a given type name (optionally schema-qualified). + pub fn type_override(&self, type_name: &str) -> Option<&str> { + // TODO: make this case-insensitive + self.type_overrides.get(type_name).map(|s| &**s) + } + + /// Get the override for a given column and table name (optionally schema-qualified). + pub fn column_override(&self, table: &str, column: &str) -> Option<&str> { + self.table_overrides + .get(table) + .and_then(|by_column| by_column.get(column)) + .map(|s| &**s) + } +} + +impl DateTimeCrate { + /// Returns `self == Self::Inferred` + #[inline(always)] + pub fn is_inferred(&self) -> bool { + *self == Self::Inferred + } + + #[inline(always)] + pub fn crate_name(&self) -> Option<&str> { + match self { + Self::Inferred => None, + Self::Chrono => Some("chrono"), + Self::Time => Some("time"), + } + } +} + +impl NumericCrate { + /// Returns `self == Self::Inferred` + #[inline(always)] + pub fn is_inferred(&self) -> bool { + *self == Self::Inferred + } + + #[inline(always)] + pub fn crate_name(&self) -> Option<&str> { + match self { + Self::Inferred => None, + Self::BigDecimal => Some("bigdecimal"), + Self::RustDecimal => Some("rust_decimal"), + } + } +} diff --git a/vendor/sqlx-core/src/config/migrate.rs b/vendor/sqlx-core/src/config/migrate.rs new file mode 100755 index 0000000..0dd6cc2 --- /dev/null +++ b/vendor/sqlx-core/src/config/migrate.rs @@ -0,0 +1,212 @@ +use std::collections::BTreeSet; + +/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`. +/// +/// ### Note +/// A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these +/// configuration options. We recommend using `sqlx::migrate!()` instead. +/// +/// ### Warning: Potential Data Loss or Corruption! +/// Many of these options, if changed after migrations are set up, +/// can result in data loss or corruption of a production database +/// if the proper precautions are not taken. +/// +/// Be sure you know what you are doing and that you read all relevant documentation _thoroughly_. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct Config { + /// Specify the names of schemas to create if they don't already exist. + /// + /// This is done before checking the existence of the migrations table + /// (`_sqlx_migrations` or overridden `table_name` below) so that it may be placed in + /// one of these schemas. + /// + /// ### Example + /// `sqlx.toml`: + /// ```toml + /// [migrate] + /// create-schemas = ["foo"] + /// ``` + pub create_schemas: BTreeSet>, + + /// Override the name of the table used to track executed migrations. + /// + /// May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`. + /// + /// Potentially useful for multi-tenant databases. + /// + /// ### Warning: Potential Data Loss or Corruption! + /// Changing this option for a production database will likely result in data loss or corruption + /// as the migration machinery will no longer be aware of what migrations have been applied + /// and will attempt to re-run them. + /// + /// You should create the new table as a copy of the existing migrations table (with contents!), + /// and be sure all instances of your application have been migrated to the new + /// table before deleting the old one. + /// + /// ### Example + /// `sqlx.toml`: + /// ```toml + /// [migrate] + /// # Put `_sqlx_migrations` in schema `foo` + /// table-name = "foo._sqlx_migrations" + /// ``` + pub table_name: Option>, + + /// Override the directory used for migrations files. + /// + /// Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`. + pub migrations_dir: Option>, + + /// Specify characters that should be ignored when hashing migrations. + /// + /// Any characters contained in the given array will be dropped when a migration is hashed. + /// + /// ### Warning: May Change Hashes for Existing Migrations + /// Changing the characters considered in hashing migrations will likely + /// change the output of the hash. + /// + /// This may require manual rectification for deployed databases. + /// + /// ### Example: Ignore Carriage Return (`` | `\r`) + /// Line ending differences between platforms can result in migrations having non-repeatable + /// hashes. The most common culprit is the carriage return (`` | `\r`), which Windows + /// uses in its line endings alongside line feed (`` | `\n`), often written `CRLF` or `\r\n`, + /// whereas Linux and macOS use only line feeds. + /// + /// `sqlx.toml`: + /// ```toml + /// [migrate] + /// ignored-chars = ["\r"] + /// ``` + /// + /// For projects using Git, this can also be addressed using [`.gitattributes`]: + /// + /// ```text + /// # Force newlines in migrations to be line feeds on all platforms + /// migrations/*.sql text eol=lf + /// ``` + /// + /// This may require resetting or re-checking out the migrations files to take effect. + /// + /// [`.gitattributes`]: https://git-scm.com/docs/gitattributes + /// + /// ### Example: Ignore all Whitespace Characters + /// To make your migrations amenable to reformatting, you may wish to tell SQLx to ignore + /// _all_ whitespace characters in migrations. + /// + /// ##### Warning: Beware Syntactically Significant Whitespace! + /// If your migrations use string literals or quoted identifiers which contain whitespace, + /// this configuration will cause the migration machinery to ignore some changes to these. + /// This may result in a mismatch between the development and production versions of + /// your database. + /// + /// `sqlx.toml`: + /// ```toml + /// [migrate] + /// # Ignore common whitespace characters when hashing + /// ignored-chars = [" ", "\t", "\r", "\n"] # Space, tab, CR, LF + /// ``` + // Likely lower overhead for small sets than `HashSet`. + pub ignored_chars: BTreeSet, + + /// Specify default options for new migrations created with `sqlx migrate add`. + pub defaults: MigrationDefaults, +} + +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case") +)] +pub struct MigrationDefaults { + /// Specify the default type of migration that `sqlx migrate add` should create by default. + /// + /// ### Example: Use Reversible Migrations by Default + /// `sqlx.toml`: + /// ```toml + /// [migrate.defaults] + /// migration-type = "reversible" + /// ``` + pub migration_type: DefaultMigrationType, + + /// Specify the default scheme that `sqlx migrate add` should use for version integers. + /// + /// ### Example: Use Sequential Versioning by Default + /// `sqlx.toml`: + /// ```toml + /// [migrate.defaults] + /// migration-versioning = "sequential" + /// ``` + pub migration_versioning: DefaultVersioning, +} + +/// The default type of migration that `sqlx migrate add` should create by default. +#[derive(Debug, Default, PartialEq, Eq)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(rename_all = "snake_case") +)] +pub enum DefaultMigrationType { + /// Create the same migration type as that of the latest existing migration, + /// or `Simple` otherwise. + #[default] + Inferred, + + /// Create non-reversible migrations (`_.sql`) by default. + Simple, + + /// Create reversible migrations (`_.up.sql` and `[...].down.sql`) by default. + Reversible, +} + +/// The default scheme that `sqlx migrate add` should use for version integers. +#[derive(Debug, Default, PartialEq, Eq)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(rename_all = "snake_case") +)] +pub enum DefaultVersioning { + /// Infer the versioning scheme from existing migrations: + /// + /// * If the versions of the last two migrations differ by `1`, infer `Sequential`. + /// * If only one migration exists and has version `1`, infer `Sequential`. + /// * Otherwise, infer `Timestamp`. + #[default] + Inferred, + + /// Use UTC timestamps for migration versions. + /// + /// This is the recommended versioning format as it's less likely to collide when multiple + /// developers are creating migrations on different branches. + /// + /// The exact timestamp format is unspecified. + Timestamp, + + /// Use sequential integers for migration versions. + Sequential, +} + +#[cfg(feature = "migrate")] +impl Config { + pub fn migrations_dir(&self) -> &str { + self.migrations_dir.as_deref().unwrap_or("migrations") + } + + pub fn table_name(&self) -> &str { + self.table_name.as_deref().unwrap_or("_sqlx_migrations") + } + + pub fn to_resolve_config(&self) -> crate::migrate::ResolveConfig { + let mut config = crate::migrate::ResolveConfig::new(); + config.ignore_chars(self.ignored_chars.iter().copied()); + config + } +} diff --git a/vendor/sqlx-core/src/config/mod.rs b/vendor/sqlx-core/src/config/mod.rs new file mode 100755 index 0000000..960d0f4 --- /dev/null +++ b/vendor/sqlx-core/src/config/mod.rs @@ -0,0 +1,223 @@ +//! (Exported for documentation only) Guide and reference for `sqlx.toml` files. +//! +//! To use, create a `sqlx.toml` file in your crate root (the same directory as your `Cargo.toml`). +//! The configuration in a `sqlx.toml` configures SQLx *only* for the current crate. +//! +//! Requires the `sqlx-toml` feature (not enabled by default). +//! +//! `sqlx-cli` will also read `sqlx.toml` when running migrations. +//! +//! See the [`Config`] type and its fields for individual configuration options. +//! +//! See the [reference][`_reference`] for the full `sqlx.toml` file. + +use std::error::Error; +use std::fmt::Debug; +use std::io; +use std::path::{Path, PathBuf}; + +/// Configuration shared by multiple components. +/// +/// See [`common::Config`] for details. +pub mod common; + +pub mod drivers; + +/// Configuration for the `query!()` family of macros. +/// +/// See [`macros::Config`] for details. +pub mod macros; + +/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`. +/// +/// See [`migrate::Config`] for details. +pub mod migrate; + +/// Reference for `sqlx.toml` files +/// +/// Source: `sqlx-core/src/config/reference.toml` +/// +/// ```toml +#[doc = include_str!("reference.toml")] +/// ``` +pub mod _reference {} + +#[cfg(all(test, feature = "sqlx-toml"))] +mod tests; + +/// The parsed structure of a `sqlx.toml` file. +#[derive(Debug, Default)] +#[cfg_attr( + feature = "sqlx-toml", + derive(serde::Deserialize), + serde(default, rename_all = "kebab-case", deny_unknown_fields) +)] +pub struct Config { + /// Configuration shared by multiple components. + /// + /// See [`common::Config`] for details. + pub common: common::Config, + + /// Configuration for database drivers. + /// + /// See [`drivers::Config`] for details. + pub drivers: drivers::Config, + + /// Configuration for the `query!()` family of macros. + /// + /// See [`macros::Config`] for details. + pub macros: macros::Config, + + /// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`. + /// + /// See [`migrate::Config`] for details. + pub migrate: migrate::Config, +} + +/// Error returned from various methods of [`Config`]. +#[derive(thiserror::Error, Debug)] +pub enum ConfigError { + /// The loading method expected `CARGO_MANIFEST_DIR` to be set and it wasn't. + /// + /// This is necessary to locate the root of the crate currently being compiled. + /// + /// See [the "Environment Variables" page of the Cargo Book][cargo-env] for details. + /// + /// [cargo-env]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates + #[error("environment variable `CARGO_MANIFEST_DIR` must be set and valid")] + Env( + #[from] + #[source] + std::env::VarError, + ), + + /// No configuration file was found. Not necessarily fatal. + #[error("config file {path:?} not found")] + NotFound { path: PathBuf }, + + /// An I/O error occurred while attempting to read the config file at `path`. + /// + /// If the error is [`io::ErrorKind::NotFound`], [`Self::NotFound`] is returned instead. + #[error("error reading config file {path:?}")] + Io { + path: PathBuf, + #[source] + error: io::Error, + }, + + /// An error in the TOML was encountered while parsing the config file at `path`. + /// + /// The error gives line numbers and context when printed with `Display`/`ToString`. + /// + /// Only returned if the `sqlx-toml` feature is enabled. + #[error("error parsing config file {path:?}")] + Parse { + path: PathBuf, + /// Type-erased [`toml::de::Error`]. + #[source] + error: Box, + }, + + /// A `sqlx.toml` file was found or specified, but the `sqlx-toml` feature is not enabled. + #[error("SQLx found config file at {path:?} but the `sqlx-toml` feature was not enabled")] + ParseDisabled { path: PathBuf }, +} + +impl ConfigError { + /// Create a [`ConfigError`] from a [`std::io::Error`]. + /// + /// Maps to either `NotFound` or `Io`. + pub fn from_io(path: impl Into, error: io::Error) -> Self { + if error.kind() == io::ErrorKind::NotFound { + Self::NotFound { path: path.into() } + } else { + Self::Io { + path: path.into(), + error, + } + } + } + + /// If this error means the file was not found, return the path that was attempted. + pub fn not_found_path(&self) -> Option<&Path> { + if let Self::NotFound { path } = self { + Some(path) + } else { + None + } + } +} + +/// Internal methods for loading a `Config`. +#[allow(clippy::result_large_err)] +impl Config { + /// Read `$CARGO_MANIFEST_DIR/sqlx.toml` or return `Config::default()` if it does not exist. + /// + /// # Errors + /// * If `CARGO_MANIFEST_DIR` is not set. + /// * If the file exists but could not be read or parsed. + /// * If the file exists but the `sqlx-toml` feature is disabled. + pub fn try_from_crate_or_default() -> Result { + Self::try_from_path_or_default(get_crate_path()?) + } + + /// Attempt to read `Config` from the path given, or return `Config::default()` if it does not exist. + /// + /// # Errors + /// * If the file exists but could not be read or parsed. + /// * If the file exists but the `sqlx-toml` feature is disabled. + pub fn try_from_path_or_default(path: PathBuf) -> Result { + Self::read_from(path).or_else(|e| { + if let ConfigError::NotFound { .. } = e { + Ok(Config::default()) + } else { + Err(e) + } + }) + } + + /// Attempt to read `Config` from the path given. + /// + /// # Errors + /// * If the file does not exist. + /// * If the file exists but could not be read or parsed. + /// * If the file exists but the `sqlx-toml` feature is disabled. + pub fn try_from_path(path: PathBuf) -> Result { + Self::read_from(path) + } + + #[cfg(feature = "sqlx-toml")] + fn read_from(path: PathBuf) -> Result { + // The `toml` crate doesn't provide an incremental reader. + let toml_s = match std::fs::read_to_string(&path) { + Ok(toml) => toml, + Err(error) => { + return Err(ConfigError::from_io(path, error)); + } + }; + + // TODO: parse and lint TOML structure before deserializing + // Motivation: https://github.com/toml-rs/toml/issues/761 + tracing::debug!("read config TOML from {path:?}:\n{toml_s}"); + + toml::from_str(&toml_s).map_err(|error| ConfigError::Parse { + path, + error: Box::new(error), + }) + } + + #[cfg(not(feature = "sqlx-toml"))] + fn read_from(path: PathBuf) -> Result { + match path.try_exists() { + Ok(true) => Err(ConfigError::ParseDisabled { path }), + Ok(false) => Err(ConfigError::NotFound { path }), + Err(e) => Err(ConfigError::from_io(path, e)), + } + } +} + +fn get_crate_path() -> Result { + let mut path = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?); + path.push("sqlx.toml"); + Ok(path) +} diff --git a/vendor/sqlx-core/src/config/reference.toml b/vendor/sqlx-core/src/config/reference.toml new file mode 100755 index 0000000..618ac23 --- /dev/null +++ b/vendor/sqlx-core/src/config/reference.toml @@ -0,0 +1,236 @@ +# `sqlx.toml` reference. +# +# Note: shown values are *not* defaults. +# They are explicitly set to non-default values to test parsing. +# Refer to the comment for a given option for its default value. + +############################################################################################### + +# Configuration shared by multiple components. +[common] +# Change the environment variable to get the database URL. +# +# This is used by both the macros and `sqlx-cli`. +# +# If not specified, defaults to `DATABASE_URL` +database-url-var = "FOO_DATABASE_URL" + +############################################################################################### + +# Configuration of SQLx database drivers (**applies to macros and sqlx-cli only**) +[drivers] + +# Configure MySQL databases in macros and sqlx-cli. +[drivers.mysql] +# No fields implemented yet. This key is only used to validate parsing. + +# Configure Postgres databases in macros and sqlx-cli. +[drivers.postgres] +# No fields implemented yet. This key is only used to validate parsing. + +# Configure Postgres databases in macros and sqlx-cli. +[drivers.sqlite] +# Load extensions into SQLite when running macros or migrations +# +# Defaults to an empty list, which has no effect. +# +# Must be specified separately at run-time using `SqliteConnectOptions::extension()` or `::extension_with_entrypoint()`. +# +# Safety +# This causes arbitrary DLLs on the filesystem to be loaded at runtime, +# which can easily result in undefined behavior, memory corruption, +# or exploitable vulnerabilities if misused. +# +# It is not possible to provide a truly safe version of this API. +# +# Use this field with care, and only load extensions that you trust. +unsafe-load-extensions = [ + "uuid", + { path = "vsv_renamed", entrypoint = "sqlite3_vsv_init" }, +] + +# Configure external drivers in macros and sqlx-cli. +# +# These keys are only validated when the external driver tries to parse them, +# unlike config for built-in drivers which is validated directly. +[drivers.external.""] +foo = 'foo' +bar = true + +############################################################################################### + +# Configuration for the `query!()` family of macros. +[macros] + +[macros.preferred-crates] +# Force the macros to use the `chrono` crate for date/time types, even if `time` is enabled. +# +# Defaults to "inferred": use whichever crate is enabled (`time` takes precedence over `chrono`). +date-time = "chrono" + +# Or, ensure the macros always prefer `time` +# in case new date/time crates are added in the future: +# date-time = "time" + +# Force the macros to use the `rust_decimal` crate for `NUMERIC`, even if `bigdecimal` is enabled. +# +# Defaults to "inferred": use whichever crate is enabled (`bigdecimal` takes precedence over `rust_decimal`). +numeric = "rust_decimal" + +# Or, ensure the macros always prefer `bigdecimal` +# in case new decimal crates are added in the future: +# numeric = "bigdecimal" + +# Set global overrides for mapping SQL types to Rust types. +# +# Default type mappings are defined by the database driver. +# Refer to the `sqlx::types` module for details. +# +# Postgres users: schema qualification should not be used for types in the search path. +# +# ### Note: Orthogonal to Nullability +# These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>` +# or not. They only override the inner type used. +[macros.type-overrides] +# Override a built-in type (map all `UUID` columns to `crate::types::MyUuid`) +# Note: currently, the case of the type name MUST match. +# Built-in types are spelled in all-uppercase to match SQL convention. +'UUID' = "crate::types::MyUuid" + +# Support an external or custom wrapper type (e.g. from the `isn` Postgres extension) +# (NOTE: FOR DOCUMENTATION PURPOSES ONLY; THIS CRATE/TYPE DOES NOT EXIST AS OF WRITING) +'isbn13' = "isn_rs::isbn::ISBN13" + +# SQL type `foo` to Rust type `crate::types::Foo`: +'foo' = "crate::types::Foo" + +# SQL type `"Bar"` to Rust type `crate::types::Bar`; notice the extra pair of quotes: +'"Bar"' = "crate::types::Bar" + +# Will NOT work (the first pair of quotes are parsed by TOML) +# "Bar" = "crate::types::Bar" + +# Schema qualified +'foo.bar' = "crate::types::Bar" + +# Schema qualified and quoted +'foo."Bar"' = "crate::schema::foo::Bar" + +# Quoted schema name +'"Foo".bar' = "crate::schema::foo::Bar" + +# Quoted schema and type name +'"Foo"."Bar"' = "crate::schema::foo::Bar" + +# Set per-table and per-column overrides for mapping SQL types to Rust types. +# +# Note: table name is required in the header. +# +# Postgres users: schema qualification should not be used for types in the search path. +# +# ### Note: Orthogonal to Nullability +# These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>` +# or not. They only override the inner type used. +[macros.table-overrides.'foo'] +# Map column `bar` of table `foo` to Rust type `crate::types::Foo`: +'bar' = "crate::types::Bar" + +# Quoted column name +# Note: same quoting requirements as `macros.type_overrides` +'"Bar"' = "crate::types::Bar" + +# Note: will NOT work (parses as `Bar`) +# "Bar" = "crate::types::Bar" + +# Table name may be quoted (note the wrapping single-quotes) +[macros.table-overrides.'"Foo"'] +'bar' = "crate::types::Bar" +'"Bar"' = "crate::types::Bar" + +# Table name may also be schema-qualified. +# Note how the dot is inside the quotes. +[macros.table-overrides.'my_schema.my_table'] +'my_column' = "crate::types::MyType" + +# Quoted schema, table, and column names +[macros.table-overrides.'"My Schema"."My Table"'] +'"My Column"' = "crate::types::MyType" + +############################################################################################### + +# Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`. +# +# ### Note +# A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these +# configuration options. We recommend using `sqlx::migrate!()` instead. +# +# ### Warning: Potential Data Loss or Corruption! +# Many of these options, if changed after migrations are set up, +# can result in data loss or corruption of a production database +# if the proper precautions are not taken. +# +# Be sure you know what you are doing and that you read all relevant documentation _thoroughly_. +[migrate] +# Override the name of the table used to track executed migrations. +# +# May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`. +# +# Potentially useful for multi-tenant databases. +# +# ### Warning: Potential Data Loss or Corruption! +# Changing this option for a production database will likely result in data loss or corruption +# as the migration machinery will no longer be aware of what migrations have been applied +# and will attempt to re-run them. +# +# You should create the new table as a copy of the existing migrations table (with contents!), +# and be sure all instances of your application have been migrated to the new +# table before deleting the old one. +table-name = "foo._sqlx_migrations" + +# Override the directory used for migrations files. +# +# Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`. +migrations-dir = "foo/migrations" + +# Specify characters that should be ignored when hashing migrations. +# +# Any characters contained in the given set will be dropped when a migration is hashed. +# +# Defaults to an empty array (don't drop any characters). +# +# ### Warning: May Change Hashes for Existing Migrations +# Changing the characters considered in hashing migrations will likely +# change the output of the hash. +# +# This may require manual rectification for deployed databases. +# ignored-chars = [] + +# Ignore Carriage Returns (`` | `\r`) +# Note that the TOML format requires double-quoted strings to process escapes. +# ignored-chars = ["\r"] + +# Ignore common whitespace characters (beware syntactically significant whitespace!) +# Space, tab, CR, LF, zero-width non-breaking space (U+FEFF) +# +# U+FEFF is added by some editors as a magic number at the beginning of a text file indicating it is UTF-8 encoded, +# where it is known as a byte-order mark (BOM): https://en.wikipedia.org/wiki/Byte_order_mark +ignored-chars = [" ", "\t", "\r", "\n", "\uFEFF"] + +# Set default options for new migrations. +[migrate.defaults] +# Specify reversible migrations by default (for `sqlx migrate create`). +# +# Defaults to "inferred": uses the type of the last migration, or "simple" otherwise. +migration-type = "reversible" + +# Specify simple (non-reversible) migrations by default. +# migration-type = "simple" + +# Specify sequential versioning by default (for `sqlx migrate create`). +# +# Defaults to "inferred": guesses the versioning scheme from the latest migrations, +# or "timestamp" otherwise. +migration-versioning = "sequential" + +# Specify timestamp versioning by default. +# migration-versioning = "timestamp" diff --git a/vendor/sqlx-core/src/config/tests.rs b/vendor/sqlx-core/src/config/tests.rs new file mode 100755 index 0000000..d01b859 --- /dev/null +++ b/vendor/sqlx-core/src/config/tests.rs @@ -0,0 +1,122 @@ +use crate::config::{self, Config}; +use std::collections::BTreeSet; + +#[test] +fn reference_parses_as_config() { + let config: Config = toml::from_str(include_str!("reference.toml")) + // The `Display` impl of `toml::Error` is *actually* more useful than `Debug` + .unwrap_or_else(|e| panic!("expected reference.toml to parse as Config: {e}")); + + assert_common_config(&config.common); + assert_drivers_config(&config.drivers); + assert_macros_config(&config.macros); + assert_migrate_config(&config.migrate); +} + +fn assert_common_config(config: &config::common::Config) { + assert_eq!(config.database_url_var.as_deref(), Some("FOO_DATABASE_URL")); +} + +fn assert_drivers_config(config: &config::drivers::Config) { + assert_eq!( + config.sqlite.unsafe_load_extensions, + vec![ + config::drivers::SqliteExtension::Path("uuid".to_string()), + config::drivers::SqliteExtension::PathWithEntrypoint { + path: "vsv_renamed".to_string(), + entrypoint: "sqlite3_vsv_init".to_string() + } + ] + ); + + #[derive(Debug, Eq, PartialEq, serde::Deserialize)] + #[serde(rename_all = "kebab-case")] + struct TestExternalDriverConfig { + foo: String, + bar: bool, + } + + assert_eq!( + config.external.try_parse("").unwrap(), + Some(TestExternalDriverConfig { + foo: "foo".to_string(), + bar: true + }) + ); +} + +fn assert_macros_config(config: &config::macros::Config) { + use config::macros::*; + + assert_eq!(config.preferred_crates.date_time, DateTimeCrate::Chrono); + assert_eq!(config.preferred_crates.numeric, NumericCrate::RustDecimal); + + // Type overrides + // Don't need to cover everything, just some important canaries. + assert_eq!(config.type_override("UUID"), Some("crate::types::MyUuid")); + + assert_eq!(config.type_override("foo"), Some("crate::types::Foo")); + + assert_eq!(config.type_override(r#""Bar""#), Some("crate::types::Bar"),); + + assert_eq!( + config.type_override(r#""Foo".bar"#), + Some("crate::schema::foo::Bar"), + ); + + assert_eq!( + config.type_override(r#""Foo"."Bar""#), + Some("crate::schema::foo::Bar"), + ); + + // Column overrides + assert_eq!( + config.column_override("foo", "bar"), + Some("crate::types::Bar"), + ); + + assert_eq!( + config.column_override("foo", r#""Bar""#), + Some("crate::types::Bar"), + ); + + assert_eq!( + config.column_override(r#""Foo""#, "bar"), + Some("crate::types::Bar"), + ); + + assert_eq!( + config.column_override(r#""Foo""#, r#""Bar""#), + Some("crate::types::Bar"), + ); + + assert_eq!( + config.column_override("my_schema.my_table", "my_column"), + Some("crate::types::MyType"), + ); + + assert_eq!( + config.column_override(r#""My Schema"."My Table""#, r#""My Column""#), + Some("crate::types::MyType"), + ); +} + +fn assert_migrate_config(config: &config::migrate::Config) { + use config::migrate::*; + + assert_eq!(config.table_name.as_deref(), Some("foo._sqlx_migrations")); + assert_eq!(config.migrations_dir.as_deref(), Some("foo/migrations")); + + let ignored_chars = BTreeSet::from([' ', '\t', '\r', '\n', '\u{FEFF}']); + + assert_eq!(config.ignored_chars, ignored_chars); + + assert_eq!( + config.defaults.migration_type, + DefaultMigrationType::Reversible + ); + assert_eq!( + config.defaults.migration_versioning, + DefaultVersioning::Sequential + ); +} diff --git a/vendor/sqlx-core/src/connection.rs b/vendor/sqlx-core/src/connection.rs new file mode 100755 index 0000000..b5f8138 --- /dev/null +++ b/vendor/sqlx-core/src/connection.rs @@ -0,0 +1,281 @@ +use crate::database::{Database, HasStatementCache}; +use crate::error::Error; + +use crate::config; +use crate::sql_str::SqlSafeStr; +use crate::transaction::{Transaction, TransactionManager}; +use futures_core::future::BoxFuture; +use log::LevelFilter; +use std::fmt::Debug; +use std::future::Future; +use std::str::FromStr; +use std::time::Duration; +use url::Url; + +/// Represents a single database connection. +pub trait Connection: Send { + type Database: Database; + + type Options: ConnectOptions; + + /// Explicitly close this database connection. + /// + /// This notifies the database server that the connection is closing so that it can + /// free up any server-side resources in use. + /// + /// While connections can simply be dropped to clean up local resources, + /// the `Drop` handler itself cannot notify the server that the connection is being closed + /// because that may require I/O to send a termination message. That can result in a delay + /// before the server learns that the connection is gone, usually from a TCP keepalive timeout. + /// + /// Creating and dropping many connections in short order without calling `.close()` may + /// lead to errors from the database server because those senescent connections will still + /// count against any connection limit or quota that is configured. + /// + /// Therefore it is recommended to call `.close()` on a connection when you are done using it + /// and to `.await` the result to ensure the termination message is sent. + fn close(self) -> impl Future> + Send + 'static; + + /// Immediately close the connection without sending a graceful shutdown. + /// + /// This should still at least send a TCP `FIN` frame to let the server know we're dying. + #[doc(hidden)] + fn close_hard(self) -> impl Future> + Send + 'static; + + /// Checks if a connection to the database is still valid. + fn ping(&mut self) -> impl Future> + Send + '_; + + /// Begin a new transaction or establish a savepoint within the active transaction. + /// + /// Returns a [`Transaction`] for controlling and tracking the new transaction. + fn begin( + &mut self, + ) -> impl Future, Error>> + Send + '_; + + /// Begin a new transaction with a custom statement. + /// + /// Returns a [`Transaction`] for controlling and tracking the new transaction. + /// + /// Returns an error if the connection is already in a transaction or if + /// `statement` does not put the connection into a transaction. + fn begin_with( + &mut self, + statement: impl SqlSafeStr, + ) -> impl Future, Error>> + Send + '_ + where + Self: Sized, + { + Transaction::begin(self, Some(statement.into_sql_str())) + } + + /// Returns `true` if the connection is currently in a transaction. + /// + /// # Note: Automatic Rollbacks May Not Be Counted + /// Certain database errors (such as a serializable isolation failure) + /// can cause automatic rollbacks of a transaction + /// which may not be indicated in the return value of this method. + #[inline] + fn is_in_transaction(&self) -> bool { + ::TransactionManager::get_transaction_depth(self) != 0 + } + + /// Execute the function inside a transaction. + /// + /// If the function returns an error, the transaction will be rolled back. If it does not + /// return an error, the transaction will be committed. + /// + /// # Example + /// + /// ```rust + /// use sqlx::postgres::{PgConnection, PgRow}; + /// use sqlx::Connection; + /// + /// # pub async fn _f(conn: &mut PgConnection) -> sqlx::Result> { + /// conn.transaction(|txn| Box::pin(async move { + /// sqlx::query("select * from ..").fetch_all(&mut **txn).await + /// })).await + /// # } + /// ``` + fn transaction<'a, F, R, E>( + &'a mut self, + callback: F, + ) -> impl Future> + Send + 'a + where + for<'c> F: FnOnce(&'c mut Transaction<'_, Self::Database>) -> BoxFuture<'c, Result> + + 'a + + Send + + Sync, + Self: Sized, + R: Send, + E: From + Send, + { + async move { + let mut transaction = self.begin().await?; + let ret = callback(&mut transaction).await; + + match ret { + Ok(ret) => { + transaction.commit().await?; + + Ok(ret) + } + Err(err) => { + transaction.rollback().await?; + + Err(err) + } + } + } + } + + /// The number of statements currently cached in the connection. + fn cached_statements_size(&self) -> usize + where + Self::Database: HasStatementCache, + { + 0 + } + + /// Removes all statements from the cache, closing them on the server if + /// needed. + fn clear_cached_statements(&mut self) -> impl Future> + Send + '_ + where + Self::Database: HasStatementCache, + { + async move { Ok(()) } + } + + /// Restore any buffers in the connection to their default capacity, if possible. + /// + /// Sending a large query or receiving a resultset with many columns can cause the connection + /// to allocate additional buffer space to fit the data which is retained afterwards in + /// case it's needed again. This can give the outward appearance of a memory leak, but is + /// in fact the intended behavior. + /// + /// Calling this method tells the connection to release that excess memory if it can, + /// though be aware that calling this too often can cause unnecessary thrashing or + /// fragmentation in the global allocator. If there's still data in the connection buffers + /// (unlikely if the last query was run to completion) then it may need to be moved to + /// allow the buffers to shrink. + fn shrink_buffers(&mut self); + + #[doc(hidden)] + fn flush(&mut self) -> impl Future> + Send + '_; + + #[doc(hidden)] + fn should_flush(&self) -> bool; + + /// Establish a new database connection. + /// + /// A value of [`Options`][Self::Options] is parsed from the provided connection string. This parsing + /// is database-specific. + #[inline] + fn connect(url: &str) -> impl Future> + Send + 'static + where + Self: Sized, + { + let options = url.parse(); + + async move { Self::connect_with(&options?).await } + } + + /// Establish a new database connection with the provided options. + fn connect_with( + options: &Self::Options, + ) -> impl Future> + Send + '_ + where + Self: Sized, + { + options.connect() + } +} + +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct LogSettings { + pub statements_level: LevelFilter, + pub slow_statements_level: LevelFilter, + pub slow_statements_duration: Duration, +} + +impl Default for LogSettings { + fn default() -> Self { + LogSettings { + statements_level: LevelFilter::Debug, + slow_statements_level: LevelFilter::Warn, + slow_statements_duration: Duration::from_secs(1), + } + } +} + +impl LogSettings { + pub fn log_statements(&mut self, level: LevelFilter) { + self.statements_level = level; + } + pub fn log_slow_statements(&mut self, level: LevelFilter, duration: Duration) { + self.slow_statements_level = level; + self.slow_statements_duration = duration; + } +} + +pub trait ConnectOptions: 'static + Send + Sync + FromStr + Debug + Clone { + type Connection: Connection + ?Sized; + + /// Parse the `ConnectOptions` from a URL. + fn from_url(url: &Url) -> Result; + + /// Get a connection URL that may be used to connect to the same database as this `ConnectOptions`. + /// + /// ### Note: Lossy + /// Any flags or settings which do not have a representation in the URL format will be lost. + /// They will fall back to their default settings when the URL is parsed. + /// + /// The only settings guaranteed to be preserved are: + /// * Username + /// * Password + /// * Hostname + /// * Port + /// * Database name + /// * Unix socket or SQLite database file path + /// * SSL mode (if applicable) + /// * SSL CA certificate path + /// * SSL client certificate path + /// * SSL client key path + /// + /// Additional settings are driver-specific. Refer to the source of a given implementation + /// to see which options are preserved in the URL. + /// + /// ### Panics + /// This defaults to `unimplemented!()`. + /// + /// Individual drivers should override this to implement the intended behavior. + fn to_url_lossy(&self) -> Url { + unimplemented!() + } + + /// Establish a new database connection with the options specified by `self`. + fn connect(&self) -> impl Future> + Send + '_ + where + Self::Connection: Sized; + + /// Log executed statements with the specified `level` + fn log_statements(self, level: LevelFilter) -> Self; + + /// Log executed statements with a duration above the specified `duration` + /// at the specified `level`. + fn log_slow_statements(self, level: LevelFilter, duration: Duration) -> Self; + + /// Entirely disables statement logging (both slow and regular). + fn disable_statement_logging(self) -> Self { + self.log_statements(LevelFilter::Off) + .log_slow_statements(LevelFilter::Off, Duration::default()) + } + + #[doc(hidden)] + fn __unstable_apply_driver_config( + self, + _config: &config::drivers::Config, + ) -> crate::Result { + Ok(self) + } +} diff --git a/vendor/sqlx-core/src/database.rs b/vendor/sqlx-core/src/database.rs new file mode 100755 index 0000000..e7aaeb1 --- /dev/null +++ b/vendor/sqlx-core/src/database.rs @@ -0,0 +1,114 @@ +//! Traits to represent a database driver. +//! +//! # Support +//! +//! ## Tier 1 +//! +//! Tier 1 support can be thought of as "guaranteed to work". Automated testing is setup to +//! ensure a high level of stability and functionality. +//! +//! | Database | Version | Driver | +//! | - | - | - | +//! | [MariaDB] | 10.1+ | [`mysql`] | +//! | [Microsoft SQL Server] | 2019 | [`mssql`] (Pending a full rewrite) | +//! | [MySQL] | 5.6, 5.7, 8.0 | [`mysql`] | +//! | [PostgreSQL] | 13+ | [`postgres`] | +//! | [SQLite] | 3.20.1+ | [`sqlite`] | +//! +//! [MariaDB]: https://mariadb.com/ +//! [MySQL]: https://www.mysql.com/ +//! [Microsoft SQL Server]: https://www.microsoft.com/en-us/sql-server +//! [PostgreSQL]: https://www.postgresql.org/ +//! [SQLite]: https://www.sqlite.org/ +//! +//! [`mysql`]: crate::mysql +//! [`postgres`]: crate::postgres +//! [`mssql`]: crate::mssql +//! [`sqlite`]: crate::sqlite +//! +//! ## Tier 2 +//! +//! Tier 2 support can be thought as "should work". No specific automated testing is done, +//! at this time, but there are efforts to ensure compatibility. Tier 2 support also includes +//! database distributions that provide protocols that closely match a database from Tier 1. +//! +//! _No databases are in tier 2 at this time._ +//! +//! # `Any` +//! +//! Selecting a database driver is, by default, a compile-time decision. SQLx is designed this way +//! to take full advantage of the performance and type safety made available by Rust. +//! +//! We recognize that you may wish to make a runtime decision to decide the database driver. The +//! [`Any`](crate::any) driver is provided for that purpose. +//! +//! ## Example +//! +//! ```rust,ignore +//! // connect to SQLite +//! let conn = AnyConnection::connect("sqlite://file.db").await?; +//! +//! // connect to Postgres, no code change +//! // required, decided by the scheme of the URL +//! let conn = AnyConnection::connect("postgres://localhost/sqlx").await?; +//! ``` + +use std::fmt::Debug; + +use crate::arguments::Arguments; +use crate::column::Column; +use crate::connection::Connection; +use crate::row::Row; + +use crate::statement::Statement; +use crate::transaction::TransactionManager; +use crate::type_info::TypeInfo; +use crate::value::{Value, ValueRef}; + +/// A database driver. +/// +/// This trait encapsulates a complete set of traits that implement a driver for a +/// specific database (e.g., MySQL, PostgreSQL). +pub trait Database: 'static + Sized + Send + Debug { + /// The concrete `Connection` implementation for this database. + type Connection: Connection; + + /// The concrete `TransactionManager` implementation for this database. + type TransactionManager: TransactionManager; + + /// The concrete `Row` implementation for this database. + type Row: Row; + + /// The concrete `QueryResult` implementation for this database. + type QueryResult: 'static + Sized + Send + Sync + Default + Extend; + + /// The concrete `Column` implementation for this database. + type Column: Column; + + /// The concrete `TypeInfo` implementation for this database. + type TypeInfo: TypeInfo; + + /// The concrete type used to hold an owned copy of the not-yet-decoded value that was + /// received from the database. + type Value: Value + 'static; + /// The concrete type used to hold a reference to the not-yet-decoded value that has just been + /// received from the database. + type ValueRef<'r>: ValueRef<'r, Database = Self>; + + /// The concrete `Arguments` implementation for this database. + type Arguments: Arguments; + /// The concrete type used as a buffer for arguments while encoding. + type ArgumentBuffer; + + /// The concrete `Statement` implementation for this database. + type Statement: Statement; + + /// The display name for this database driver. + const NAME: &'static str; + + /// The schemes for database URLs that should match this driver. + const URL_SCHEMES: &'static [&'static str]; +} + +/// A [`Database`] that maintains a client-side cache of prepared statements. +pub trait HasStatementCache {} diff --git a/vendor/sqlx-core/src/decode.rs b/vendor/sqlx-core/src/decode.rs new file mode 100755 index 0000000..87dd0f6 --- /dev/null +++ b/vendor/sqlx-core/src/decode.rs @@ -0,0 +1,140 @@ +//! Provides [`Decode`] for decoding values from the database. + +use std::borrow::Cow; +use std::rc::Rc; +use std::sync::Arc; + +use crate::database::Database; +use crate::error::BoxDynError; + +use crate::value::ValueRef; + +/// A type that can be decoded from the database. +/// +/// ## How can I implement `Decode`? +/// +/// A manual implementation of `Decode` can be useful when adding support for +/// types externally to SQLx. +/// +/// The following showcases how to implement `Decode` to be generic over [`Database`]. The +/// implementation can be marginally simpler if you remove the `DB` type parameter and explicitly +/// use the concrete [`ValueRef`](Database::ValueRef) and [`TypeInfo`](Database::TypeInfo) types. +/// +/// ```rust +/// # use sqlx_core::database::{Database}; +/// # use sqlx_core::decode::Decode; +/// # use sqlx_core::types::Type; +/// # use std::error::Error; +/// # +/// struct MyType; +/// +/// # impl Type for MyType { +/// # fn type_info() -> DB::TypeInfo { todo!() } +/// # } +/// # +/// # impl std::str::FromStr for MyType { +/// # type Err = sqlx_core::error::Error; +/// # fn from_str(s: &str) -> Result { todo!() } +/// # } +/// # +/// // DB is the database driver +/// // `'r` is the lifetime of the `Row` being decoded +/// impl<'r, DB: Database> Decode<'r, DB> for MyType +/// where +/// // we want to delegate some of the work to string decoding so let's make sure strings +/// // are supported by the database +/// &'r str: Decode<'r, DB> +/// { +/// fn decode( +/// value: ::ValueRef<'r>, +/// ) -> Result> { +/// // the interface of ValueRef is largely unstable at the moment +/// // so this is not directly implementable +/// +/// // however, you can delegate to a type that matches the format of the type you want +/// // to decode (such as a UTF-8 string) +/// +/// let value = <&str as Decode>::decode(value)?; +/// +/// // now you can parse this into your type (assuming there is a `FromStr`) +/// +/// Ok(value.parse()?) +/// } +/// } +/// ``` +pub trait Decode<'r, DB: Database>: Sized { + /// Decode a new value of this type using a raw value from the database. + fn decode(value: ::ValueRef<'r>) -> Result; +} + +// implement `Decode` for Option for all SQL types +impl<'r, DB, T> Decode<'r, DB> for Option +where + DB: Database, + T: Decode<'r, DB>, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + if value.is_null() { + Ok(None) + } else { + Ok(Some(T::decode(value)?)) + } + } +} + +macro_rules! impl_decode_for_smartpointer { + ($smart_pointer:tt) => { + impl<'r, DB, T> Decode<'r, DB> for $smart_pointer + where + DB: Database, + T: Decode<'r, DB>, + { + fn decode(value: ::ValueRef<'r>) -> Result { + Ok(Self::new(T::decode(value)?)) + } + } + + impl<'r, DB> Decode<'r, DB> for $smart_pointer + where + DB: Database, + &'r str: Decode<'r, DB>, + { + fn decode(value: ::ValueRef<'r>) -> Result { + let ref_str = <&str as Decode>::decode(value)?; + Ok(ref_str.into()) + } + } + + impl<'r, DB> Decode<'r, DB> for $smart_pointer<[u8]> + where + DB: Database, + Vec: Decode<'r, DB>, + { + fn decode(value: ::ValueRef<'r>) -> Result { + // The `Postgres` implementation requires this to be decoded as an owned value because + // bytes can be sent in text format. + let bytes = as Decode>::decode(value)?; + Ok(bytes.into()) + } + } + }; +} + +impl_decode_for_smartpointer!(Arc); +impl_decode_for_smartpointer!(Box); +impl_decode_for_smartpointer!(Rc); + +// implement `Decode` for Cow for all SQL types +impl<'r, DB, T> Decode<'r, DB> for Cow<'_, T> +where + DB: Database, + // `ToOwned` is required here to satisfy `Cow` + T: ToOwned + ?Sized, + ::Owned: Decode<'r, DB>, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + // See https://github.com/launchbadge/sqlx/pull/3674#discussion_r2008611502 for more info + // about why decoding to a `Cow::Owned` was chosen. + <::Owned as Decode>::decode(value).map(Cow::Owned) + } +} diff --git a/vendor/sqlx-core/src/describe.rs b/vendor/sqlx-core/src/describe.rs new file mode 100755 index 0000000..887d83c --- /dev/null +++ b/vendor/sqlx-core/src/describe.rs @@ -0,0 +1,101 @@ +use crate::database::Database; +use either::Either; +use std::convert::identity; + +/// Provides extended information on a statement. +/// +/// Returned from [`Executor::describe`]. +/// +/// The query macros (e.g., `query!`, `query_as!`, etc.) use the information here to validate +/// output and parameter types; and, generate an anonymous record. +#[derive(Debug)] +#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr( + feature = "offline", + serde(bound( + serialize = "DB::TypeInfo: serde::Serialize, DB::Column: serde::Serialize", + deserialize = "DB::TypeInfo: serde::de::DeserializeOwned, DB::Column: serde::de::DeserializeOwned", + )) +)] +#[doc(hidden)] +pub struct Describe { + pub columns: Vec, + pub parameters: Option, usize>>, + pub nullable: Vec>, +} + +impl Describe { + /// Gets all columns in this statement. + pub fn columns(&self) -> &[DB::Column] { + &self.columns + } + + /// Gets the column information at `index`. + /// + /// Panics if `index` is out of bounds. + pub fn column(&self, index: usize) -> &DB::Column { + &self.columns[index] + } + + /// Gets the available information for parameters in this statement. + /// + /// Some drivers may return more or less than others. As an example, **PostgreSQL** will + /// return `Some(Either::Left(_))` with a full list of type information for each parameter. + /// However, **MSSQL** will return `None` as there is no information available. + pub fn parameters(&self) -> Option> { + self.parameters.as_ref().map(|p| match p { + Either::Left(params) => Either::Left(&**params), + Either::Right(count) => Either::Right(*count), + }) + } + + /// Gets whether a column may be `NULL`, if this information is available. + pub fn nullable(&self, column: usize) -> Option { + self.nullable.get(column).copied().and_then(identity) + } +} + +#[cfg(feature = "any")] +impl Describe { + #[doc(hidden)] + pub fn try_into_any(self) -> crate::Result> + where + crate::any::AnyColumn: for<'a> TryFrom<&'a DB::Column, Error = crate::Error>, + crate::any::AnyTypeInfo: for<'a> TryFrom<&'a DB::TypeInfo, Error = crate::Error>, + { + use crate::any::AnyTypeInfo; + + let columns = self + .columns + .iter() + .map(crate::any::AnyColumn::try_from) + .collect::, _>>()?; + + let parameters = match self.parameters { + Some(Either::Left(parameters)) => Some(Either::Left( + parameters + .iter() + .enumerate() + .map(|(i, type_info)| { + AnyTypeInfo::try_from(type_info).map_err(|_| { + crate::Error::AnyDriverError( + format!( + "Any driver does not support type {type_info} of parameter {i}" + ) + .into(), + ) + }) + }) + .collect::, _>>()?, + )), + Some(Either::Right(count)) => Some(Either::Right(count)), + None => None, + }; + + Ok(Describe { + columns, + parameters, + nullable: self.nullable, + }) + } +} diff --git a/vendor/sqlx-core/src/encode.rs b/vendor/sqlx-core/src/encode.rs new file mode 100755 index 0000000..173c283 --- /dev/null +++ b/vendor/sqlx-core/src/encode.rs @@ -0,0 +1,216 @@ +//! Provides [`Encode`] for encoding values for the database. + +use std::borrow::Cow; +use std::mem; +use std::rc::Rc; +use std::sync::Arc; + +use crate::database::Database; +use crate::error::BoxDynError; + +/// The return type of [Encode::encode]. +#[must_use] +pub enum IsNull { + /// The value is null; no data was written. + Yes, + + /// The value is not null. + /// + /// This does not mean that data was written. + No, +} + +impl IsNull { + pub fn is_null(&self) -> bool { + matches!(self, IsNull::Yes) + } +} + +/// Encode a single value to be sent to the database. +pub trait Encode<'q, DB: Database> { + /// Writes the value of `self` into `buf` in the expected format for the database. + fn encode(self, buf: &mut ::ArgumentBuffer) -> Result + where + Self: Sized, + { + self.encode_by_ref(buf) + } + + /// Writes the value of `self` into `buf` without moving `self`. + /// + /// Where possible, make use of `encode` instead as it can take advantage of re-using + /// memory. + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result; + + fn produces(&self) -> Option { + // `produces` is inherently a hook to allow database drivers to produce value-dependent + // type information; if the driver doesn't need this, it can leave this as `None` + None + } + + #[inline] + fn size_hint(&self) -> usize { + mem::size_of_val(self) + } +} + +impl<'q, T, DB: Database> Encode<'q, DB> for &'_ T +where + T: Encode<'q, DB>, +{ + #[inline] + fn encode(self, buf: &mut ::ArgumentBuffer) -> Result { + >::encode_by_ref(self, buf) + } + + #[inline] + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + <&T as Encode>::encode(self, buf) + } + + #[inline] + fn produces(&self) -> Option { + (**self).produces() + } + + #[inline] + fn size_hint(&self) -> usize { + (**self).size_hint() + } +} + +#[macro_export] +macro_rules! impl_encode_for_option { + ($DB:ident) => { + impl<'q, T> $crate::encode::Encode<'q, $DB> for Option + where + T: $crate::encode::Encode<'q, $DB> + $crate::types::Type<$DB> + 'q, + { + #[inline] + fn produces(&self) -> Option<<$DB as $crate::database::Database>::TypeInfo> { + if let Some(v) = self { + v.produces() + } else { + T::type_info().into() + } + } + + #[inline] + fn encode( + self, + buf: &mut <$DB as $crate::database::Database>::ArgumentBuffer, + ) -> Result<$crate::encode::IsNull, $crate::error::BoxDynError> { + if let Some(v) = self { + v.encode(buf) + } else { + Ok($crate::encode::IsNull::Yes) + } + } + + #[inline] + fn encode_by_ref( + &self, + buf: &mut <$DB as $crate::database::Database>::ArgumentBuffer, + ) -> Result<$crate::encode::IsNull, $crate::error::BoxDynError> { + if let Some(v) = self { + v.encode_by_ref(buf) + } else { + Ok($crate::encode::IsNull::Yes) + } + } + + #[inline] + fn size_hint(&self) -> usize { + self.as_ref().map_or(0, $crate::encode::Encode::size_hint) + } + } + }; +} + +macro_rules! impl_encode_for_smartpointer { + ($smart_pointer:ty) => { + impl<'q, T, DB: Database> Encode<'q, DB> for $smart_pointer + where + T: Encode<'q, DB>, + { + #[inline] + fn encode( + self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + >::encode_by_ref(self.as_ref(), buf) + } + + #[inline] + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + <&T as Encode>::encode(self, buf) + } + + #[inline] + fn produces(&self) -> Option { + (**self).produces() + } + + #[inline] + fn size_hint(&self) -> usize { + (**self).size_hint() + } + } + }; +} + +impl_encode_for_smartpointer!(Arc); +impl_encode_for_smartpointer!(Box); +impl_encode_for_smartpointer!(Rc); + +impl<'q, T, DB: Database> Encode<'q, DB> for Cow<'q, T> +where + T: Encode<'q, DB>, + T: ToOwned, +{ + #[inline] + fn encode(self, buf: &mut ::ArgumentBuffer) -> Result { + <&T as Encode>::encode_by_ref(&self.as_ref(), buf) + } + + #[inline] + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + <&T as Encode>::encode_by_ref(&self.as_ref(), buf) + } + + #[inline] + fn produces(&self) -> Option { + <&T as Encode>::produces(&self.as_ref()) + } + + #[inline] + fn size_hint(&self) -> usize { + <&T as Encode>::size_hint(&self.as_ref()) + } +} + +#[macro_export] +macro_rules! forward_encode_impl { + ($for_type:ty, $forward_to:ty, $db:ident) => { + impl<'q> Encode<'q, $db> for $for_type { + fn encode_by_ref( + &self, + buf: &mut <$db as sqlx_core::database::Database>::ArgumentBuffer, + ) -> Result { + <$forward_to as Encode<$db>>::encode(self.as_ref(), buf) + } + } + }; +} diff --git a/vendor/sqlx-core/src/error.rs b/vendor/sqlx-core/src/error.rs new file mode 100755 index 0000000..8c6f424 --- /dev/null +++ b/vendor/sqlx-core/src/error.rs @@ -0,0 +1,353 @@ +//! Types for working with errors produced by SQLx. + +use std::any::type_name; +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fmt::Display; +use std::io; + +use crate::database::Database; + +use crate::type_info::TypeInfo; +use crate::types::Type; + +/// A specialized `Result` type for SQLx. +pub type Result = ::std::result::Result; + +// Convenience type alias for usage within SQLx. +// Do not make this type public. +pub type BoxDynError = Box; + +/// An unexpected `NULL` was encountered during decoding. +/// +/// Returned from [`Row::get`](crate::row::Row::get) if the value from the database is `NULL`, +/// and you are not decoding into an `Option`. +#[derive(thiserror::Error, Debug)] +#[error("unexpected null; try decoding as an `Option`")] +pub struct UnexpectedNullError; + +/// Represents all the ways a method can fail within SQLx. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// Error occurred while parsing a connection string. + #[error("error with configuration: {0}")] + Configuration(#[source] BoxDynError), + + /// One or more of the arguments to the called function was invalid. + /// + /// The string contains more information. + #[error("{0}")] + InvalidArgument(String), + + /// Error returned from the database. + #[error("error returned from database: {0}")] + Database(#[source] Box), + + /// Error communicating with the database backend. + #[error("error communicating with database: {0}")] + Io(#[from] io::Error), + + /// Error occurred while attempting to establish a TLS connection. + #[error("error occurred while attempting to establish a TLS connection: {0}")] + Tls(#[source] BoxDynError), + + /// Unexpected or invalid data encountered while communicating with the database. + /// + /// This should indicate there is a programming error in a SQLx driver or there + /// is something corrupted with the connection to the database itself. + #[error("encountered unexpected or invalid data: {0}")] + Protocol(String), + + /// No rows returned by a query that expected to return at least one row. + #[error("no rows returned by a query that expected to return at least one row")] + RowNotFound, + + /// Type in query doesn't exist. Likely due to typo or missing user type. + #[error("type named {type_name} not found")] + TypeNotFound { type_name: String }, + + /// Column index was out of bounds. + #[error("column index out of bounds: the len is {len}, but the index is {index}")] + ColumnIndexOutOfBounds { index: usize, len: usize }, + + /// No column found for the given name. + #[error("no column found for name: {0}")] + ColumnNotFound(String), + + /// Error occurred while decoding a value from a specific column. + #[error("error occurred while decoding column {index}: {source}")] + ColumnDecode { + index: String, + + #[source] + source: BoxDynError, + }, + + /// Error occurred while encoding a value. + #[error("error occurred while encoding a value: {0}")] + Encode(#[source] BoxDynError), + + /// Error occurred while decoding a value. + #[error("error occurred while decoding: {0}")] + Decode(#[source] BoxDynError), + + /// Error occurred within the `Any` driver mapping to/from the native driver. + #[error("error in Any driver mapping: {0}")] + AnyDriverError(#[source] BoxDynError), + + /// A [`Pool::acquire`] timed out due to connections not becoming available or + /// because another task encountered too many errors while trying to open a new connection. + /// + /// [`Pool::acquire`]: crate::pool::Pool::acquire + #[error("pool timed out while waiting for an open connection")] + PoolTimedOut, + + /// [`Pool::close`] was called while we were waiting in [`Pool::acquire`]. + /// + /// [`Pool::acquire`]: crate::pool::Pool::acquire + /// [`Pool::close`]: crate::pool::Pool::close + #[error("attempted to acquire a connection on a closed pool")] + PoolClosed, + + /// A background worker has crashed. + #[error("attempted to communicate with a crashed background worker")] + WorkerCrashed, + + #[cfg(feature = "migrate")] + #[error("{0}")] + Migrate(#[source] Box), + + #[error("attempted to call begin_with at non-zero transaction depth")] + InvalidSavePointStatement, + + #[error("got unexpected connection status after attempting to begin transaction")] + BeginFailed, + + // Not returned in normal operation. + /// Error occurred while reading configuration file + #[doc(hidden)] + #[error("error reading configuration file: {0}")] + ConfigFile(#[from] crate::config::ConfigError), +} + +impl StdError for Box {} + +impl Error { + pub fn into_database_error(self) -> Option> { + match self { + Error::Database(err) => Some(err), + _ => None, + } + } + + pub fn as_database_error(&self) -> Option<&(dyn DatabaseError + 'static)> { + match self { + Error::Database(err) => Some(&**err), + _ => None, + } + } + + #[doc(hidden)] + #[inline] + pub fn protocol(err: impl Display) -> Self { + Error::Protocol(err.to_string()) + } + + #[doc(hidden)] + #[inline] + pub fn database(err: impl DatabaseError) -> Self { + Error::Database(Box::new(err)) + } + + #[doc(hidden)] + #[inline] + pub fn config(err: impl StdError + Send + Sync + 'static) -> Self { + Error::Configuration(err.into()) + } + + pub(crate) fn tls(err: impl Into>) -> Self { + Error::Tls(err.into()) + } + + #[doc(hidden)] + #[inline] + pub fn decode(err: impl Into>) -> Self { + Error::Decode(err.into()) + } +} + +pub fn mismatched_types>(ty: &DB::TypeInfo) -> BoxDynError { + // TODO: `#name` only produces `TINYINT` but perhaps we want to show `TINYINT(1)` + format!( + "mismatched types; Rust type `{}` (as SQL type `{}`) is not compatible with SQL type `{}`", + type_name::(), + T::type_info().name(), + ty.name() + ) + .into() +} + +/// The error kind. +/// +/// This enum is to be used to identify frequent errors that can be handled by the program. +/// Although it currently only supports constraint violations, the type may grow in the future. +#[derive(Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ErrorKind { + /// Unique/primary key constraint violation. + UniqueViolation, + /// Foreign key constraint violation. + ForeignKeyViolation, + /// Not-null constraint violation. + NotNullViolation, + /// Check constraint violation. + CheckViolation, + /// Exclusion constraint violation. + ExclusionViolation, + /// An unmapped error. + Other, +} + +/// An error that was returned from the database. +pub trait DatabaseError: 'static + Send + Sync + StdError { + /// The primary, human-readable error message. + fn message(&self) -> &str; + + /// The (SQLSTATE) code for the error. + fn code(&self) -> Option> { + None + } + + #[doc(hidden)] + fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static); + + #[doc(hidden)] + fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static); + + #[doc(hidden)] + fn into_error(self: Box) -> Box; + + #[doc(hidden)] + fn is_transient_in_connect_phase(&self) -> bool { + false + } + + /// Returns the name of the constraint that triggered the error, if applicable. + /// If the error was caused by a conflict of a unique index, this will be the index name. + /// + /// ### Note + /// Currently only populated by the Postgres driver. + fn constraint(&self) -> Option<&str> { + None + } + + /// Returns the name of the table that was affected by the error, if applicable. + /// + /// ### Note + /// Currently only populated by the Postgres driver. + fn table(&self) -> Option<&str> { + None + } + + /// Returns the kind of the error, if supported. + /// + /// ### Note + /// Not all back-ends behave the same when reporting the error code. + fn kind(&self) -> ErrorKind; + + /// Returns whether the error kind is a violation of a unique/primary key constraint. + fn is_unique_violation(&self) -> bool { + matches!(self.kind(), ErrorKind::UniqueViolation) + } + + /// Returns whether the error kind is a violation of a foreign key. + fn is_foreign_key_violation(&self) -> bool { + matches!(self.kind(), ErrorKind::ForeignKeyViolation) + } + + /// Returns whether the error kind is a violation of a check. + fn is_check_violation(&self) -> bool { + matches!(self.kind(), ErrorKind::CheckViolation) + } +} + +impl dyn DatabaseError { + /// Downcast a reference to this generic database error to a specific + /// database error type. + /// + /// # Panics + /// + /// Panics if the database error type is not `E`. This is a deliberate contrast from + /// `Error::downcast_ref` which returns `Option<&E>`. In normal usage, you should know the + /// specific error type. In other cases, use `try_downcast_ref`. + pub fn downcast_ref(&self) -> &E { + self.try_downcast_ref().unwrap_or_else(|| { + panic!("downcast to wrong DatabaseError type; original error: {self}") + }) + } + + /// Downcast this generic database error to a specific database error type. + /// + /// # Panics + /// + /// Panics if the database error type is not `E`. This is a deliberate contrast from + /// `Error::downcast` which returns `Option`. In normal usage, you should know the + /// specific error type. In other cases, use `try_downcast`. + pub fn downcast(self: Box) -> Box { + self.try_downcast() + .unwrap_or_else(|e| panic!("downcast to wrong DatabaseError type; original error: {e}")) + } + + /// Downcast a reference to this generic database error to a specific + /// database error type. + #[inline] + pub fn try_downcast_ref(&self) -> Option<&E> { + self.as_error().downcast_ref() + } + + /// Downcast this generic database error to a specific database error type. + #[inline] + pub fn try_downcast(self: Box) -> Result, Box> { + if self.as_error().is::() { + Ok(self.into_error().downcast().unwrap()) + } else { + Err(self) + } + } +} + +impl From for Error +where + E: DatabaseError, +{ + #[inline] + fn from(error: E) -> Self { + Error::Database(Box::new(error)) + } +} + +#[cfg(feature = "migrate")] +impl From for Error { + #[inline] + fn from(error: crate::migrate::MigrateError) -> Self { + Error::Migrate(Box::new(error)) + } +} + +/// Format an error message as a `Protocol` error +#[macro_export] +macro_rules! err_protocol { + ($($fmt_args:tt)*) => { + $crate::error::Error::Protocol( + format!( + "{} ({}:{})", + // Note: the format string needs to be unmodified (e.g. by `concat!()`) + // for implicit formatting arguments to work + format_args!($($fmt_args)*), + module_path!(), + line!(), + ) + ) + }; +} diff --git a/vendor/sqlx-core/src/executor.rs b/vendor/sqlx-core/src/executor.rs new file mode 100755 index 0000000..e146c7a --- /dev/null +++ b/vendor/sqlx-core/src/executor.rs @@ -0,0 +1,284 @@ +use crate::database::Database; +use crate::error::{BoxDynError, Error}; +use crate::sql_str::{SqlSafeStr, SqlStr}; + +use either::Either; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; +use futures_util::{FutureExt, StreamExt, TryFutureExt, TryStreamExt}; +use std::{fmt::Debug, future}; + +/// A type that contains or can provide a database +/// connection to use for executing queries against the database. +/// +/// No guarantees are provided that successive queries run on the same +/// physical database connection. +/// +/// A [`Connection`](crate::connection::Connection) is an `Executor` that guarantees that +/// successive queries are ran on the same physical database connection. +/// +/// Implemented for the following: +/// +/// * [`&Pool`](super::pool::Pool) +/// * [`&mut Connection`](super::connection::Connection) +/// +/// The [`Executor`] impls for [`Transaction`](crate::transaction::Transaction) +/// and [`PoolConnection`](crate::pool::PoolConnection) have been deleted because they +/// cannot exist in the new crate architecture without rewriting the Executor trait entirely. +/// To fix this breakage, simply add a dereference where an impl [`Executor`] is expected, as +/// they both dereference to the inner connection type which will still implement it: +/// * `&mut transaction` -> `&mut *transaction` +/// * `&mut connection` -> `&mut *connection` +/// +/// # Note: Methods Not for General Use +/// This is a building-block trait that is exposed mainly for use as a trait bound. +/// +/// Instead of calling the methods of this trait, use the free functions in the `sqlx` crate root: +/// * [`sqlx::query()`]: use for DML queries (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, etc.) +/// * uses and caches prepared statements internally per-connection +/// * may use argument placeholders (MySQL/MariaDB: `?`, Postgres/SQLite: `$1`, `$2`, etc.) +/// * one query per string +/// * [`sqlx::query_as()`], [`sqlx::query_scalar()`]: preferred for DML queries with type mapping +/// * [`sqlx::raw_sql()`]: for DDL (`CREATE`, `ALTER`, etc.), batch queries and administration functions +/// * accepts multiple queries separated by semicolons (`;`) in the same string +/// * never uses prepared statements +/// +/// Consider also the `query!()` family of macros, which offer queries and type mapping checked +/// at compile-time. +/// +/// [`sqlx::query()`]: crate::query::query +/// [`sqlx::query_as()`]: crate::query_as::query_as +/// [`sqlx::query_scalar()`]: crate::query_scalar::query_scalar +/// [`sqlx::raw_sql()`]: crate::raw_sql::raw_sql +pub trait Executor<'c>: Send + Debug + Sized { + type Database: Database; + + /// Execute the query and return the total number of rows affected. + fn execute<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxFuture<'e, Result<::QueryResult, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>, + { + self.execute_many(query).try_collect().boxed() + } + + /// Execute multiple queries and return the rows affected from each query, in a stream. + fn execute_many<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxStream<'e, Result<::QueryResult, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>, + { + self.fetch_many(query) + .try_filter_map(|step| async move { + Ok(match step { + Either::Left(rows) => Some(rows), + Either::Right(_) => None, + }) + }) + .boxed() + } + + /// Execute the query and return the generated results as a stream. + fn fetch<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxStream<'e, Result<::Row, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>, + { + self.fetch_many(query) + .try_filter_map(|step| async move { + Ok(match step { + Either::Left(_) => None, + Either::Right(row) => Some(row), + }) + }) + .boxed() + } + + /// Execute multiple queries and return the generated results as a stream + /// from each query, in a stream. + fn fetch_many<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxStream< + 'e, + Result< + Either<::QueryResult, ::Row>, + Error, + >, + > + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>; + + /// Execute the query and return all the generated results, collected into a [`Vec`]. + fn fetch_all<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxFuture<'e, Result::Row>, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>, + { + self.fetch(query).try_collect().boxed() + } + + /// Execute the query and returns exactly one row. + fn fetch_one<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxFuture<'e, Result<::Row, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>, + { + self.fetch_optional(query) + .and_then(|row| { + future::ready(match row { + Some(row) => Ok(row), + None => Err(Error::RowNotFound), + }) + }) + .boxed() + } + + /// Execute the query and returns at most one row. + fn fetch_optional<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxFuture<'e, Result::Row>, Error>> + where + 'c: 'e, + E: 'q + Execute<'q, Self::Database>; + + /// Prepare the SQL query to inspect the type information of its parameters + /// and results. + /// + /// Be advised that when using the `query`, `query_as`, or `query_scalar` functions, the query + /// is transparently prepared and executed. + /// + /// This explicit API is provided to allow access to the statement metadata available after + /// it prepared but before the first row is returned. + #[inline] + fn prepare<'e>( + self, + query: SqlStr, + ) -> BoxFuture<'e, Result<::Statement, Error>> + where + 'c: 'e, + { + self.prepare_with(query, &[]) + } + + /// Prepare the SQL query, with parameter type information, to inspect the + /// type information about its parameters and results. + /// + /// Only some database drivers (PostgreSQL, MSSQL) can take advantage of + /// this extra information to influence parameter type inference. + fn prepare_with<'e>( + self, + sql: SqlStr, + parameters: &'e [::TypeInfo], + ) -> BoxFuture<'e, Result<::Statement, Error>> + where + 'c: 'e; + + /// Describe the SQL query and return type information about its parameters + /// and results. + /// + /// This is used by compile-time verification in the query macros to + /// power their type inference. + #[doc(hidden)] + #[cfg(feature = "offline")] + fn describe<'e>( + self, + sql: SqlStr, + ) -> BoxFuture<'e, Result, Error>> + where + 'c: 'e; +} + +/// A type that may be executed against a database connection. +/// +/// Implemented for the following: +/// +/// * [`&str`](std::str) +/// * [`Query`](super::query::Query) +/// +pub trait Execute<'q, DB: Database>: Send + Sized { + /// Gets the SQL that will be executed. + fn sql(self) -> SqlStr; + + /// Gets the previously cached statement, if available. + fn statement(&self) -> Option<&DB::Statement>; + + /// Returns the arguments to be bound against the query string. + /// + /// Returning `Ok(None)` for `Arguments` indicates to use a "simple" query protocol and to not + /// prepare the query. Returning `Ok(Some(Default::default()))` is an empty arguments object that + /// will be prepared (and cached) before execution. + /// + /// Returns `Err` if encoding any of the arguments failed. + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError>; + + /// Returns `true` if the statement should be cached. + fn persistent(&self) -> bool; +} + +impl Execute<'_, DB> for T +where + T: SqlSafeStr + Send, +{ + #[inline] + fn sql(self) -> SqlStr { + self.into_sql_str() + } + + #[inline] + fn statement(&self) -> Option<&DB::Statement> { + None + } + + #[inline] + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + Ok(None) + } + + #[inline] + fn persistent(&self) -> bool { + true + } +} + +impl Execute<'_, DB> for (T, Option<::Arguments>) +where + T: SqlSafeStr + Send, +{ + #[inline] + fn sql(self) -> SqlStr { + self.0.into_sql_str() + } + + #[inline] + fn statement(&self) -> Option<&DB::Statement> { + None + } + + #[inline] + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + Ok(self.1.take()) + } + + #[inline] + fn persistent(&self) -> bool { + true + } +} diff --git a/vendor/sqlx-core/src/ext/async_stream.rs b/vendor/sqlx-core/src/ext/async_stream.rs new file mode 100755 index 0000000..31c4db2 --- /dev/null +++ b/vendor/sqlx-core/src/ext/async_stream.rs @@ -0,0 +1,138 @@ +//! A minimalist clone of the `async-stream` crate in 100% safe code, without proc macros. +//! +//! This was created initially to get around some weird compiler errors we were getting with +//! `async-stream`, and now it'd just be more work to replace. + +use std::future::{self, Future}; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; + +use futures_core::future::BoxFuture; +use futures_core::stream::Stream; +use futures_core::FusedFuture; +use futures_util::future::Fuse; +use futures_util::FutureExt; + +use crate::error::Error; + +pub struct TryAsyncStream<'a, T> { + yielder: Yielder, + future: Fuse>>, +} + +impl<'a, T> TryAsyncStream<'a, T> { + pub fn new(f: F) -> Self + where + F: FnOnce(Yielder) -> Fut + Send, + Fut: 'a + Future> + Send, + T: 'a + Send, + { + let yielder = Yielder::new(); + + let future = f(yielder.duplicate()).boxed().fuse(); + + Self { future, yielder } + } +} + +pub struct Yielder { + // This mutex should never have any contention in normal operation. + // We're just using it because `Rc>>` would not be `Send`. + value: Arc>>, +} + +impl Yielder { + fn new() -> Self { + Yielder { + value: Arc::new(Mutex::new(None)), + } + } + + // Don't want to expose a `Clone` impl + fn duplicate(&self) -> Self { + Yielder { + value: self.value.clone(), + } + } + + /// NOTE: may deadlock the task if called from outside the future passed to `TryAsyncStream`. + pub async fn r#yield(&self, val: T) { + let replaced = self + .value + .lock() + .expect("BUG: panicked while holding a lock") + .replace(val); + + debug_assert!( + replaced.is_none(), + "BUG: previously yielded value not taken" + ); + + let mut yielded = false; + + // Allows the generating future to suspend its execution without changing the task priority, + // which would happen with `tokio::task::yield_now()`. + // + // Note that because this has no way to schedule a wakeup, this could deadlock the task + // if called in the wrong place. + future::poll_fn(|_cx| { + if !yielded { + yielded = true; + Poll::Pending + } else { + Poll::Ready(()) + } + }) + .await + } + + fn take(&self) -> Option { + self.value + .lock() + .expect("BUG: panicked while holding a lock") + .take() + } +} + +impl Stream for TryAsyncStream<'_, T> { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.future.is_terminated() { + return Poll::Ready(None); + } + + match self.future.poll_unpin(cx) { + Poll::Ready(Ok(())) => { + // Future returned without yielding another value, + // or else it would have returned `Pending` instead. + Poll::Ready(None) + } + Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))), + Poll::Pending => self + .yielder + .take() + .map_or(Poll::Pending, |val| Poll::Ready(Some(Ok(val)))), + } + } +} + +#[macro_export] +macro_rules! try_stream { + ($($block:tt)*) => { + $crate::ext::async_stream::TryAsyncStream::new(move |yielder| ::tracing::Instrument::in_current_span(async move { + // Anti-footgun: effectively pins `yielder` to this future to prevent any accidental + // move to another task, which could deadlock. + let yielder = &yielder; + + macro_rules! r#yield { + ($v:expr) => {{ + yielder.r#yield($v).await; + }} + } + + $($block)* + })) + } +} diff --git a/vendor/sqlx-core/src/ext/mod.rs b/vendor/sqlx-core/src/ext/mod.rs new file mode 100755 index 0000000..98059f8 --- /dev/null +++ b/vendor/sqlx-core/src/ext/mod.rs @@ -0,0 +1,4 @@ +pub mod ustr; + +#[macro_use] +pub mod async_stream; diff --git a/vendor/sqlx-core/src/ext/ustr.rs b/vendor/sqlx-core/src/ext/ustr.rs new file mode 100755 index 0000000..95fa754 --- /dev/null +++ b/vendor/sqlx-core/src/ext/ustr.rs @@ -0,0 +1,121 @@ +use std::borrow::Borrow; +use std::fmt::{self, Debug, Display, Formatter}; +use std::hash::{Hash, Hasher}; +use std::ops::Deref; +use std::sync::Arc; + +// U meaning micro +// a micro-string is either a reference-counted string or a static string +// this guarantees these are cheap to clone everywhere +#[derive(Clone, Eq)] +pub enum UStr { + Static(&'static str), + Shared(Arc), +} + +impl UStr { + pub fn new(s: &str) -> Self { + UStr::Shared(Arc::from(s.to_owned())) + } + + /// Apply [str::strip_prefix], without copying if possible. + pub fn strip_prefix(this: &Self, prefix: &str) -> Option { + match this { + UStr::Static(s) => s.strip_prefix(prefix).map(Self::Static), + UStr::Shared(s) => s.strip_prefix(prefix).map(|s| Self::Shared(s.into())), + } + } +} + +impl Deref for UStr { + type Target = str; + + #[inline] + fn deref(&self) -> &str { + match self { + UStr::Static(s) => s, + UStr::Shared(s) => s, + } + } +} + +impl Hash for UStr { + #[inline] + fn hash(&self, state: &mut H) { + // Forward the hash to the string representation of this + // A derive(Hash) encodes the enum discriminant + (**self).hash(state); + } +} + +impl Borrow for UStr { + #[inline] + fn borrow(&self) -> &str { + self + } +} + +impl PartialEq for UStr { + fn eq(&self, other: &UStr) -> bool { + (**self).eq(&**other) + } +} + +impl From<&'static str> for UStr { + #[inline] + fn from(s: &'static str) -> Self { + UStr::Static(s) + } +} + +impl<'a> From<&'a UStr> for UStr { + fn from(value: &'a UStr) -> Self { + value.clone() + } +} + +impl From for UStr { + #[inline] + fn from(s: String) -> Self { + UStr::Shared(s.into()) + } +} + +impl Debug for UStr { + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.pad(self) + } +} + +impl Display for UStr { + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.pad(self) + } +} + +// manual impls because otherwise things get a little screwy with lifetimes + +#[cfg(feature = "offline")] +impl<'de> serde::Deserialize<'de> for UStr { + fn deserialize(deserializer: D) -> Result>::Error> + where + D: serde::Deserializer<'de>, + { + Ok(String::deserialize(deserializer)?.into()) + } +} + +#[cfg(feature = "offline")] +impl serde::Serialize for UStr { + fn serialize( + &self, + serializer: S, + ) -> Result<::Ok, ::Error> + where + S: serde::Serializer, + { + serializer.serialize_str(self) + } +} diff --git a/vendor/sqlx-core/src/from_row.rs b/vendor/sqlx-core/src/from_row.rs new file mode 100755 index 0000000..b96801c --- /dev/null +++ b/vendor/sqlx-core/src/from_row.rs @@ -0,0 +1,524 @@ +use crate::{error::Error, row::Row}; + +/// A record that can be built from a row returned by the database. +/// +/// In order to use [`query_as`](crate::query_as) the output type must implement `FromRow`. +/// +/// ## Derivable +/// +/// This trait can be derived by SQLx for any struct. The generated implementation +/// will consist of a sequence of calls to [`Row::try_get`] using the name from each +/// struct field. +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// } +/// ``` +/// +/// ### Field attributes +/// +/// Several attributes can be specified to customize how each column in a row is read: +/// +/// #### `rename` +/// +/// When the name of a field in Rust does not match the name of its corresponding column, +/// you can use the `rename` attribute to specify the name that the field has in the row. +/// For example: +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(rename = "description")] +/// about_me: String +/// } +/// ``` +/// +/// Given a query such as: +/// +/// ```sql +/// SELECT id, name, description FROM users; +/// ``` +/// +/// will read the content of the column `description` into the field `about_me`. +/// +/// #### `rename_all` +/// By default, field names are expected verbatim (with the exception of the raw identifier prefix `r#`, if present). +/// Placed at the struct level, this attribute changes how the field name is mapped to its SQL column name: +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// #[sqlx(rename_all = "camelCase")] +/// struct UserPost { +/// id: i32, +/// // remapped to "userId" +/// user_id: i32, +/// contents: String +/// } +/// ``` +/// +/// The supported values are `snake_case` (available if you have non-snake-case field names for some +/// reason), `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`, `SCREAMING_SNAKE_CASE` and `kebab-case`. +/// The styling of each option is intended to be an example of its behavior. +/// +/// Case conversion is handled by the `heck` crate. +/// See [its documentation](https://docs.rs/heck/0.5.0/heck/#definition-of-a-word-boundary) +/// for details. +/// +/// Note that numbers are *not* considered separate words. +/// For example, `Foo1` to snake case would be `foo1`, *not* `foo_1`. +/// See [this issue](https://github.com/launchbadge/sqlx/issues/3864) for discussion. +/// +/// #### `default` +/// +/// When your struct contains a field that is not present in your query, +/// if the field type has an implementation for [`Default`], +/// you can use the `default` attribute to assign the default value to said field. +/// For example: +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(default)] +/// location: Option +/// } +/// ``` +/// +/// Given a query such as: +/// +/// ```sql +/// SELECT id, name FROM users; +/// ``` +/// +/// will set the value of the field `location` to the default value of `Option`, +/// which is `None`. +/// +/// Moreover, if the struct has an implementation for [`Default`], you can use the `default` +/// attribute at the struct level rather than for each single field. If a field does not appear in the result, +/// its value is taken from the `Default` implementation for the struct. +/// For example: +/// +/// ```rust, ignore +/// #[derive(Default, sqlx::FromRow)] +/// #[sqlx(default)] +/// struct Options { +/// option_a: Option, +/// option_b: Option, +/// option_c: Option, +/// } +/// ``` +/// +/// For a derived `Default` implementation this effectively populates each missing field +/// with `Default::default()`, but a manual `Default` implementation can provide +/// different placeholder values, if applicable. +/// +/// This is similar to how `#[serde(default)]` behaves. +/// +/// #### `flatten` +/// +/// If you want to handle a field that implements [`FromRow`], +/// you can use the `flatten` attribute to specify that you want +/// it to use [`FromRow`] for parsing rather than the usual method. +/// For example: +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// struct Address { +/// country: String, +/// city: String, +/// road: String, +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(flatten)] +/// address: Address, +/// } +/// ``` +/// Given a query such as: +/// +/// ```sql +/// SELECT id, name, country, city, road FROM users; +/// ``` +/// +/// This field is compatible with the `default` attribute. +/// +/// #### `skip` +/// +/// This is a variant of the `default` attribute which instead always takes the value from +/// the `Default` implementation for this field type ignoring any results in your query. +/// This can be useful, if some field does not satifisfy the trait bounds (i.e. +/// `sqlx::decode::Decode`, `sqlx::type::Type`), in particular in case of nested structures. +/// For example: +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// struct Address { +/// user_name: String, +/// street: String, +/// city: String, +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct User { +/// name: String, +/// #[sqlx(skip)] +/// addresses: Vec
, +/// } +/// ``` +/// +/// Then when querying into `User`, only `name` needs to be set: +/// +/// ```rust,ignore +/// let user: User = sqlx::query_as("SELECT name FROM users") +/// .fetch_one(&mut some_connection) +/// .await?; +/// +/// // `Default` for `Vec
` is an empty vector. +/// assert!(user.addresses.is_empty()); +/// ``` +/// +/// #### `try_from` +/// +/// When your struct contains a field whose type is not matched with the database type, +/// if the field type has an implementation [`TryFrom`] for the database type, +/// you can use the `try_from` attribute to convert the database type to the field type. +/// For example: +/// +/// ```rust,ignore +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(try_from = "i64")] +/// bigIntInMySql: u64 +/// } +/// ``` +/// +/// Given a query such as: +/// +/// ```sql +/// SELECT id, name, bigIntInMySql FROM users; +/// ``` +/// +/// In MySql, `BigInt` type matches `i64`, but you can convert it to `u64` by `try_from`. +/// +/// #### `json` +/// +/// If your database supports a JSON type, you can leverage `#[sqlx(json)]` +/// to automatically integrate JSON deserialization in your [`FromRow`] implementation using [`serde`](https://docs.rs/serde/latest/serde/). +/// +/// ```rust,ignore +/// #[derive(serde::Deserialize)] +/// struct Data { +/// field1: String, +/// field2: u64 +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(json)] +/// metadata: Data +/// } +/// ``` +/// +/// Given a query like the following: +/// +/// ```sql +/// SELECT +/// 1 AS id, +/// 'Name' AS name, +/// JSON_OBJECT('field1', 'value1', 'field2', 42) AS metadata +/// ``` +/// +/// The `metadata` field will be deserialized used its `serde::Deserialize` implementation: +/// +/// ```rust,ignore +/// User { +/// id: 1, +/// name: "Name", +/// metadata: Data { +/// field1: "value1", +/// field2: 42 +/// } +/// } +/// ``` +/// +/// By default the `#[sqlx(json)]` attribute will assume that the underlying database row is +/// _not_ NULL. This can cause issues when your field type is an `Option` because this would be +/// represented as the _not_ NULL (in terms of DB) JSON value of `null`. +/// +/// If you wish to describe a database row which _is_ NULLable but _cannot_ contain the JSON value `null`, +/// use the `#[sqlx(json(nullable))]` attribute. +/// +/// For example +/// ```rust,ignore +/// #[derive(serde::Deserialize)] +/// struct Data { +/// field1: String, +/// field2: u64 +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct User { +/// id: i32, +/// name: String, +/// #[sqlx(json(nullable))] +/// metadata: Option +/// } +/// ``` +/// Would describe a database field which _is_ NULLable but if it exists it must be the JSON representation of `Data` +/// and cannot be the JSON value `null` +/// +/// ## Manual implementation +/// +/// You can also implement the [`FromRow`] trait by hand. This can be useful if you +/// have a struct with a field that needs manual decoding: +/// +/// +/// ```rust,ignore +/// use sqlx::{FromRow, sqlite::SqliteRow, sqlx::Row}; +/// struct MyCustomType { +/// custom: String, +/// } +/// +/// struct Foo { +/// bar: MyCustomType, +/// } +/// +/// impl FromRow<'_, SqliteRow> for Foo { +/// fn from_row(row: &SqliteRow) -> sqlx::Result { +/// Ok(Self { +/// bar: MyCustomType { +/// custom: row.try_get("custom")? +/// } +/// }) +/// } +/// } +/// ``` +pub trait FromRow<'r, R: Row>: Sized { + fn from_row(row: &'r R) -> Result; +} + +impl<'r, R> FromRow<'r, R> for () +where + R: Row, +{ + #[inline] + fn from_row(_: &'r R) -> Result { + Ok(()) + } +} + +// implement FromRow for tuples of types that implement Decode +// up to tuples of 16 values + +macro_rules! impl_from_row_for_tuple { + ($( ($idx:tt) -> $T:ident );+;) => { + impl<'r, R, $($T,)+> FromRow<'r, R> for ($($T,)+) + where + R: Row, + usize: crate::column::ColumnIndex, + $($T: crate::decode::Decode<'r, R::Database> + crate::types::Type,)+ + { + #[inline] + fn from_row(row: &'r R) -> Result { + Ok(($(row.try_get($idx as usize)?,)+)) + } + } + }; +} + +impl_from_row_for_tuple!( + (0) -> T1; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; + (10) -> T11; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; + (10) -> T11; + (11) -> T12; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; + (10) -> T11; + (11) -> T12; + (12) -> T13; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; + (10) -> T11; + (11) -> T12; + (12) -> T13; + (13) -> T14; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; + (10) -> T11; + (11) -> T12; + (12) -> T13; + (13) -> T14; + (14) -> T15; +); + +impl_from_row_for_tuple!( + (0) -> T1; + (1) -> T2; + (2) -> T3; + (3) -> T4; + (4) -> T5; + (5) -> T6; + (6) -> T7; + (7) -> T8; + (8) -> T9; + (9) -> T10; + (10) -> T11; + (11) -> T12; + (12) -> T13; + (13) -> T14; + (14) -> T15; + (15) -> T16; +); diff --git a/vendor/sqlx-core/src/fs.rs b/vendor/sqlx-core/src/fs.rs new file mode 100755 index 0000000..0993cbe --- /dev/null +++ b/vendor/sqlx-core/src/fs.rs @@ -0,0 +1,96 @@ +use std::ffi::OsString; +use std::fs::Metadata; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::rt; + +pub struct ReadDir { + inner: Option, +} + +pub struct DirEntry { + pub path: PathBuf, + pub file_name: OsString, + pub metadata: Metadata, +} + +// Filesystem operations are generally not capable of being non-blocking +// so Tokio and async-std don't bother; they just send the work to a blocking thread pool. +// +// We save on code duplication here by just implementing the same strategy ourselves +// using the runtime's `spawn_blocking()` primitive. + +pub async fn read>(path: P) -> io::Result> { + let path = PathBuf::from(path.as_ref()); + rt::spawn_blocking(move || std::fs::read(path)).await +} + +pub async fn read_to_string>(path: P) -> io::Result { + let path = PathBuf::from(path.as_ref()); + rt::spawn_blocking(move || std::fs::read_to_string(path)).await +} + +pub async fn create_dir_all>(path: P) -> io::Result<()> { + let path = PathBuf::from(path.as_ref()); + rt::spawn_blocking(move || std::fs::create_dir_all(path)).await +} + +pub async fn remove_file>(path: P) -> io::Result<()> { + let path = PathBuf::from(path.as_ref()); + rt::spawn_blocking(move || std::fs::remove_file(path)).await +} + +pub async fn remove_dir>(path: P) -> io::Result<()> { + let path = PathBuf::from(path.as_ref()); + rt::spawn_blocking(move || std::fs::remove_dir(path)).await +} + +pub async fn remove_dir_all>(path: P) -> io::Result<()> { + let path = PathBuf::from(path.as_ref()); + rt::spawn_blocking(move || std::fs::remove_dir_all(path)).await +} + +pub async fn read_dir(path: PathBuf) -> io::Result { + let read_dir = rt::spawn_blocking(move || std::fs::read_dir(path)).await?; + + Ok(ReadDir { + inner: Some(read_dir), + }) +} + +impl ReadDir { + pub async fn next(&mut self) -> io::Result> { + if let Some(mut read_dir) = self.inner.take() { + let maybe = rt::spawn_blocking(move || { + let entry = read_dir.next().transpose()?; + + entry + .map(|entry| -> io::Result<_> { + Ok(( + read_dir, + DirEntry { + path: entry.path(), + file_name: entry.file_name(), + // We always want the metadata as well so might as well fetch + // it in the same blocking call. + metadata: entry.metadata()?, + }, + )) + }) + .transpose() + }) + .await?; + + match maybe { + Some((read_dir, entry)) => { + self.inner = Some(read_dir); + Ok(Some(entry)) + } + None => Ok(None), + } + } else { + Ok(None) + } + } +} diff --git a/vendor/sqlx-core/src/io/buf.rs b/vendor/sqlx-core/src/io/buf.rs new file mode 100755 index 0000000..2446ce6 --- /dev/null +++ b/vendor/sqlx-core/src/io/buf.rs @@ -0,0 +1,58 @@ +use std::str::from_utf8; + +use bytes::{Buf, Bytes}; +use memchr::memchr; + +use crate::error::Error; + +pub trait BufExt: Buf { + // Read a nul-terminated byte sequence + fn get_bytes_nul(&mut self) -> Result; + + // Read a byte sequence of the exact length + fn get_bytes(&mut self, len: usize) -> Bytes; + + // Read a nul-terminated string + fn get_str_nul(&mut self) -> Result; + + // Read a string of the exact length + fn get_str(&mut self, len: usize) -> Result; +} + +impl BufExt for Bytes { + fn get_bytes_nul(&mut self) -> Result { + let nul = + memchr(b'\0', self).ok_or_else(|| err_protocol!("expected NUL in byte sequence"))?; + + let v = self.slice(0..nul); + + self.advance(nul + 1); + + Ok(v) + } + + fn get_bytes(&mut self, len: usize) -> Bytes { + let v = self.slice(..len); + self.advance(len); + + v + } + + fn get_str_nul(&mut self) -> Result { + self.get_bytes_nul().and_then(|bytes| { + from_utf8(&bytes) + .map(ToOwned::to_owned) + .map_err(|err| err_protocol!("{}", err)) + }) + } + + fn get_str(&mut self, len: usize) -> Result { + let v = from_utf8(&self[..len]) + .map_err(|err| err_protocol!("{}", err)) + .map(ToOwned::to_owned)?; + + self.advance(len); + + Ok(v) + } +} diff --git a/vendor/sqlx-core/src/io/buf_mut.rs b/vendor/sqlx-core/src/io/buf_mut.rs new file mode 100755 index 0000000..565d850 --- /dev/null +++ b/vendor/sqlx-core/src/io/buf_mut.rs @@ -0,0 +1,12 @@ +use bytes::BufMut; + +pub trait BufMutExt: BufMut { + fn put_str_nul(&mut self, s: &str); +} + +impl BufMutExt for Vec { + fn put_str_nul(&mut self, s: &str) { + self.extend(s.as_bytes()); + self.push(0); + } +} diff --git a/vendor/sqlx-core/src/io/buf_stream.rs b/vendor/sqlx-core/src/io/buf_stream.rs new file mode 100755 index 0000000..a21cfe2 --- /dev/null +++ b/vendor/sqlx-core/src/io/buf_stream.rs @@ -0,0 +1,105 @@ +#![allow(dead_code)] + +use std::io; +use std::ops::{Deref, DerefMut}; + +use bytes::BytesMut; +use sqlx_rt::{AsyncRead, AsyncReadExt, AsyncWrite}; + +use crate::error::Error; +use crate::io::write_and_flush::WriteAndFlush; +use crate::io::{decode::Decode, encode::Encode}; +use std::io::Cursor; + +pub struct BufStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + pub(crate) stream: S, + + // writes with `write` to the underlying stream are buffered + // this can be flushed with `flush` + pub(crate) wbuf: Vec, + + // we read into the read buffer using 100% safe code + rbuf: BytesMut, +} + +impl BufStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + pub fn new(stream: S) -> Self { + Self { + stream, + wbuf: Vec::with_capacity(512), + rbuf: BytesMut::with_capacity(4096), + } + } + + pub fn write<'en, T>(&mut self, value: T) + where + T: Encode<'en, ()>, + { + self.write_with(value, ()) + } + + pub fn write_with<'en, T, C>(&mut self, value: T, context: C) + where + T: Encode<'en, C>, + { + value.encode_with(&mut self.wbuf, context); + } + + pub fn flush(&mut self) -> WriteAndFlush<'_, S> { + WriteAndFlush { + stream: &mut self.stream, + buf: Cursor::new(&mut self.wbuf), + } + } + + pub async fn read<'de, T>(&mut self, cnt: usize) -> Result + where + T: Decode<'de, ()>, + { + self.read_with(cnt, ()).await + } + + pub async fn read_with<'de, T, C>(&mut self, cnt: usize, context: C) -> Result + where + T: Decode<'de, C>, + { + T::decode_with(self.read_raw(cnt).await?.freeze(), context) + } + + pub async fn read_raw(&mut self, cnt: usize) -> Result { + read_raw_into(&mut self.stream, &mut self.rbuf, cnt).await?; + let buf = self.rbuf.split_to(cnt); + + Ok(buf) + } + + pub async fn read_raw_into(&mut self, buf: &mut BytesMut, cnt: usize) -> Result<(), Error> { + read_raw_into(&mut self.stream, buf, cnt).await + } +} + +impl Deref for BufStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + type Target = S; + + fn deref(&self) -> &Self::Target { + &self.stream + } +} + +impl DerefMut for BufStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.stream + } +} diff --git a/vendor/sqlx-core/src/io/decode.rs b/vendor/sqlx-core/src/io/decode.rs new file mode 100755 index 0000000..798fc8b --- /dev/null +++ b/vendor/sqlx-core/src/io/decode.rs @@ -0,0 +1,29 @@ +use bytes::Bytes; + +use crate::error::Error; + +pub trait ProtocolDecode<'de, Context = ()> +where + Self: Sized, +{ + fn decode(buf: Bytes) -> Result + where + Self: ProtocolDecode<'de, ()>, + { + Self::decode_with(buf, ()) + } + + fn decode_with(buf: Bytes, context: Context) -> Result; +} + +impl ProtocolDecode<'_> for Bytes { + fn decode_with(buf: Bytes, _: ()) -> Result { + Ok(buf) + } +} + +impl ProtocolDecode<'_> for () { + fn decode_with(_: Bytes, _: ()) -> Result<(), Error> { + Ok(()) + } +} diff --git a/vendor/sqlx-core/src/io/encode.rs b/vendor/sqlx-core/src/io/encode.rs new file mode 100755 index 0000000..ba032d2 --- /dev/null +++ b/vendor/sqlx-core/src/io/encode.rs @@ -0,0 +1,17 @@ +pub trait ProtocolEncode<'en, Context = ()> { + fn encode(&self, buf: &mut Vec) -> Result<(), crate::Error> + where + Self: ProtocolEncode<'en, ()>, + { + self.encode_with(buf, ()) + } + + fn encode_with(&self, buf: &mut Vec, context: Context) -> Result<(), crate::Error>; +} + +impl ProtocolEncode<'_, C> for &'_ [u8] { + fn encode_with(&self, buf: &mut Vec, _context: C) -> Result<(), crate::Error> { + buf.extend_from_slice(self); + Ok(()) + } +} diff --git a/vendor/sqlx-core/src/io/mod.rs b/vendor/sqlx-core/src/io/mod.rs new file mode 100755 index 0000000..2765abe --- /dev/null +++ b/vendor/sqlx-core/src/io/mod.rs @@ -0,0 +1,26 @@ +mod buf; +mod buf_mut; +// mod buf_stream; +mod decode; +mod encode; +mod read_buf; +// mod write_and_flush; + +pub use buf::BufExt; +pub use buf_mut::BufMutExt; +//pub use buf_stream::BufStream; +pub use decode::ProtocolDecode; +pub use encode::ProtocolEncode; +pub use read_buf::ReadBuf; + +#[cfg(not(feature = "_rt-tokio"))] +pub use futures_io::AsyncRead; + +#[cfg(feature = "_rt-tokio")] +pub use tokio::io::AsyncRead; + +#[cfg(not(feature = "_rt-tokio"))] +pub use futures_util::io::AsyncReadExt; + +#[cfg(feature = "_rt-tokio")] +pub use tokio::io::AsyncReadExt; diff --git a/vendor/sqlx-core/src/io/read_buf.rs b/vendor/sqlx-core/src/io/read_buf.rs new file mode 100755 index 0000000..c32f37b --- /dev/null +++ b/vendor/sqlx-core/src/io/read_buf.rs @@ -0,0 +1,35 @@ +use bytes::{BufMut, BytesMut}; + +/// An extension for [`BufMut`] for getting a writeable buffer in safe code. +pub trait ReadBuf: BufMut { + /// Get the full capacity of this buffer as a safely initialized slice. + fn init_mut(&mut self) -> &mut [u8]; +} + +impl ReadBuf for &'_ mut [u8] { + #[inline(always)] + fn init_mut(&mut self) -> &mut [u8] { + self + } +} + +impl ReadBuf for BytesMut { + #[inline(always)] + fn init_mut(&mut self) -> &mut [u8] { + // `self.remaining_mut()` returns `usize::MAX - self.len()` + let remaining = self.capacity() - self.len(); + + // I'm hoping for most uses that this operation is elided by the optimizer. + self.put_bytes(0, remaining); + + self + } +} + +#[test] +fn test_read_buf_bytes_mut() { + let mut buf = BytesMut::with_capacity(8); + buf.put_u32(0x12345678); + + assert_eq!(buf.init_mut(), [0x12, 0x34, 0x56, 0x78, 0, 0, 0, 0]); +} diff --git a/vendor/sqlx-core/src/io/write_and_flush.rs b/vendor/sqlx-core/src/io/write_and_flush.rs new file mode 100755 index 0000000..8a0db31 --- /dev/null +++ b/vendor/sqlx-core/src/io/write_and_flush.rs @@ -0,0 +1,44 @@ +use crate::error::Error; +use sqlx_rt::AsyncWrite; +use std::future::Future; +use std::io::{BufRead, Cursor}; +use std::pin::Pin; +use std::task::{ready, Context, Poll}; + +// Atomic operation that writes the full buffer to the stream, flushes the stream, and then +// clears the buffer (even if either of the two previous operations failed). +pub struct WriteAndFlush<'a, S> { + pub(super) stream: &'a mut S, + pub(super) buf: Cursor<&'a mut Vec>, +} + +impl Future for WriteAndFlush<'_, S> { + type Output = Result<(), Error>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let Self { + ref mut stream, + ref mut buf, + } = *self; + + loop { + let read = buf.fill_buf()?; + + if !read.is_empty() { + let written = ready!(Pin::new(&mut *stream).poll_write(cx, read)?); + buf.consume(written); + } else { + break; + } + } + + Pin::new(stream).poll_flush(cx).map_err(Error::Io) + } +} + +impl<'a, S> Drop for WriteAndFlush<'a, S> { + fn drop(&mut self) { + // clear the buffer regardless of whether the flush succeeded or not + self.buf.get_mut().clear(); + } +} diff --git a/vendor/sqlx-core/src/lib.rs b/vendor/sqlx-core/src/lib.rs new file mode 100755 index 0000000..494c41e --- /dev/null +++ b/vendor/sqlx-core/src/lib.rs @@ -0,0 +1,122 @@ +//! Core of SQLx, the rust SQL toolkit. +//! +//! ### Note: Semver Exempt API +//! The API of this crate is not meant for general use and does *not* follow Semantic Versioning. +//! The only crate that follows Semantic Versioning in the project is the `sqlx` crate itself. +//! If you are building a custom SQLx driver, you should pin an exact version for `sqlx-core` to +//! avoid breakages: +//! +//! ```toml +//! sqlx-core = { version = "=0.6.2" } +//! ``` +//! +//! And then make releases in lockstep with `sqlx-core`. We recommend all driver crates, in-tree +//! or otherwise, use the same version numbers as `sqlx-core` to avoid confusion. +#![recursion_limit = "512"] +#![warn(future_incompatible, rust_2018_idioms)] +#![allow(clippy::needless_doctest_main, clippy::type_complexity)] +// The only unsafe code in SQLx is that necessary to interact with native APIs like with SQLite, +// and that can live in its own separate driver crate. +#![forbid(unsafe_code)] +// Allows an API be documented as only available in some specific platforms. +// +#![cfg_attr(docsrs, feature(doc_cfg))] + +#[macro_use] +pub mod ext; + +#[macro_use] +pub mod error; + +#[macro_use] +pub mod arguments; + +#[macro_use] +pub mod pool; + +pub mod connection; + +#[macro_use] +pub mod transaction; + +#[macro_use] +pub mod encode; + +#[macro_use] +pub mod decode; + +#[macro_use] +pub mod types; + +#[macro_use] +pub mod query; + +#[macro_use] +pub mod acquire; + +#[macro_use] +pub mod column; + +#[macro_use] +pub mod statement; + +pub mod common; +pub mod database; +pub mod describe; +pub mod executor; +pub mod from_row; +pub mod fs; +pub mod io; +pub mod logger; +pub mod net; +pub mod query_as; +pub mod query_builder; +pub mod query_scalar; +pub mod sql_str; + +pub mod raw_sql; +pub mod row; +pub mod rt; +pub mod sync; +pub mod type_checking; +pub mod type_info; +pub mod value; + +#[cfg(feature = "migrate")] +pub mod migrate; + +#[cfg(feature = "any")] +pub mod any; + +// Implements test support with automatic DB management. +#[cfg(feature = "migrate")] +pub mod testing; + +pub mod config; + +pub use error::{Error, Result}; + +pub use either::Either; +pub use hashbrown::{hash_map, HashMap}; +pub use indexmap::IndexMap; +pub use percent_encoding; +pub use smallvec::SmallVec; +pub use url::{self, Url}; + +pub use bytes; + +/// Helper module to get drivers compiling again that used to be in this crate, +/// to avoid having to replace tons of `use crate::<...>` imports. +/// +/// This module can be glob-imported and should not clash with any modules a driver +/// would want to implement itself. +pub mod driver_prelude { + pub use crate::{ + acquire, common, decode, describe, encode, executor, ext, from_row, fs, io, logger, net, + pool, query, query_as, query_builder, query_scalar, rt, sync, + }; + + pub use crate::error::{Error, Result}; + pub use crate::{hash_map, HashMap}; + pub use either::Either; +} diff --git a/vendor/sqlx-core/src/logger.rs b/vendor/sqlx-core/src/logger.rs new file mode 100755 index 0000000..424639e --- /dev/null +++ b/vendor/sqlx-core/src/logger.rs @@ -0,0 +1,169 @@ +use crate::{connection::LogSettings, sql_str::SqlStr}; +use std::time::Instant; + +// Yes these look silly. `tracing` doesn't currently support dynamic levels +// https://github.com/tokio-rs/tracing/issues/372 +#[doc(hidden)] +#[macro_export] +macro_rules! private_tracing_dynamic_enabled { + (target: $target:expr, $level:expr) => {{ + use ::tracing::Level; + + match $level { + Level::ERROR => ::tracing::enabled!(target: $target, Level::ERROR), + Level::WARN => ::tracing::enabled!(target: $target, Level::WARN), + Level::INFO => ::tracing::enabled!(target: $target, Level::INFO), + Level::DEBUG => ::tracing::enabled!(target: $target, Level::DEBUG), + Level::TRACE => ::tracing::enabled!(target: $target, Level::TRACE), + } + }}; + ($level:expr) => {{ + $crate::private_tracing_dynamic_enabled!(target: module_path!(), $level) + }}; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! private_tracing_dynamic_event { + (target: $target:expr, $level:expr, $($args:tt)*) => {{ + use ::tracing::Level; + + match $level { + Level::ERROR => ::tracing::event!(target: $target, Level::ERROR, $($args)*), + Level::WARN => ::tracing::event!(target: $target, Level::WARN, $($args)*), + Level::INFO => ::tracing::event!(target: $target, Level::INFO, $($args)*), + Level::DEBUG => ::tracing::event!(target: $target, Level::DEBUG, $($args)*), + Level::TRACE => ::tracing::event!(target: $target, Level::TRACE, $($args)*), + } + }}; +} + +#[doc(hidden)] +pub fn private_level_filter_to_levels( + filter: log::LevelFilter, +) -> Option<(tracing::Level, log::Level)> { + let tracing_level = match filter { + log::LevelFilter::Error => Some(tracing::Level::ERROR), + log::LevelFilter::Warn => Some(tracing::Level::WARN), + log::LevelFilter::Info => Some(tracing::Level::INFO), + log::LevelFilter::Debug => Some(tracing::Level::DEBUG), + log::LevelFilter::Trace => Some(tracing::Level::TRACE), + log::LevelFilter::Off => None, + }; + + tracing_level.zip(filter.to_level()) +} + +pub(crate) fn private_level_filter_to_trace_level( + filter: log::LevelFilter, +) -> Option { + private_level_filter_to_levels(filter).map(|(level, _)| level) +} + +pub struct QueryLogger { + sql: SqlStr, + rows_returned: u64, + rows_affected: u64, + start: Instant, + settings: LogSettings, +} + +impl QueryLogger { + pub fn new(sql: SqlStr, settings: LogSettings) -> Self { + Self { + sql, + rows_returned: 0, + rows_affected: 0, + start: Instant::now(), + settings, + } + } + + pub fn increment_rows_returned(&mut self) { + self.rows_returned += 1; + } + + pub fn increase_rows_affected(&mut self, n: u64) { + self.rows_affected += n; + } + + pub fn sql(&self) -> &SqlStr { + &self.sql + } + + pub fn finish(&self) { + let elapsed = self.start.elapsed(); + + let was_slow = elapsed >= self.settings.slow_statements_duration; + + let lvl = if was_slow { + self.settings.slow_statements_level + } else { + self.settings.statements_level + }; + + if let Some((tracing_level, log_level)) = private_level_filter_to_levels(lvl) { + // The enabled level could be set from either tracing world or log world, so check both + // to see if logging should be enabled for our level + let log_is_enabled = log::log_enabled!(target: "sqlx::query", log_level) + || private_tracing_dynamic_enabled!(target: "sqlx::query", tracing_level); + if log_is_enabled { + let mut summary = parse_query_summary(self.sql.as_str()); + + let sql = if summary != self.sql.as_str() { + summary.push_str(" …"); + format!("\n\n{}\n", self.sql.as_str()) + } else { + String::new() + }; + + if was_slow { + private_tracing_dynamic_event!( + target: "sqlx::query", + tracing_level, + summary, + db.statement = sql, + rows_affected = self.rows_affected, + rows_returned = self.rows_returned, + // Human-friendly - includes units (usually ms). Also kept for backward compatibility + ?elapsed, + // Search friendly - numeric + elapsed_secs = elapsed.as_secs_f64(), + // When logging to JSON, one can trigger alerts from the presence of this field. + slow_threshold=?self.settings.slow_statements_duration, + // Make sure to use "slow" in the message as that's likely + // what people will grep for. + "slow statement: execution time exceeded alert threshold" + ); + } else { + private_tracing_dynamic_event!( + target: "sqlx::query", + tracing_level, + summary, + db.statement = sql, + rows_affected = self.rows_affected, + rows_returned = self.rows_returned, + // Human-friendly - includes units (usually ms). Also kept for backward compatibility + ?elapsed, + // Search friendly - numeric + elapsed_secs = elapsed.as_secs_f64(), + ); + } + } + } + } +} + +impl Drop for QueryLogger { + fn drop(&mut self) { + self.finish(); + } +} + +pub fn parse_query_summary(sql: &str) -> String { + // For now, just take the first 4 words + sql.split_whitespace() + .take(4) + .collect::>() + .join(" ") +} diff --git a/vendor/sqlx-core/src/migrate/error.rs b/vendor/sqlx-core/src/migrate/error.rs new file mode 100755 index 0000000..3c08f57 --- /dev/null +++ b/vendor/sqlx-core/src/migrate/error.rs @@ -0,0 +1,48 @@ +use crate::error::{BoxDynError, Error}; + +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum MigrateError { + #[error("while executing migrations: {0}")] + Execute(#[from] Error), + + #[error("while executing migration {1}: {0}")] + ExecuteMigration(#[source] Error, i64), + + #[error("while resolving migrations: {0}")] + Source(#[source] BoxDynError), + + #[error("migration {0} was previously applied but is missing in the resolved migrations")] + VersionMissing(i64), + + #[error("migration {0} was previously applied but has been modified")] + VersionMismatch(i64), + + #[error("migration {0} is not present in the migration source")] + VersionNotPresent(i64), + + #[error("migration {0} is older than the latest applied migration {1}")] + VersionTooOld(i64, i64), + + #[error("migration {0} is newer than the latest applied migration {1}")] + VersionTooNew(i64, i64), + + #[error("database driver does not support force-dropping a database (Only PostgreSQL)")] + ForceNotSupported, + + #[deprecated = "migration types are now inferred"] + #[error("cannot mix reversible migrations with simple migrations. All migrations should be reversible or simple migrations")] + InvalidMixReversibleAndSimple, + + // NOTE: this will only happen with a database that does not have transactional DDL (.e.g, MySQL or Oracle) + #[error( + "migration {0} is partially applied; fix and remove row from `_sqlx_migrations` table" + )] + Dirty(i64), + + #[error("database driver does not support creation of schemas at migrate time: {0}")] + CreateSchemasNotSupported(String), + + #[error("database driver does not support skipping migrations")] + SkipNotSupported(), +} diff --git a/vendor/sqlx-core/src/migrate/migrate.rs b/vendor/sqlx-core/src/migrate/migrate.rs new file mode 100755 index 0000000..de4bbc5 --- /dev/null +++ b/vendor/sqlx-core/src/migrate/migrate.rs @@ -0,0 +1,90 @@ +use crate::error::Error; +use crate::migrate::{AppliedMigration, MigrateError, Migration}; +use futures_core::future::BoxFuture; +use std::future::Future; +use std::time::Duration; + +pub trait MigrateDatabase { + // create database in url + // uses a maintenance database depending on driver + fn create_database(url: &str) -> impl Future> + Send + '_; + + // check if the database in url exists + // uses a maintenance database depending on driver + fn database_exists(url: &str) -> impl Future> + Send + '_; + + // drop database in url + // uses a maintenance database depending on driver + fn drop_database(url: &str) -> impl Future> + Send + '_; + + // force drop database in url + // uses a maintenance database depending on driver + fn force_drop_database(_url: &str) -> impl Future> + Send + '_ { + async { Err(MigrateError::ForceNotSupported)? } + } +} + +// 'e = Executor +pub trait Migrate { + /// Create a database schema with the given name if it does not already exist. + fn create_schema_if_not_exists<'e>( + &'e mut self, + schema_name: &'e str, + ) -> BoxFuture<'e, Result<(), MigrateError>>; + + // ensure migrations table exists + // will create or migrate it if needed + fn ensure_migrations_table<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result<(), MigrateError>>; + + // Return the version on which the database is dirty or None otherwise. + // "dirty" means there is a partially applied migration that failed. + fn dirty_version<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result, MigrateError>>; + + // Return the ordered list of applied migrations + fn list_applied_migrations<'e>( + &'e mut self, + table_name: &'e str, + ) -> BoxFuture<'e, Result, MigrateError>>; + + // Should acquire a database lock so that only one migration process + // can run at a time. [`Migrate`] will call this function before applying + // any migrations. + fn lock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>>; + + // Should release the lock. [`Migrate`] will call this function after all + // migrations have been run. + fn unlock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>>; + + // run SQL from migration in a DDL transaction + // insert new row to [_migrations] table on completion (success or failure) + // returns the time taking to run the migration SQL + fn apply<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result>; + + // run a revert SQL from migration in a DDL transaction + // deletes the row in [_migrations] table with specified migration version on completion (success or failure) + // returns the time taking to run the migration SQL + fn revert<'e>( + &'e mut self, + table_name: &'e str, + migration: &'e Migration, + ) -> BoxFuture<'e, Result>; + + // insert new row to [_migrations] table without running SQL from migration + fn skip<'e>( + &'e mut self, + _table_name: &'e str, + _migration: &'e Migration, + ) -> BoxFuture<'e, Result<(), MigrateError>> { + Box::pin(async move { Err(MigrateError::SkipNotSupported()) }) + } +} diff --git a/vendor/sqlx-core/src/migrate/migration.rs b/vendor/sqlx-core/src/migrate/migration.rs new file mode 100755 index 0000000..878139f --- /dev/null +++ b/vendor/sqlx-core/src/migrate/migration.rs @@ -0,0 +1,120 @@ +use sha2::{Digest, Sha384}; +use std::borrow::Cow; +use std::cmp::Ordering; + +use crate::sql_str::SqlStr; + +use super::MigrationType; + +#[derive(Debug, Clone)] +pub struct Migration { + pub version: i64, + pub description: Cow<'static, str>, + pub migration_type: MigrationType, + pub sql: SqlStr, + pub checksum: Cow<'static, [u8]>, + pub no_tx: bool, +} + +impl PartialEq for Migration { + fn eq(&self, other: &Self) -> bool { + self.version == other.version && self.migration_type == other.migration_type + } +} + +impl Eq for Migration {} + +impl PartialOrd for Migration { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Migration { + fn cmp(&self, other: &Self) -> Ordering { + self.version + .cmp(&other.version) + .then_with(|| self.migration_type.cmp(&other.migration_type)) + } +} + +impl Migration { + pub fn new( + version: i64, + description: Cow<'static, str>, + migration_type: MigrationType, + sql: SqlStr, + no_tx: bool, + ) -> Self { + let checksum = checksum(sql.as_str()); + + Self::with_checksum( + version, + description, + migration_type, + sql, + checksum.into(), + no_tx, + ) + } + + pub(crate) fn with_checksum( + version: i64, + description: Cow<'static, str>, + migration_type: MigrationType, + sql: SqlStr, + checksum: Cow<'static, [u8]>, + no_tx: bool, + ) -> Self { + Migration { + version, + description, + migration_type, + sql, + checksum, + no_tx, + } + } +} + +#[derive(Debug, Clone)] +pub struct AppliedMigration { + pub version: i64, + pub checksum: Cow<'static, [u8]>, +} + +pub fn checksum(sql: &str) -> Vec { + Sha384::digest(sql).to_vec() +} + +pub fn checksum_fragments<'a>(fragments: impl Iterator) -> Vec { + let mut digest = Sha384::new(); + + for fragment in fragments { + digest.update(fragment); + } + + digest.finalize().to_vec() +} + +#[test] +fn fragments_checksum_equals_full_checksum() { + // Copied from `examples/postgres/axum-social-with-tests/migrations/3_comment.sql` + let sql = "\ + \u{FEFF}create table comment (\r\n\ + \tcomment_id uuid primary key default gen_random_uuid(),\r\n\ + \tpost_id uuid not null references post(post_id),\r\n\ + \tuser_id uuid not null references \"user\"(user_id),\r\n\ + \tcontent text not null,\r\n\ + \tcreated_at timestamptz not null default now()\r\n\ + );\r\n\ + \r\n\ + create index on comment(post_id, created_at);\r\n\ + "; + + // Should yield a string for each character + let fragments_checksum = checksum_fragments(sql.split("")); + let full_checksum = checksum(sql); + + assert_eq!(fragments_checksum, full_checksum); +} diff --git a/vendor/sqlx-core/src/migrate/migration_type.rs b/vendor/sqlx-core/src/migrate/migration_type.rs new file mode 100755 index 0000000..107cdd2 --- /dev/null +++ b/vendor/sqlx-core/src/migrate/migration_type.rs @@ -0,0 +1,90 @@ +use super::Migrator; + +/// Migration Type represents the type of migration +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum MigrationType { + /// Simple migration are single file migrations with no up / down queries + Simple, + + /// ReversibleUp migrations represents the add or update part of a reversible migrations + /// It is expected the every migration of this type will have a corresponding down file + ReversibleUp, + + /// ReversibleDown migrations represents the delete or downgrade part of a reversible migrations + /// It is expected the every migration of this type will have a corresponding up file + ReversibleDown, +} + +impl MigrationType { + pub fn from_filename(filename: &str) -> Self { + if filename.ends_with(MigrationType::ReversibleUp.suffix()) { + MigrationType::ReversibleUp + } else if filename.ends_with(MigrationType::ReversibleDown.suffix()) { + MigrationType::ReversibleDown + } else { + MigrationType::Simple + } + } + + pub fn is_reversible(&self) -> bool { + match self { + MigrationType::Simple => false, + MigrationType::ReversibleUp => true, + MigrationType::ReversibleDown => true, + } + } + + pub fn is_up_migration(&self) -> bool { + match self { + MigrationType::Simple => true, + MigrationType::ReversibleUp => true, + MigrationType::ReversibleDown => false, + } + } + + pub fn is_down_migration(&self) -> bool { + match self { + MigrationType::Simple => false, + MigrationType::ReversibleUp => false, + MigrationType::ReversibleDown => true, + } + } + + pub fn label(&self) -> &'static str { + match self { + MigrationType::Simple => "migrate", + MigrationType::ReversibleUp => "migrate", + MigrationType::ReversibleDown => "revert", + } + } + + pub fn suffix(&self) -> &'static str { + match self { + MigrationType::Simple => ".sql", + MigrationType::ReversibleUp => ".up.sql", + MigrationType::ReversibleDown => ".down.sql", + } + } + + pub fn file_content(&self) -> &'static str { + match self { + MigrationType::Simple => "-- Add migration script here\n", + MigrationType::ReversibleUp => "-- Add up migration script here\n", + MigrationType::ReversibleDown => "-- Add down migration script here\n", + } + } + + #[deprecated = "unused"] + pub fn infer(migrator: &Migrator, reversible: bool) -> MigrationType { + match migrator.iter().last() { + Some(first_migration) => first_migration.migration_type, + None => { + if reversible { + MigrationType::ReversibleUp + } else { + MigrationType::Simple + } + } + } + } +} diff --git a/vendor/sqlx-core/src/migrate/migrator.rs b/vendor/sqlx-core/src/migrate/migrator.rs new file mode 100755 index 0000000..c64b0f2 --- /dev/null +++ b/vendor/sqlx-core/src/migrate/migrator.rs @@ -0,0 +1,380 @@ +use crate::acquire::Acquire; +use crate::migrate::{AppliedMigration, Migrate, MigrateError, Migration, MigrationSource}; +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; +use std::ops::Deref; +use std::slice; + +/// A resolved set of migrations, ready to be run. +/// +/// Can be constructed statically using `migrate!()` or at runtime using [`Migrator::new()`]. +#[derive(Debug)] +// Forbids `migrate!()` from constructing this: +// #[non_exhaustive] +pub struct Migrator { + // NOTE: these fields are semver-exempt and may be changed or removed in any future version. + // These have to be public for `migrate!()` to be able to initialize them in an implicitly + // const-promotable context. A `const fn` constructor isn't implicitly const-promotable. + #[doc(hidden)] + pub migrations: Cow<'static, [Migration]>, + #[doc(hidden)] + pub ignore_missing: bool, + #[doc(hidden)] + pub locking: bool, + #[doc(hidden)] + pub no_tx: bool, + #[doc(hidden)] + pub table_name: Cow<'static, str>, + + #[doc(hidden)] + pub create_schemas: Cow<'static, [Cow<'static, str>]>, +} + +impl Migrator { + #[doc(hidden)] + pub const DEFAULT: Migrator = Migrator { + migrations: Cow::Borrowed(&[]), + ignore_missing: false, + no_tx: false, + locking: true, + table_name: Cow::Borrowed("_sqlx_migrations"), + create_schemas: Cow::Borrowed(&[]), + }; + + /// Creates a new instance with the given source. + /// + /// # Examples + /// + /// ```rust,no_run + /// # use sqlx_core::migrate::MigrateError; + /// # fn main() -> Result<(), MigrateError> { + /// # sqlx::__rt::test_block_on(async move { + /// # use sqlx_core::migrate::Migrator; + /// use std::path::Path; + /// + /// // Read migrations from a local folder: ./migrations + /// let m = Migrator::new(Path::new("./migrations")).await?; + /// # Ok(()) + /// # }) + /// # } + /// ``` + /// See [MigrationSource] for details on structure of the `./migrations` directory. + pub async fn new<'s, S>(source: S) -> Result + where + S: MigrationSource<'s>, + { + Ok(Self { + migrations: Cow::Owned(source.resolve().await.map_err(MigrateError::Source)?), + ..Self::DEFAULT + }) + } + + /// Creates a new instance with the given migrations. + /// + /// + /// # Examples + /// + /// ```rust,no_run + /// use sqlx::{ SqlSafeStr, migrate::{Migration, MigrationType::*, Migrator}}; + /// + /// // Define your migrations. + /// // You can also use include_str!("./xxx.sql") instead of hard-coded SQL statements. + /// let migrations = vec![ + /// Migration::new(1, "user".into(), ReversibleUp, "create table users ( ... )".into_sql_str(), false), + /// Migration::new(2, "post".into(), ReversibleUp, "create table posts ( ... )".into_sql_str(), false), + /// // add more... + /// ]; + /// let m = Migrator::with_migrations(migrations); + /// ``` + pub fn with_migrations(mut migrations: Vec) -> Self { + migrations.sort(); + Self { + migrations: Cow::Owned(migrations), + ..Self::DEFAULT + } + } + + /// Override the name of the table used to track executed migrations. + /// + /// May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`. + /// + /// Potentially useful for multi-tenant databases. + /// + /// ### Warning: Potential Data Loss or Corruption! + /// Changing this option for a production database will likely result in data loss or corruption + /// as the migration machinery will no longer be aware of what migrations have been applied + /// and will attempt to re-run them. + /// + /// You should create the new table as a copy of the existing migrations table (with contents!), + /// and be sure all instances of your application have been migrated to the new + /// table before deleting the old one. + pub fn dangerous_set_table_name(&mut self, table_name: impl Into>) -> &Self { + self.table_name = table_name.into(); + self + } + + /// Add a schema name to be created if it does not already exist. + /// + /// May be used with [`Self::dangerous_set_table_name()`] to place the migrations table + /// in a new schema without requiring it to exist first. + /// + /// ### Note: Support Depends on Database + /// SQLite cannot create new schemas without attaching them to a database file, + /// the path of which must be specified separately in an [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) command. + pub fn create_schema(&mut self, schema_name: impl Into>) -> &Self { + self.create_schemas.to_mut().push(schema_name.into()); + self + } + + /// Specify whether applied migrations that are missing from the resolved migrations should be ignored. + pub fn set_ignore_missing(&mut self, ignore_missing: bool) -> &mut Self { + self.ignore_missing = ignore_missing; + self + } + + /// Specify whether or not to lock the database during migration. Defaults to `true`. + /// + /// ### Warning + /// Disabling locking can lead to errors or data loss if multiple clients attempt to apply migrations simultaneously + /// without some sort of mutual exclusion. + /// + /// This should only be used if the database does not support locking, e.g. CockroachDB which talks the Postgres + /// protocol but does not support advisory locks used by SQLx's migrations support for Postgres. + pub fn set_locking(&mut self, locking: bool) -> &mut Self { + self.locking = locking; + self + } + + /// Get an iterator over all known migrations. + pub fn iter(&self) -> slice::Iter<'_, Migration> { + self.migrations.iter() + } + + /// Check if a migration version exists. + pub fn version_exists(&self, version: i64) -> bool { + self.iter().any(|m| m.version == version) + } + + /// Run any pending migrations against the database; and, validate previously applied migrations + /// against the current migration source to detect accidental changes in previously-applied migrations. + /// + /// # Examples + /// + /// ```rust,no_run + /// # use sqlx::migrate::MigrateError; + /// # fn main() -> Result<(), MigrateError> { + /// # sqlx::__rt::test_block_on(async move { + /// use sqlx::migrate::Migrator; + /// use sqlx::sqlite::SqlitePoolOptions; + /// + /// let m = Migrator::new(std::path::Path::new("./migrations")).await?; + /// let pool = SqlitePoolOptions::new().connect("sqlite::memory:").await?; + /// m.run(&pool).await + /// # }) + /// # } + /// ``` + pub async fn run<'a, A>(&self, migrator: A) -> Result<(), MigrateError> + where + A: Acquire<'a>, + ::Target: Migrate, + { + let mut conn = migrator.acquire().await?; + self.run_direct(None, &mut *conn, false).await + } + + pub async fn run_to<'a, A>(&self, target: i64, migrator: A) -> Result<(), MigrateError> + where + A: Acquire<'a>, + ::Target: Migrate, + { + let mut conn = migrator.acquire().await?; + self.run_direct(Some(target), &mut *conn, false).await + } + + /// Skip any pending migrations until a specific version against the database; + /// Additionally validate previously applied migrations against the current migration + /// source to detect accidental changes in previously-applied migrations. + /// + /// Skipping entails not executing the SQL of the migrations, but marking them as + /// applied in the [_migrations] table. + /// + /// # Examples + /// + /// ```rust,no_run + /// # use sqlx::migrate::MigrateError; + /// # fn main() -> Result<(), MigrateError> { + /// # sqlx::__rt::test_block_on(async move { + /// use sqlx::migrate::Migrator; + /// use sqlx::sqlite::SqlitePoolOptions; + /// + /// let m = Migrator::new(std::path::Path::new("./migrations")).await?; + /// let pool = SqlitePoolOptions::new().connect("sqlite::memory:").await?; + /// m.skip(&pool, Some(17)).await + /// # }) + /// # } + /// ``` + pub async fn skip<'a, A>(&self, migrator: A, target: Option) -> Result<(), MigrateError> + where + A: Acquire<'a>, + ::Target: Migrate, + { + let mut conn = migrator.acquire().await?; + self.run_direct(target, &mut *conn, true).await + } + + // Getting around the annoying "implementation of `Acquire` is not general enough" error + #[doc(hidden)] + pub async fn run_direct( + &self, + target: Option, + conn: &mut C, + skip: bool, + ) -> Result<(), MigrateError> + where + C: Migrate, + { + // lock the database for exclusive access by the migrator + if self.locking { + conn.lock().await?; + } + + for schema_name in self.create_schemas.iter() { + conn.create_schema_if_not_exists(schema_name).await?; + } + + // creates [_migrations] table only if needed + // eventually this will likely migrate previous versions of the table + conn.ensure_migrations_table(&self.table_name).await?; + + let version = conn.dirty_version(&self.table_name).await?; + if let Some(version) = version { + return Err(MigrateError::Dirty(version)); + } + + let applied_migrations = conn.list_applied_migrations(&self.table_name).await?; + validate_applied_migrations(&applied_migrations, self)?; + + let applied_migrations: HashMap<_, _> = applied_migrations + .into_iter() + .map(|m| (m.version, m)) + .collect(); + + for migration in self.iter() { + if target.is_some_and(|target| target < migration.version) { + // Target version reached + break; + } + + if migration.migration_type.is_down_migration() { + continue; + } + + match applied_migrations.get(&migration.version) { + Some(applied_migration) => { + if migration.checksum != applied_migration.checksum { + return Err(MigrateError::VersionMismatch(migration.version)); + } + } + None => { + if skip { + conn.skip(&self.table_name, migration).await?; + } else { + conn.apply(&self.table_name, migration).await?; + } + } + } + } + + // unlock the migrator to allow other migrators to run + // but do nothing as we already migrated + if self.locking { + conn.unlock().await?; + } + + Ok(()) + } + + /// Run down migrations against the database until a specific version. + /// + /// # Examples + /// + /// ```rust,no_run + /// # use sqlx::migrate::MigrateError; + /// # fn main() -> Result<(), MigrateError> { + /// # sqlx::__rt::test_block_on(async move { + /// use sqlx::migrate::Migrator; + /// use sqlx::sqlite::SqlitePoolOptions; + /// + /// let m = Migrator::new(std::path::Path::new("./migrations")).await?; + /// let pool = SqlitePoolOptions::new().connect("sqlite::memory:").await?; + /// m.undo(&pool, 4).await + /// # }) + /// # } + /// ``` + pub async fn undo<'a, A>(&self, migrator: A, target: i64) -> Result<(), MigrateError> + where + A: Acquire<'a>, + ::Target: Migrate, + { + let mut conn = migrator.acquire().await?; + + // lock the database for exclusive access by the migrator + if self.locking { + conn.lock().await?; + } + + // creates [_migrations] table only if needed + // eventually this will likely migrate previous versions of the table + conn.ensure_migrations_table(&self.table_name).await?; + + let version = conn.dirty_version(&self.table_name).await?; + if let Some(version) = version { + return Err(MigrateError::Dirty(version)); + } + + let applied_migrations = conn.list_applied_migrations(&self.table_name).await?; + validate_applied_migrations(&applied_migrations, self)?; + + let applied_migrations: HashMap<_, _> = applied_migrations + .into_iter() + .map(|m| (m.version, m)) + .collect(); + + for migration in self + .iter() + .rev() + .filter(|m| m.migration_type.is_down_migration()) + .filter(|m| applied_migrations.contains_key(&m.version)) + .filter(|m| m.version > target) + { + conn.revert(&self.table_name, migration).await?; + } + + // unlock the migrator to allow other migrators to run + // but do nothing as we already migrated + if self.locking { + conn.unlock().await?; + } + + Ok(()) + } +} + +fn validate_applied_migrations( + applied_migrations: &[AppliedMigration], + migrator: &Migrator, +) -> Result<(), MigrateError> { + if migrator.ignore_missing { + return Ok(()); + } + + let migrations: HashSet<_> = migrator.iter().map(|m| m.version).collect(); + + for applied_migration in applied_migrations { + if !migrations.contains(&applied_migration.version) { + return Err(MigrateError::VersionMissing(applied_migration.version)); + } + } + + Ok(()) +} diff --git a/vendor/sqlx-core/src/migrate/mod.rs b/vendor/sqlx-core/src/migrate/mod.rs new file mode 100755 index 0000000..39347cf --- /dev/null +++ b/vendor/sqlx-core/src/migrate/mod.rs @@ -0,0 +1,17 @@ +mod error; +#[allow(clippy::module_inception)] +mod migrate; +mod migration; +mod migration_type; +mod migrator; +mod source; + +pub use error::MigrateError; +pub use migrate::{Migrate, MigrateDatabase}; +pub use migration::{AppliedMigration, Migration}; +pub use migration_type::MigrationType; +pub use migrator::Migrator; +pub use source::{MigrationSource, ResolveConfig, ResolveWith}; + +#[doc(hidden)] +pub use source::{resolve_blocking, resolve_blocking_with_config}; diff --git a/vendor/sqlx-core/src/migrate/source.rs b/vendor/sqlx-core/src/migrate/source.rs new file mode 100755 index 0000000..10fc7c7 --- /dev/null +++ b/vendor/sqlx-core/src/migrate/source.rs @@ -0,0 +1,298 @@ +use crate::error::BoxDynError; +use crate::migrate::{migration, Migration, MigrationType}; +use crate::sql_str::{AssertSqlSafe, SqlSafeStr}; +use futures_core::future::BoxFuture; + +use std::borrow::Cow; +use std::collections::BTreeSet; +use std::fmt::Debug; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +/// In the default implementation, a MigrationSource is a directory which +/// contains the migration SQL scripts. All these scripts must be stored in +/// files with names using the format `_.sql`, where +/// `` is a string that can be parsed into `i64` and its value is +/// greater than zero, and `` is a string. +/// +/// Files that don't match this format are silently ignored. +/// +/// You can create a new empty migration script using sqlx-cli: +/// `sqlx migrate add `. +/// +/// Note that migrations for each database are tracked using the +/// `_sqlx_migrations` table (stored in the database). If a migration's hash +/// changes and it has already been run, this will cause an error. +pub trait MigrationSource<'s>: Debug { + fn resolve(self) -> BoxFuture<'s, Result, BoxDynError>>; +} + +impl<'s> MigrationSource<'s> for &'s Path { + fn resolve(self) -> BoxFuture<'s, Result, BoxDynError>> { + // Behavior changed from previous because `canonicalize()` is potentially blocking + // since it might require going to disk to fetch filesystem data. + self.to_owned().resolve() + } +} + +impl MigrationSource<'static> for PathBuf { + fn resolve(self) -> BoxFuture<'static, Result, BoxDynError>> { + // Technically this could just be `Box::pin(spawn_blocking(...))` + // but that would actually be a breaking behavior change because it would call + // `spawn_blocking()` on the current thread + Box::pin(async move { + crate::rt::spawn_blocking(move || { + let migrations_with_paths = resolve_blocking(&self)?; + + Ok(migrations_with_paths.into_iter().map(|(m, _p)| m).collect()) + }) + .await + }) + } +} + +/// A [`MigrationSource`] implementation with configurable resolution. +/// +/// `S` may be `PathBuf`, `&Path` or any type that implements `Into`. +/// +/// See [`ResolveConfig`] for details. +#[derive(Debug)] +pub struct ResolveWith(pub S, pub ResolveConfig); + +impl<'s, S: Debug + Into + Send + 's> MigrationSource<'s> for ResolveWith { + fn resolve(self) -> BoxFuture<'s, Result, BoxDynError>> { + Box::pin(async move { + let path = self.0.into(); + let config = self.1; + + let migrations_with_paths = + crate::rt::spawn_blocking(move || resolve_blocking_with_config(&path, &config)) + .await?; + + Ok(migrations_with_paths.into_iter().map(|(m, _p)| m).collect()) + }) + } +} + +#[derive(thiserror::Error, Debug)] +#[error("{message}")] +pub struct ResolveError { + message: String, + #[source] + source: Option, +} + +/// Configuration for migration resolution using [`ResolveWith`]. +#[derive(Debug, Default)] +pub struct ResolveConfig { + ignored_chars: BTreeSet, +} + +impl ResolveConfig { + /// Return a default, empty configuration. + pub fn new() -> Self { + ResolveConfig { + ignored_chars: BTreeSet::new(), + } + } + + /// Ignore a character when hashing migrations. + /// + /// The migration SQL string itself will still contain the character, + /// but it will not be included when calculating the checksum. + /// + /// This can be used to ignore whitespace characters so changing formatting + /// does not change the checksum. + /// + /// Adding the same `char` more than once is a no-op. + /// + /// ### Note: Changes Migration Checksum + /// This will change the checksum of resolved migrations, + /// which may cause problems with existing deployments. + /// + /// **Use at your own risk.** + pub fn ignore_char(&mut self, c: char) -> &mut Self { + self.ignored_chars.insert(c); + self + } + + /// Ignore one or more characters when hashing migrations. + /// + /// The migration SQL string itself will still contain these characters, + /// but they will not be included when calculating the checksum. + /// + /// This can be used to ignore whitespace characters so changing formatting + /// does not change the checksum. + /// + /// Adding the same `char` more than once is a no-op. + /// + /// ### Note: Changes Migration Checksum + /// This will change the checksum of resolved migrations, + /// which may cause problems with existing deployments. + /// + /// **Use at your own risk.** + pub fn ignore_chars(&mut self, chars: impl IntoIterator) -> &mut Self { + self.ignored_chars.extend(chars); + self + } + + /// Iterate over the set of ignored characters. + /// + /// Duplicate `char`s are not included. + pub fn ignored_chars(&self) -> impl Iterator + '_ { + self.ignored_chars.iter().copied() + } +} + +// FIXME: paths should just be part of `Migration` but we can't add a field backwards compatibly +// since it's `#[non_exhaustive]`. +#[doc(hidden)] +pub fn resolve_blocking(path: &Path) -> Result, ResolveError> { + resolve_blocking_with_config(path, &ResolveConfig::new()) +} + +#[doc(hidden)] +pub fn resolve_blocking_with_config( + path: &Path, + config: &ResolveConfig, +) -> Result, ResolveError> { + let path = path.canonicalize().map_err(|e| ResolveError { + message: format!("error canonicalizing path {}", path.display()), + source: Some(e), + })?; + + let s = fs::read_dir(&path).map_err(|e| ResolveError { + message: format!("error reading migration directory {}", path.display()), + source: Some(e), + })?; + + let mut migrations = Vec::new(); + + for res in s { + let entry = res.map_err(|e| ResolveError { + message: format!( + "error reading contents of migration directory {}", + path.display() + ), + source: Some(e), + })?; + + let entry_path = entry.path(); + + let metadata = fs::metadata(&entry_path).map_err(|e| ResolveError { + message: format!( + "error getting metadata of migration path {}", + entry_path.display() + ), + source: Some(e), + })?; + + if !metadata.is_file() { + // not a file; ignore + continue; + } + + let file_name = entry.file_name(); + // This is arguably the wrong choice, + // but it really only matters for parsing the version and description. + // + // Using `.to_str()` and returning an error if the filename is not UTF-8 + // would be a breaking change. + let file_name = file_name.to_string_lossy(); + + let parts = file_name.splitn(2, '_').collect::>(); + + if parts.len() != 2 || !parts[1].ends_with(".sql") { + // not of the format: _..sql; ignore + continue; + } + + let version: i64 = parts[0].parse() + .map_err(|_e| ResolveError { + message: format!("error parsing migration filename {file_name:?}; expected integer version prefix (e.g. `01_foo.sql`)"), + source: None, + })?; + + let migration_type = MigrationType::from_filename(parts[1]); + + // remove the `.sql` and replace `_` with ` ` + let description = parts[1] + .trim_end_matches(migration_type.suffix()) + .replace('_', " ") + .to_owned(); + + let sql = fs::read_to_string(&entry_path).map_err(|e| ResolveError { + message: format!( + "error reading contents of migration {}: {e}", + entry_path.display() + ), + source: Some(e), + })?; + + // opt-out of migration transaction + let no_tx = sql.starts_with("-- no-transaction"); + + let checksum = checksum_with(&sql, &config.ignored_chars); + + migrations.push(( + Migration::with_checksum( + version, + Cow::Owned(description), + migration_type, + AssertSqlSafe(sql).into_sql_str(), + checksum.into(), + no_tx, + ), + entry_path, + )); + } + + migrations.sort(); + + Ok(migrations) +} + +fn checksum_with(sql: &str, ignored_chars: &BTreeSet) -> Vec { + if ignored_chars.is_empty() { + // This is going to be much faster because it doesn't have to UTF-8 decode `sql`. + return migration::checksum(sql); + } + + migration::checksum_fragments(sql.split(|c| ignored_chars.contains(&c))) +} + +#[test] +fn checksum_with_ignored_chars() { + // Ensure that `checksum_with` returns the same digest for a given set of ignored chars + // as the equivalent string with the characters removed. + let ignored_chars = [ + ' ', '\t', '\r', '\n', + // Zero-width non-breaking space (ZWNBSP), often added as a magic-number at the beginning + // of UTF-8 encoded files as a byte-order mark (BOM): + // https://en.wikipedia.org/wiki/Byte_order_mark + '\u{FEFF}', + ]; + + // Copied from `examples/postgres/axum-social-with-tests/migrations/3_comment.sql` + let sql = "\ + \u{FEFF}create table comment (\r\n\ + \tcomment_id uuid primary key default gen_random_uuid(),\r\n\ + \tpost_id uuid not null references post(post_id),\r\n\ + \tuser_id uuid not null references \"user\"(user_id),\r\n\ + \tcontent text not null,\r\n\ + \tcreated_at timestamptz not null default now()\r\n\ + );\r\n\ + \r\n\ + create index on comment(post_id, created_at);\r\n\ + "; + + let stripped_sql = sql.replace(&ignored_chars[..], ""); + + let ignored_chars = BTreeSet::from(ignored_chars); + + let digest_ignored = checksum_with(sql, &ignored_chars); + let digest_stripped = migration::checksum(&stripped_sql); + + assert_eq!(digest_ignored, digest_stripped); +} diff --git a/vendor/sqlx-core/src/net/mod.rs b/vendor/sqlx-core/src/net/mod.rs new file mode 100755 index 0000000..f9c4366 --- /dev/null +++ b/vendor/sqlx-core/src/net/mod.rs @@ -0,0 +1,6 @@ +mod socket; +pub mod tls; + +pub use socket::{ + connect_tcp, connect_uds, BufferedSocket, Socket, SocketIntoBox, WithSocket, WriteBuffer, +}; diff --git a/vendor/sqlx-core/src/net/socket/buffered.rs b/vendor/sqlx-core/src/net/socket/buffered.rs new file mode 100755 index 0000000..6785e70 --- /dev/null +++ b/vendor/sqlx-core/src/net/socket/buffered.rs @@ -0,0 +1,329 @@ +use crate::error::Error; +use crate::net::Socket; +use bytes::BytesMut; +use std::ops::ControlFlow; +use std::{cmp, io}; + +use crate::io::{AsyncRead, AsyncReadExt, ProtocolDecode, ProtocolEncode}; + +// Tokio, async-std, and std all use this as the default capacity for their buffered I/O. +const DEFAULT_BUF_SIZE: usize = 8192; + +pub struct BufferedSocket { + socket: S, + write_buf: WriteBuffer, + read_buf: ReadBuffer, +} + +pub struct WriteBuffer { + buf: Vec, + bytes_written: usize, + bytes_flushed: usize, +} + +pub struct ReadBuffer { + read: BytesMut, + available: BytesMut, +} + +impl BufferedSocket { + pub fn new(socket: S) -> Self + where + S: Sized, + { + BufferedSocket { + socket, + write_buf: WriteBuffer { + buf: Vec::with_capacity(DEFAULT_BUF_SIZE), + bytes_written: 0, + bytes_flushed: 0, + }, + read_buf: ReadBuffer { + read: BytesMut::new(), + available: BytesMut::with_capacity(DEFAULT_BUF_SIZE), + }, + } + } + + pub async fn read_buffered(&mut self, len: usize) -> Result { + self.try_read(|buf| { + Ok(if buf.len() < len { + ControlFlow::Continue(len) + } else { + ControlFlow::Break(buf.split_to(len)) + }) + }) + .await + } + + /// Retryable read operation. + /// + /// The callback should check the contents of the buffer passed to it and either: + /// + /// * Remove a full message from the buffer and return [`ControlFlow::Break`], or: + /// * Return [`ControlFlow::Continue`] with the expected _total_ length of the buffer, + /// _without_ modifying it. + /// + /// Cancel-safe as long as the callback does not modify the passed `BytesMut` + /// before returning [`ControlFlow::Continue`]. + pub async fn try_read(&mut self, mut try_read: F) -> Result + where + F: FnMut(&mut BytesMut) -> Result, Error>, + { + loop { + let read_len = match try_read(&mut self.read_buf.read)? { + ControlFlow::Continue(read_len) => read_len, + ControlFlow::Break(ret) => return Ok(ret), + }; + + self.read_buf.read(read_len, &mut self.socket).await?; + } + } + + pub fn write_buffer(&self) -> &WriteBuffer { + &self.write_buf + } + + pub fn write_buffer_mut(&mut self) -> &mut WriteBuffer { + &mut self.write_buf + } + + pub async fn read<'de, T>(&mut self, byte_len: usize) -> Result + where + T: ProtocolDecode<'de, ()>, + { + self.read_with(byte_len, ()).await + } + + pub async fn read_with<'de, T, C>(&mut self, byte_len: usize, context: C) -> Result + where + T: ProtocolDecode<'de, C>, + { + T::decode_with(self.read_buffered(byte_len).await?.freeze(), context) + } + + #[inline(always)] + pub fn write<'en, T>(&mut self, value: T) -> Result<(), Error> + where + T: ProtocolEncode<'en, ()>, + { + self.write_with(value, ()) + } + + #[inline(always)] + pub fn write_with<'en, T, C>(&mut self, value: T, context: C) -> Result<(), Error> + where + T: ProtocolEncode<'en, C>, + { + value.encode_with(self.write_buf.buf_mut(), context)?; + self.write_buf.bytes_written = self.write_buf.buf.len(); + self.write_buf.sanity_check(); + + Ok(()) + } + + pub async fn flush(&mut self) -> io::Result<()> { + while !self.write_buf.is_empty() { + let written = self.socket.write(self.write_buf.get()).await?; + self.write_buf.consume(written); + self.write_buf.sanity_check(); + } + + self.socket.flush().await?; + + Ok(()) + } + + pub async fn shutdown(&mut self) -> io::Result<()> { + self.flush().await?; + self.socket.shutdown().await + } + + pub fn shrink_buffers(&mut self) { + // Won't drop data still in the buffer. + self.write_buf.shrink(); + self.read_buf.shrink(); + } + + pub fn into_inner(self) -> S { + self.socket + } + + pub fn boxed(self) -> BufferedSocket> { + BufferedSocket { + socket: Box::new(self.socket), + write_buf: self.write_buf, + read_buf: self.read_buf, + } + } +} + +impl WriteBuffer { + fn sanity_check(&self) { + assert_ne!(self.buf.capacity(), 0); + assert!(self.bytes_written <= self.buf.len()); + assert!(self.bytes_flushed <= self.bytes_written); + } + + pub fn buf_mut(&mut self) -> &mut Vec { + self.buf.truncate(self.bytes_written); + self.sanity_check(); + &mut self.buf + } + + pub fn init_remaining_mut(&mut self) -> &mut [u8] { + self.buf.resize(self.buf.capacity(), 0); + self.sanity_check(); + &mut self.buf[self.bytes_written..] + } + + pub fn put_slice(&mut self, slice: &[u8]) { + // If we already have an initialized area that can fit the slice, + // don't change `self.buf.len()` + if let Some(dest) = self.buf[self.bytes_written..].get_mut(..slice.len()) { + dest.copy_from_slice(slice); + } else { + self.buf.truncate(self.bytes_written); + self.buf.extend_from_slice(slice); + } + self.advance(slice.len()); + self.sanity_check(); + } + + pub fn advance(&mut self, amt: usize) { + let new_bytes_written = self + .bytes_written + .checked_add(amt) + .expect("self.bytes_written + amt overflowed"); + + assert!(new_bytes_written <= self.buf.len()); + + self.bytes_written = new_bytes_written; + + self.sanity_check(); + } + + /// Read into the buffer from `source`, returning the number of bytes read. + /// + /// The buffer is automatically advanced by the number of bytes read. + pub async fn read_from(&mut self, mut source: impl AsyncRead + Unpin) -> io::Result { + let read = match () { + // Tokio lets us read into the buffer without zeroing first + #[cfg(feature = "_rt-tokio")] + _ => source.read_buf(self.buf_mut()).await?, + #[cfg(not(feature = "_rt-tokio"))] + _ => source.read(self.init_remaining_mut()).await?, + }; + + if read > 0 { + self.advance(read); + } + + Ok(read) + } + + pub fn is_empty(&self) -> bool { + self.bytes_flushed >= self.bytes_written + } + + pub fn is_full(&self) -> bool { + self.bytes_written == self.buf.len() + } + + pub fn get(&self) -> &[u8] { + &self.buf[self.bytes_flushed..self.bytes_written] + } + + pub fn get_mut(&mut self) -> &mut [u8] { + &mut self.buf[self.bytes_flushed..self.bytes_written] + } + + pub fn shrink(&mut self) { + if self.bytes_flushed > 0 { + // Move any data that remains to be flushed to the beginning of the buffer, + // if necessary. + self.buf + .copy_within(self.bytes_flushed..self.bytes_written, 0); + self.bytes_written -= self.bytes_flushed; + self.bytes_flushed = 0 + } + + // Drop excess capacity. + self.buf + .truncate(cmp::max(self.bytes_written, DEFAULT_BUF_SIZE)); + self.buf.shrink_to_fit(); + } + + fn consume(&mut self, amt: usize) { + let new_bytes_flushed = self + .bytes_flushed + .checked_add(amt) + .expect("self.bytes_flushed + amt overflowed"); + + assert!(new_bytes_flushed <= self.bytes_written); + + self.bytes_flushed = new_bytes_flushed; + + if self.bytes_flushed == self.bytes_written { + // Reset cursors to zero if we've consumed the whole buffer + self.bytes_flushed = 0; + self.bytes_written = 0; + } + + self.sanity_check(); + } +} + +impl ReadBuffer { + async fn read(&mut self, len: usize, socket: &mut impl Socket) -> io::Result<()> { + // Because of how `BytesMut` works, we should only be shifting capacity back and forth + // between `read` and `available` unless we have to read an oversize message. + while self.read.len() < len { + self.reserve(len - self.read.len()); + + let read = socket.read(&mut self.available).await?; + + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!( + "expected to read {} bytes, got {} bytes at EOF", + len, + self.read.len() + ), + )); + } + + self.advance(read); + } + + Ok(()) + } + + fn reserve(&mut self, amt: usize) { + if let Some(additional) = amt.checked_sub(self.available.capacity()) { + self.available.reserve(additional); + } + } + + fn advance(&mut self, amt: usize) { + self.read.unsplit(self.available.split_to(amt)); + } + + fn shrink(&mut self) { + if self.available.capacity() > DEFAULT_BUF_SIZE { + // `BytesMut` doesn't have a way to shrink its capacity, + // but we only use `available` for spare capacity anyway so we can just replace it. + // + // If `self.read` still contains data on the next call to `advance` then this might + // force a memcpy as they'll no longer be pointing to the same allocation, + // but that's kind of unavoidable. + // + // The `async-std` impl of `Socket` will also need to re-zero the buffer, + // but that's also kind of unavoidable. + // + // We should be warning the user not to call this often. + self.available = BytesMut::with_capacity(DEFAULT_BUF_SIZE); + } + } +} diff --git a/vendor/sqlx-core/src/net/socket/mod.rs b/vendor/sqlx-core/src/net/socket/mod.rs new file mode 100755 index 0000000..0f9aae6 --- /dev/null +++ b/vendor/sqlx-core/src/net/socket/mod.rs @@ -0,0 +1,294 @@ +use std::future::Future; +use std::io; +use std::path::Path; +use std::pin::Pin; +use std::task::{ready, Context, Poll}; + +pub use buffered::{BufferedSocket, WriteBuffer}; +use bytes::BufMut; +use cfg_if::cfg_if; + +use crate::io::ReadBuf; + +mod buffered; + +pub trait Socket: Send + Sync + Unpin + 'static { + fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result; + + fn try_write(&mut self, buf: &[u8]) -> io::Result; + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll>; + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll>; + + fn poll_flush(&mut self, _cx: &mut Context<'_>) -> Poll> { + // `flush()` is a no-op for TCP/UDS + Poll::Ready(Ok(())) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll>; + + fn read<'a, B: ReadBuf>(&'a mut self, buf: &'a mut B) -> Read<'a, Self, B> + where + Self: Sized, + { + Read { socket: self, buf } + } + + fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self> + where + Self: Sized, + { + Write { socket: self, buf } + } + + fn flush(&mut self) -> Flush<'_, Self> + where + Self: Sized, + { + Flush { socket: self } + } + + fn shutdown(&mut self) -> Shutdown<'_, Self> + where + Self: Sized, + { + Shutdown { socket: self } + } +} + +pub struct Read<'a, S: ?Sized, B> { + socket: &'a mut S, + buf: &'a mut B, +} + +impl Future for Read<'_, S, B> +where + S: Socket, + B: ReadBuf, +{ + type Output = io::Result; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = &mut *self; + + while this.buf.has_remaining_mut() { + match this.socket.try_read(&mut *this.buf) { + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + ready!(this.socket.poll_read_ready(cx))?; + } + ready => return Poll::Ready(ready), + } + } + + Poll::Ready(Ok(0)) + } +} + +pub struct Write<'a, S: ?Sized> { + socket: &'a mut S, + buf: &'a [u8], +} + +impl Future for Write<'_, S> +where + S: Socket, +{ + type Output = io::Result; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = &mut *self; + + while !this.buf.is_empty() { + match this.socket.try_write(this.buf) { + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + ready!(this.socket.poll_write_ready(cx))?; + } + ready => return Poll::Ready(ready), + } + } + + Poll::Ready(Ok(0)) + } +} + +pub struct Flush<'a, S: ?Sized> { + socket: &'a mut S, +} + +impl Future for Flush<'_, S> { + type Output = io::Result<()>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.socket.poll_flush(cx) + } +} + +pub struct Shutdown<'a, S: ?Sized> { + socket: &'a mut S, +} + +impl Future for Shutdown<'_, S> +where + S: Socket, +{ + type Output = io::Result<()>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.socket.poll_shutdown(cx) + } +} + +pub trait WithSocket { + type Output; + + fn with_socket(self, socket: S) -> impl Future + Send; +} + +pub struct SocketIntoBox; + +impl WithSocket for SocketIntoBox { + type Output = Box; + + async fn with_socket(self, socket: S) -> Self::Output { + Box::new(socket) + } +} + +impl Socket for Box { + fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result { + (**self).try_read(buf) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + (**self).try_write(buf) + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + (**self).poll_read_ready(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + (**self).poll_write_ready(cx) + } + + fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll> { + (**self).poll_flush(cx) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll> { + (**self).poll_shutdown(cx) + } +} + +pub async fn connect_tcp( + host: &str, + port: u16, + with_socket: Ws, +) -> crate::Result { + #[cfg(feature = "_rt-tokio")] + if crate::rt::rt_tokio::available() { + return Ok(with_socket + .with_socket(tokio::net::TcpStream::connect((host, port)).await?) + .await); + } + + cfg_if! { + if #[cfg(feature = "_rt-async-io")] { + Ok(with_socket.with_socket(connect_tcp_async_io(host, port).await?).await) + } else { + crate::rt::missing_rt((host, port, with_socket)) + } + } +} + +/// Open a TCP socket to `host` and `port`. +/// +/// If `host` is a hostname, attempt to connect to each address it resolves to. +/// +/// This implements the same behavior as [`tokio::net::TcpStream::connect()`]. +#[cfg(feature = "_rt-async-io")] +async fn connect_tcp_async_io(host: &str, port: u16) -> crate::Result { + use async_io::Async; + use std::net::{IpAddr, TcpStream, ToSocketAddrs}; + + // IPv6 addresses in URLs will be wrapped in brackets and the `url` crate doesn't trim those. + let host = host.trim_matches(&['[', ']'][..]); + + if let Ok(addr) = host.parse::() { + return Ok(Async::::connect((addr, port)).await?); + } + + let host = host.to_string(); + + let addresses = crate::rt::spawn_blocking(move || { + let addr = (host.as_str(), port); + ToSocketAddrs::to_socket_addrs(&addr) + }) + .await?; + + let mut last_err = None; + + // Loop through all the Socket Addresses that the hostname resolves to + for socket_addr in addresses { + match Async::::connect(socket_addr).await { + Ok(stream) => return Ok(stream), + Err(e) => last_err = Some(e), + } + } + + // If we reach this point, it means we failed to connect to any of the addresses. + // Return the last error we encountered, or a custom error if the hostname didn't resolve to any address. + Err(last_err + .unwrap_or_else(|| { + io::Error::new( + io::ErrorKind::AddrNotAvailable, + "Hostname did not resolve to any addresses", + ) + }) + .into()) +} + +/// Connect a Unix Domain Socket at the given path. +/// +/// Returns an error if Unix Domain Sockets are not supported on this platform. +pub async fn connect_uds, Ws: WithSocket>( + path: P, + with_socket: Ws, +) -> crate::Result { + #[cfg(unix)] + { + #[cfg(feature = "_rt-tokio")] + if crate::rt::rt_tokio::available() { + use tokio::net::UnixStream; + + let stream = UnixStream::connect(path).await?; + + return Ok(with_socket.with_socket(stream).await); + } + + cfg_if! { + if #[cfg(feature = "_rt-async-io")] { + use async_io::Async; + use std::os::unix::net::UnixStream; + + let stream = Async::::connect(path).await?; + + Ok(with_socket.with_socket(stream).await) + } else { + crate::rt::missing_rt((path, with_socket)) + } + } + } + + #[cfg(not(unix))] + { + drop((path, with_socket)); + + Err(io::Error::new( + io::ErrorKind::Unsupported, + "Unix domain sockets are not supported on this platform", + ) + .into()) + } +} diff --git a/vendor/sqlx-core/src/net/tls/mod.rs b/vendor/sqlx-core/src/net/tls/mod.rs new file mode 100755 index 0000000..7bb1744 --- /dev/null +++ b/vendor/sqlx-core/src/net/tls/mod.rs @@ -0,0 +1,108 @@ +#![allow(dead_code)] + +use std::path::PathBuf; + +use crate::error::Error; +use crate::net::socket::WithSocket; +use crate::net::Socket; + +#[cfg(feature = "_tls-rustls")] +mod tls_rustls; + +#[cfg(feature = "_tls-native-tls")] +mod tls_native_tls; + +mod util; + +/// X.509 Certificate input, either a file path or a PEM encoded inline certificate(s). +#[derive(Clone, Debug)] +pub enum CertificateInput { + /// PEM encoded certificate(s) + Inline(Vec), + /// Path to a file containing PEM encoded certificate(s) + File(PathBuf), +} + +impl From for CertificateInput { + fn from(value: String) -> Self { + // Leading and trailing whitespace/newlines + let trimmed = value.trim(); + + // Heuristic for PEM encoded inputs: + // https://tools.ietf.org/html/rfc7468 + if trimmed.starts_with("-----BEGIN") && trimmed.ends_with("-----") { + CertificateInput::Inline(value.as_bytes().to_vec()) + } else { + CertificateInput::File(PathBuf::from(value)) + } + } +} + +impl CertificateInput { + async fn data(&self) -> Result, std::io::Error> { + use crate::fs; + match self { + CertificateInput::Inline(v) => Ok(v.clone()), + CertificateInput::File(path) => fs::read(path).await, + } + } +} + +impl std::fmt::Display for CertificateInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + CertificateInput::Inline(v) => write!(f, "{}", String::from_utf8_lossy(v.as_slice())), + CertificateInput::File(path) => write!(f, "file: {}", path.display()), + } + } +} + +pub struct TlsConfig<'a> { + pub accept_invalid_certs: bool, + pub accept_invalid_hostnames: bool, + pub hostname: &'a str, + pub root_cert_path: Option<&'a CertificateInput>, + pub client_cert_path: Option<&'a CertificateInput>, + pub client_key_path: Option<&'a CertificateInput>, +} + +pub async fn handshake( + socket: S, + config: TlsConfig<'_>, + with_socket: Ws, +) -> crate::Result +where + S: Socket, + Ws: WithSocket, +{ + #[cfg(feature = "_tls-native-tls")] + return Ok(with_socket + .with_socket(tls_native_tls::handshake(socket, config).await?) + .await); + + #[cfg(all(feature = "_tls-rustls", not(feature = "_tls-native-tls")))] + return Ok(with_socket + .with_socket(tls_rustls::handshake(socket, config).await?) + .await); + + #[cfg(not(any(feature = "_tls-native-tls", feature = "_tls-rustls")))] + { + drop((socket, config, with_socket)); + panic!("one of the `runtime-*-native-tls` or `runtime-*-rustls` features must be enabled") + } +} + +pub fn available() -> bool { + cfg!(any(feature = "_tls-native-tls", feature = "_tls-rustls")) +} + +pub fn error_if_unavailable() -> crate::Result<()> { + if !available() { + return Err(Error::tls( + "TLS upgrade required by connect options \ + but SQLx was built without TLS support enabled", + )); + } + + Ok(()) +} diff --git a/vendor/sqlx-core/src/net/tls/tls_native_tls.rs b/vendor/sqlx-core/src/net/tls/tls_native_tls.rs new file mode 100755 index 0000000..3423e48 --- /dev/null +++ b/vendor/sqlx-core/src/net/tls/tls_native_tls.rs @@ -0,0 +1,88 @@ +use std::io::{self, Read, Write}; + +use crate::io::ReadBuf; +use crate::net::tls::util::StdSocket; +use crate::net::tls::TlsConfig; +use crate::net::Socket; +use crate::rt; +use crate::Error; + +use native_tls::{HandshakeError, Identity}; +use std::task::{Context, Poll}; + +pub struct NativeTlsSocket { + stream: native_tls::TlsStream>, +} + +impl Socket for NativeTlsSocket { + fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result { + self.stream.read(buf.init_mut()) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + self.stream.write(buf) + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.stream.get_mut().poll_ready(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.stream.get_mut().poll_ready(cx) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll> { + match self.stream.shutdown() { + Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.stream.get_mut().poll_ready(cx), + ready => Poll::Ready(ready), + } + } +} + +pub async fn handshake( + socket: S, + config: TlsConfig<'_>, +) -> crate::Result> { + let mut builder = native_tls::TlsConnector::builder(); + + builder + .danger_accept_invalid_certs(config.accept_invalid_certs) + .danger_accept_invalid_hostnames(config.accept_invalid_hostnames); + + if let Some(root_cert_path) = config.root_cert_path { + let data = root_cert_path.data().await?; + builder.add_root_certificate(native_tls::Certificate::from_pem(&data).map_err(Error::tls)?); + } + + // authentication using user's key-file and its associated certificate + if let (Some(cert_path), Some(key_path)) = (config.client_cert_path, config.client_key_path) { + let cert_path = cert_path.data().await?; + let key_path = key_path.data().await?; + let identity = Identity::from_pkcs8(&cert_path, &key_path).map_err(Error::tls)?; + builder.identity(identity); + } + + // The openssl TlsConnector synchronously loads certificates from files. + // Loading these files can block for tens of milliseconds. + let connector = rt::spawn_blocking(move || builder.build()) + .await + .map_err(Error::tls)?; + + let mut mid_handshake = match connector.connect(config.hostname, StdSocket::new(socket)) { + Ok(tls_stream) => return Ok(NativeTlsSocket { stream: tls_stream }), + Err(HandshakeError::Failure(e)) => return Err(Error::tls(e)), + Err(HandshakeError::WouldBlock(mid_handshake)) => mid_handshake, + }; + + loop { + mid_handshake.get_mut().ready().await?; + + match mid_handshake.handshake() { + Ok(tls_stream) => return Ok(NativeTlsSocket { stream: tls_stream }), + Err(HandshakeError::Failure(e)) => return Err(Error::tls(e)), + Err(HandshakeError::WouldBlock(mid_handshake_)) => { + mid_handshake = mid_handshake_; + } + } + } +} diff --git a/vendor/sqlx-core/src/net/tls/tls_rustls.rs b/vendor/sqlx-core/src/net/tls/tls_rustls.rs new file mode 100755 index 0000000..1ecbbad --- /dev/null +++ b/vendor/sqlx-core/src/net/tls/tls_rustls.rs @@ -0,0 +1,340 @@ +use std::future; +use std::io::{self, Read, Write}; +use std::sync::Arc; +use std::task::{ready, Context, Poll}; + +use rustls::{ + client::{ + danger::{ServerCertVerified, ServerCertVerifier}, + WebPkiServerVerifier, + }, + crypto::{verify_tls12_signature, verify_tls13_signature, CryptoProvider}, + pki_types::{ + pem::{self, PemObject}, + CertificateDer, PrivateKeyDer, ServerName, UnixTime, + }, + CertificateError, ClientConfig, ClientConnection, Error as TlsError, RootCertStore, +}; + +use crate::error::Error; +use crate::io::ReadBuf; +use crate::net::tls::util::StdSocket; +use crate::net::tls::TlsConfig; +use crate::net::Socket; + +pub struct RustlsSocket { + inner: StdSocket, + state: ClientConnection, + close_notify_sent: bool, +} + +impl RustlsSocket { + fn poll_complete_io(&mut self, cx: &mut Context<'_>) -> Poll> { + loop { + match self.state.complete_io(&mut self.inner) { + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + ready!(self.inner.poll_ready(cx))?; + } + ready => return Poll::Ready(ready.map(|_| ())), + } + } + } + + async fn complete_io(&mut self) -> io::Result<()> { + future::poll_fn(|cx| self.poll_complete_io(cx)).await + } +} + +impl Socket for RustlsSocket { + fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result { + self.state.reader().read(buf.init_mut()) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + match self.state.writer().write(buf) { + // Returns a zero-length write when the buffer is full. + Ok(0) => Err(io::ErrorKind::WouldBlock.into()), + other => other, + } + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_complete_io(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_complete_io(cx) + } + + fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_complete_io(cx) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll> { + if !self.close_notify_sent { + self.state.send_close_notify(); + self.close_notify_sent = true; + } + + ready!(self.poll_complete_io(cx))?; + + // Server can close socket as soon as it receives the connection shutdown request. + // We shouldn't expect it to stick around for the TLS session to close cleanly. + // https://security.stackexchange.com/a/82034 + let _ = ready!(self.inner.socket.poll_shutdown(cx)); + + Poll::Ready(Ok(())) + } +} + +pub async fn handshake(socket: S, tls_config: TlsConfig<'_>) -> Result, Error> +where + S: Socket, +{ + #[cfg(all( + feature = "_tls-rustls-aws-lc-rs", + not(feature = "_tls-rustls-ring-webpki"), + not(feature = "_tls-rustls-ring-native-roots") + ))] + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + #[cfg(any( + feature = "_tls-rustls-ring-webpki", + feature = "_tls-rustls-ring-native-roots" + ))] + let provider = Arc::new(rustls::crypto::ring::default_provider()); + + // Unwrapping is safe here because we use a default provider. + let config = ClientConfig::builder_with_provider(provider.clone()) + .with_safe_default_protocol_versions() + .unwrap(); + + // authentication using user's key and its associated certificate + let user_auth = match (tls_config.client_cert_path, tls_config.client_key_path) { + (Some(cert_path), Some(key_path)) => { + let cert_chain = certs_from_pem(cert_path.data().await?)?; + let key_der = private_key_from_pem(key_path.data().await?)?; + Some((cert_chain, key_der)) + } + (None, None) => None, + (_, _) => { + return Err(Error::Configuration( + "user auth key and certs must be given together".into(), + )) + } + }; + + let config = if tls_config.accept_invalid_certs { + if let Some(user_auth) = user_auth { + config + .dangerous() + .with_custom_certificate_verifier(Arc::new(DummyTlsVerifier { provider })) + .with_client_auth_cert(user_auth.0, user_auth.1) + .map_err(Error::tls)? + } else { + config + .dangerous() + .with_custom_certificate_verifier(Arc::new(DummyTlsVerifier { provider })) + .with_no_client_auth() + } + } else { + let mut cert_store = import_root_certs(); + + if let Some(ca) = tls_config.root_cert_path { + let data = ca.data().await?; + + for result in CertificateDer::pem_slice_iter(&data) { + let Ok(cert) = result else { + return Err(Error::Tls(format!("Invalid certificate {ca}").into())); + }; + + cert_store.add(cert).map_err(|err| Error::Tls(err.into()))?; + } + } + + if tls_config.accept_invalid_hostnames { + let verifier = WebPkiServerVerifier::builder(Arc::new(cert_store)) + .build() + .map_err(|err| Error::Tls(err.into()))?; + + if let Some(user_auth) = user_auth { + config + .dangerous() + .with_custom_certificate_verifier(Arc::new(NoHostnameTlsVerifier { verifier })) + .with_client_auth_cert(user_auth.0, user_auth.1) + .map_err(Error::tls)? + } else { + config + .dangerous() + .with_custom_certificate_verifier(Arc::new(NoHostnameTlsVerifier { verifier })) + .with_no_client_auth() + } + } else if let Some(user_auth) = user_auth { + config + .with_root_certificates(cert_store) + .with_client_auth_cert(user_auth.0, user_auth.1) + .map_err(Error::tls)? + } else { + config + .with_root_certificates(cert_store) + .with_no_client_auth() + } + }; + + let host = ServerName::try_from(tls_config.hostname.to_owned()).map_err(Error::tls)?; + + let mut socket = RustlsSocket { + inner: StdSocket::new(socket), + state: ClientConnection::new(Arc::new(config), host).map_err(Error::tls)?, + close_notify_sent: false, + }; + + // Performs the TLS handshake or bails + socket.complete_io().await?; + + Ok(socket) +} + +fn certs_from_pem(pem: Vec) -> Result>, Error> { + CertificateDer::pem_slice_iter(&pem) + .map(|result| result.map_err(|err| Error::Tls(err.into()))) + .collect() +} + +fn private_key_from_pem(pem: Vec) -> Result, Error> { + match PrivateKeyDer::from_pem_slice(&pem) { + Ok(key) => Ok(key), + Err(pem::Error::NoItemsFound) => Err(Error::Configuration("no keys found pem file".into())), + Err(e) => Err(Error::Configuration(e.to_string().into())), + } +} + +#[cfg(all(feature = "webpki-roots", not(feature = "rustls-native-certs")))] +fn import_root_certs() -> RootCertStore { + RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()) +} + +#[cfg(feature = "rustls-native-certs")] +fn import_root_certs() -> RootCertStore { + let mut root_cert_store = RootCertStore::empty(); + + let load_results = rustls_native_certs::load_native_certs(); + for e in load_results.errors { + log::warn!("Error loading native certificates: {e:?}"); + } + for cert in load_results.certs { + if let Err(e) = root_cert_store.add(cert) { + log::warn!("rustls failed to parse native certificate: {e:?}"); + } + } + + root_cert_store +} + +// Not currently used but allows for a "tls-rustls-no-roots" feature. +#[cfg(not(any(feature = "rustls-native-certs", feature = "webpki-roots")))] +fn import_root_certs() -> RootCertStore { + RootCertStore::empty() +} + +#[derive(Debug)] +struct DummyTlsVerifier { + provider: Arc, +} + +impl ServerCertVerifier for DummyTlsVerifier { + fn verify_server_cert( + &self, + _end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime, + ) -> Result { + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + verify_tls12_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + verify_tls13_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn supported_verify_schemes(&self) -> Vec { + self.provider + .signature_verification_algorithms + .supported_schemes() + } +} + +#[derive(Debug)] +pub struct NoHostnameTlsVerifier { + verifier: Arc, +} + +impl ServerCertVerifier for NoHostnameTlsVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> Result { + match self.verifier.verify_server_cert( + end_entity, + intermediates, + server_name, + ocsp_response, + now, + ) { + Err(TlsError::InvalidCertificate( + CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. }, + )) => Ok(ServerCertVerified::assertion()), + res => res, + } + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + self.verifier.verify_tls12_signature(message, cert, dss) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + self.verifier.verify_tls13_signature(message, cert, dss) + } + + fn supported_verify_schemes(&self) -> Vec { + self.verifier.supported_verify_schemes() + } +} diff --git a/vendor/sqlx-core/src/net/tls/util.rs b/vendor/sqlx-core/src/net/tls/util.rs new file mode 100755 index 0000000..99aa638 --- /dev/null +++ b/vendor/sqlx-core/src/net/tls/util.rs @@ -0,0 +1,78 @@ +use crate::net::Socket; + +use std::future; +use std::io::{self, Read, Write}; +use std::task::{Context, Poll}; + +pub struct StdSocket { + pub socket: S, + wants_read: bool, + wants_write: bool, +} + +impl StdSocket { + pub fn new(socket: S) -> Self { + Self { + socket, + wants_read: false, + wants_write: false, + } + } + + /// Returns `Ready` if a previously blocked read _or_ write may now proceed. + /// + /// If both a read and a write were attempted, to avoid deadlocks this returns `Ready` + /// when _either_ direction is ready, not necessarily both. + pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + // Return `Ready` without waiting if the caller hasn't tried to do I/O in either direction. + let mut ready = !(self.wants_read || self.wants_write); + + if self.wants_write && self.socket.poll_write_ready(cx)?.is_ready() { + self.wants_write = false; + ready |= true; + } + + if self.wants_read && self.socket.poll_read_ready(cx)?.is_ready() { + self.wants_read = false; + ready |= true; + } + + if ready { + Poll::Ready(Ok(())) + } else { + Poll::Pending + } + } + + /// Returns successfully if a previously blocked read _or_ write may now proceed. + /// + /// If both a read and a write were attempted, to avoid deadlocks this returns when _either_ + /// direction is ready, not necessarily both. + pub async fn ready(&mut self) -> io::Result<()> { + future::poll_fn(|cx| self.poll_ready(cx)).await + } +} + +impl Read for StdSocket { + fn read(&mut self, mut buf: &mut [u8]) -> io::Result { + self.wants_read = true; + let read = self.socket.try_read(&mut buf)?; + self.wants_read = false; + + Ok(read) + } +} + +impl Write for StdSocket { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.wants_write = true; + let written = self.socket.try_write(buf)?; + self.wants_write = false; + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + // NOTE: TCP sockets and unix sockets are both no-ops for flushes + Ok(()) + } +} diff --git a/vendor/sqlx-core/src/pool/connection.rs b/vendor/sqlx-core/src/pool/connection.rs new file mode 100755 index 0000000..7912b12 --- /dev/null +++ b/vendor/sqlx-core/src/pool/connection.rs @@ -0,0 +1,421 @@ +use std::fmt::{self, Debug, Formatter}; +use std::future::{self, Future}; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use crate::sync::AsyncSemaphoreReleaser; + +use crate::connection::Connection; +use crate::database::Database; +use crate::error::Error; + +use super::inner::{is_beyond_max_lifetime, DecrementSizeGuard, PoolInner}; +use crate::pool::options::PoolConnectionMetadata; + +const CLOSE_ON_DROP_TIMEOUT: Duration = Duration::from_secs(5); + +/// A connection managed by a [`Pool`][crate::pool::Pool]. +/// +/// Will be returned to the pool on-drop. +pub struct PoolConnection { + live: Option>, + close_on_drop: bool, + pub(crate) pool: Arc>, +} + +pub(super) struct Live { + pub(super) raw: DB::Connection, + pub(super) created_at: Instant, +} + +pub(super) struct Idle { + pub(super) live: Live, + pub(super) idle_since: Instant, +} + +/// RAII wrapper for connections being handled by functions that may drop them +pub(super) struct Floating { + pub(super) inner: C, + pub(super) guard: DecrementSizeGuard, +} + +const EXPECT_MSG: &str = "BUG: inner connection already taken!"; + +impl Debug for PoolConnection { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + // TODO: Show the type name of the connection ? + f.debug_struct("PoolConnection").finish() + } +} + +impl Deref for PoolConnection { + type Target = DB::Connection; + + fn deref(&self) -> &Self::Target { + &self.live.as_ref().expect(EXPECT_MSG).raw + } +} + +impl DerefMut for PoolConnection { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.live.as_mut().expect(EXPECT_MSG).raw + } +} + +impl AsRef for PoolConnection { + fn as_ref(&self) -> &DB::Connection { + self + } +} + +impl AsMut for PoolConnection { + fn as_mut(&mut self) -> &mut DB::Connection { + self + } +} + +impl PoolConnection { + /// Close this connection, allowing the pool to open a replacement. + /// + /// Equivalent to calling [`.detach()`] then [`.close()`], but the connection permit is retained + /// for the duration so that the pool may not exceed `max_connections`. + /// + /// [`.detach()`]: PoolConnection::detach + /// [`.close()`]: Connection::close + pub async fn close(mut self) -> Result<(), Error> { + let floating = self.take_live().float(self.pool.clone()); + floating.inner.raw.close().await + } + + /// Close this connection on-drop, instead of returning it to the pool. + /// + /// May be used in cases where waiting for the [`.close()`][Self::close] call + /// to complete is unacceptable, but you still want the connection to be closed gracefully + /// so that the server can clean up resources. + #[inline(always)] + pub fn close_on_drop(&mut self) { + self.close_on_drop = true; + } + + /// Detach this connection from the pool, allowing it to open a replacement. + /// + /// Note that if your application uses a single shared pool, this + /// effectively lets the application exceed the [`max_connections`] setting. + /// + /// If [`min_connections`] is nonzero, a task will be spawned to replace this connection. + /// + /// If you want the pool to treat this connection as permanently checked-out, + /// use [`.leak()`][Self::leak] instead. + /// + /// [`max_connections`]: crate::pool::PoolOptions::max_connections + /// [`min_connections`]: crate::pool::PoolOptions::min_connections + pub fn detach(mut self) -> DB::Connection { + self.take_live().float(self.pool.clone()).detach() + } + + /// Detach this connection from the pool, treating it as permanently checked-out. + /// + /// This effectively will reduce the maximum capacity of the pool by 1 every time it is used. + /// + /// If you don't want to impact the pool's capacity, use [`.detach()`][Self::detach] instead. + pub fn leak(mut self) -> DB::Connection { + self.take_live().raw + } + + fn take_live(&mut self) -> Live { + self.live.take().expect(EXPECT_MSG) + } + + /// Test the connection to make sure it is still live before returning it to the pool. + /// + /// This effectively runs the drop handler eagerly instead of spawning a task to do it. + #[doc(hidden)] + pub fn return_to_pool(&mut self) -> impl Future + Send + 'static { + // float the connection in the pool before we move into the task + // in case the returned `Future` isn't executed, like if it's spawned into a dying runtime + // https://github.com/launchbadge/sqlx/issues/1396 + // Type hints seem to be broken by `Option` combinators in IntelliJ Rust right now (6/22). + let floating: Option>> = + self.live.take().map(|live| live.float(self.pool.clone())); + + let pool = self.pool.clone(); + + async move { + let returned_to_pool = if let Some(floating) = floating { + floating.return_to_pool().await + } else { + false + }; + + if !returned_to_pool { + pool.min_connections_maintenance(None).await; + } + } + } + + fn take_and_close(&mut self) -> impl Future + Send + 'static { + // float the connection in the pool before we move into the task + // in case the returned `Future` isn't executed, like if it's spawned into a dying runtime + // https://github.com/launchbadge/sqlx/issues/1396 + // Type hints seem to be broken by `Option` combinators in IntelliJ Rust right now (6/22). + let floating = self.live.take().map(|live| live.float(self.pool.clone())); + + let pool = self.pool.clone(); + + async move { + if let Some(floating) = floating { + // Don't hold the connection forever if it hangs while trying to close + crate::rt::timeout(CLOSE_ON_DROP_TIMEOUT, floating.close()) + .await + .ok(); + } + + pool.min_connections_maintenance(None).await; + } + } +} + +impl<'c, DB: Database> crate::acquire::Acquire<'c> for &'c mut PoolConnection { + type Database = DB; + + type Connection = &'c mut ::Connection; + + #[inline] + fn acquire(self) -> futures_core::future::BoxFuture<'c, Result> { + Box::pin(future::ready(Ok(&mut **self))) + } + + #[inline] + fn begin( + self, + ) -> futures_core::future::BoxFuture<'c, Result, Error>> + { + crate::transaction::Transaction::begin(&mut **self, None) + } +} + +/// Returns the connection to the [`Pool`][crate::pool::Pool] it was checked-out from. +impl Drop for PoolConnection { + fn drop(&mut self) { + if self.close_on_drop { + crate::rt::spawn(self.take_and_close()); + return; + } + + // We still need to spawn a task to maintain `min_connections`. + if self.live.is_some() || self.pool.options.min_connections > 0 { + crate::rt::spawn(self.return_to_pool()); + } + } +} + +impl Live { + pub fn float(self, pool: Arc>) -> Floating { + Floating { + inner: self, + // create a new guard from a previously leaked permit + guard: DecrementSizeGuard::new_permit(pool), + } + } + + pub fn into_idle(self) -> Idle { + Idle { + live: self, + idle_since: Instant::now(), + } + } +} + +impl Deref for Idle { + type Target = Live; + + fn deref(&self) -> &Self::Target { + &self.live + } +} + +impl DerefMut for Idle { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.live + } +} + +impl Floating> { + pub fn new_live(conn: DB::Connection, guard: DecrementSizeGuard) -> Self { + Self { + inner: Live { + raw: conn, + created_at: Instant::now(), + }, + guard, + } + } + + pub fn reattach(self) -> PoolConnection { + let Floating { inner, guard } = self; + + let pool = Arc::clone(&guard.pool); + + guard.cancel(); + PoolConnection { + live: Some(inner), + close_on_drop: false, + pool, + } + } + + pub fn release(self) { + self.guard.pool.clone().release(self); + } + + /// Return the connection to the pool. + /// + /// Returns `true` if the connection was successfully returned, `false` if it was closed. + async fn return_to_pool(mut self) -> bool { + // Immediately close the connection. + if self.guard.pool.is_closed() { + self.close().await; + return false; + } + + // If the connection is beyond max lifetime, close the connection and + // immediately create a new connection + if is_beyond_max_lifetime(&self.inner, &self.guard.pool.options) { + self.close().await; + return false; + } + + if let Some(test) = &self.guard.pool.options.after_release { + let meta = self.metadata(); + match (test)(&mut self.inner.raw, meta).await { + Ok(true) => (), + Ok(false) => { + self.close().await; + return false; + } + Err(error) => { + tracing::warn!(%error, "error from `after_release`"); + // Connection is broken, don't try to gracefully close as + // something weird might happen. + self.close_hard().await; + return false; + } + } + } + + // test the connection on-release to ensure it is still viable, + // and flush anything time-sensitive like transaction rollbacks + // if an Executor future/stream is dropped during an `.await` call, the connection + // is likely to be left in an inconsistent state, in which case it should not be + // returned to the pool; also of course, if it was dropped due to an error + // this is simply a band-aid as SQLx-next connections should be able + // to recover from cancellations + if let Err(error) = self.raw.ping().await { + tracing::warn!( + %error, + "error occurred while testing the connection on-release", + ); + + // Connection is broken, don't try to gracefully close. + self.close_hard().await; + false + } else { + // if the connection is still viable, release it to the pool + self.release(); + true + } + } + + pub async fn close(self) { + // This isn't used anywhere that we care about the return value + let _ = self.inner.raw.close().await; + + // `guard` is dropped as intended + } + + pub async fn close_hard(self) { + let _ = self.inner.raw.close_hard().await; + } + + pub fn detach(self) -> DB::Connection { + self.inner.raw + } + + pub fn into_idle(self) -> Floating> { + Floating { + inner: self.inner.into_idle(), + guard: self.guard, + } + } + + pub fn metadata(&self) -> PoolConnectionMetadata { + PoolConnectionMetadata { + age: self.created_at.elapsed(), + idle_for: Duration::ZERO, + } + } +} + +impl Floating> { + pub fn from_idle( + idle: Idle, + pool: Arc>, + permit: AsyncSemaphoreReleaser<'_>, + ) -> Self { + Self { + inner: idle, + guard: DecrementSizeGuard::from_permit(pool, permit), + } + } + + pub async fn ping(&mut self) -> Result<(), Error> { + self.live.raw.ping().await + } + + pub fn into_live(self) -> Floating> { + Floating { + inner: self.inner.live, + guard: self.guard, + } + } + + pub async fn close(self) -> DecrementSizeGuard { + if let Err(error) = self.inner.live.raw.close().await { + tracing::debug!(%error, "error occurred while closing the pool connection"); + } + self.guard + } + + pub async fn close_hard(self) -> DecrementSizeGuard { + let _ = self.inner.live.raw.close_hard().await; + + self.guard + } + + pub fn metadata(&self) -> PoolConnectionMetadata { + // Use a single `now` value for consistency. + let now = Instant::now(); + + PoolConnectionMetadata { + // NOTE: the receiver is the later `Instant` and the arg is the earlier + // https://github.com/launchbadge/sqlx/issues/1912 + age: now.saturating_duration_since(self.created_at), + idle_for: now.saturating_duration_since(self.idle_since), + } + } +} + +impl Deref for Floating { + type Target = C; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl DerefMut for Floating { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} diff --git a/vendor/sqlx-core/src/pool/executor.rs b/vendor/sqlx-core/src/pool/executor.rs new file mode 100755 index 0000000..6fb06b9 --- /dev/null +++ b/vendor/sqlx-core/src/pool/executor.rs @@ -0,0 +1,147 @@ +use either::Either; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; +use futures_util::TryStreamExt; + +use crate::database::Database; +use crate::error::Error; +use crate::executor::{Execute, Executor}; +use crate::pool::Pool; +use crate::sql_str::SqlStr; + +impl<'p, DB: Database> Executor<'p> for &'_ Pool +where + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, +{ + type Database = DB; + + fn fetch_many<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxStream<'e, Result, Error>> + where + E: 'q + Execute<'q, Self::Database>, + { + let pool = self.clone(); + + Box::pin(try_stream! { + let mut conn = pool.acquire().await?; + let mut s = conn.fetch_many(query); + + while let Some(v) = s.try_next().await? { + r#yield!(v); + } + + Ok(()) + }) + } + + fn fetch_optional<'e, 'q: 'e, E>( + self, + query: E, + ) -> BoxFuture<'e, Result, Error>> + where + E: 'q + Execute<'q, Self::Database>, + { + let pool = self.clone(); + + Box::pin(async move { pool.acquire().await?.fetch_optional(query).await }) + } + + fn prepare_with<'e>( + self, + sql: SqlStr, + parameters: &'e [::TypeInfo], + ) -> BoxFuture<'e, Result<::Statement, Error>> + where + 'p: 'e, + { + let pool = self.clone(); + + Box::pin(async move { pool.acquire().await?.prepare_with(sql, parameters).await }) + } + + #[doc(hidden)] + #[cfg(feature = "offline")] + fn describe<'e>( + self, + sql: SqlStr, + ) -> BoxFuture<'e, Result, Error>> { + let pool = self.clone(); + + Box::pin(async move { pool.acquire().await?.describe(sql).await }) + } +} + +// Causes an overflow when evaluating `&mut DB::Connection: Executor`. +// +// +// impl<'c, DB: Database> crate::executor::Executor<'c> for &'c mut crate::pool::PoolConnection +// where +// &'c mut DB::Connection: Executor<'c, Database = DB>, +// { +// type Database = DB; +// +// +// +// #[inline] +// fn fetch_many<'e, 'q: 'e, E: 'q>( +// self, +// query: E, +// ) -> futures_core::stream::BoxStream< +// 'e, +// Result< +// either::Either<::QueryResult, DB::Row>, +// crate::error::Error, +// >, +// > +// where +// 'c: 'e, +// E: crate::executor::Execute<'q, DB>, +// { +// (**self).fetch_many(query) +// } +// +// #[inline] +// fn fetch_optional<'e, 'q: 'e, E: 'q>( +// self, +// query: E, +// ) -> futures_core::future::BoxFuture<'e, Result, crate::error::Error>> +// where +// 'c: 'e, +// E: crate::executor::Execute<'q, DB>, +// { +// (**self).fetch_optional(query) +// } +// +// #[inline] +// fn prepare_with<'e, 'q: 'e>( +// self, +// sql: &'q str, +// parameters: &'e [::TypeInfo], +// ) -> futures_core::future::BoxFuture< +// 'e, +// Result<::Statement<'q>, crate::error::Error>, +// > +// where +// 'c: 'e, +// { +// (**self).prepare_with(sql, parameters) +// } +// +// #[doc(hidden)] +// #[cfg(feature = "offline")] +// #[inline] +// fn describe<'e, 'q: 'e>( +// self, +// sql: &'q str, +// ) -> futures_core::future::BoxFuture< +// 'e, +// Result, crate::error::Error>, +// > +// where +// 'c: 'e, +// { +// (**self).describe(sql) +// } +// } diff --git a/vendor/sqlx-core/src/pool/inner.rs b/vendor/sqlx-core/src/pool/inner.rs new file mode 100755 index 0000000..0a12e26 --- /dev/null +++ b/vendor/sqlx-core/src/pool/inner.rs @@ -0,0 +1,767 @@ +// Local CranK pool patch: this file is patched from the upstream `sqlx-core` +// 0.9.0 source. The changes reserve `num_idle` before publishing an idle +// connection and bound each pool maintenance scan by the pool capacity. +// See ../../../../docs/dependency-patches/sqlx-core-0.9.0.md for provenance, +// the exact patch and the regression tests. Upstream copyright and license +// notices are unchanged. +use super::connection::{Floating, Idle, Live}; +use crate::connection::ConnectOptions; +use crate::connection::Connection; +use crate::database::Database; +use crate::error::Error; +use crate::pool::{deadline_as_timeout, CloseEvent, Pool, PoolOptions}; +use crossbeam_queue::ArrayQueue; + +use crate::sync::{AsyncSemaphore, AsyncSemaphoreReleaser}; + +use std::cmp; +use std::future::{self, Future}; +use std::pin::pin; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; +use std::sync::{Arc, RwLock}; +use std::task::Poll; + +use crate::logger::private_level_filter_to_trace_level; +use crate::pool::options::PoolConnectionMetadata; +use crate::private_tracing_dynamic_event; +use futures_util::FutureExt; +use std::time::{Duration, Instant}; +use tracing::Level; + +pub(crate) struct PoolInner { + pub(super) connect_options: RwLock::Options>>, + pub(super) idle_conns: ArrayQueue>, + pub(super) semaphore: AsyncSemaphore, + pub(super) size: AtomicU32, + pub(super) num_idle: AtomicUsize, + is_closed: AtomicBool, + pub(super) on_closed: event_listener::Event, + pub(super) options: PoolOptions, + pub(crate) acquire_time_level: Option, + pub(crate) acquire_slow_level: Option, +} + +impl PoolInner { + pub(super) fn new_arc( + options: PoolOptions, + connect_options: ::Options, + ) -> Arc { + let capacity = options.max_connections as usize; + + let semaphore_capacity = if let Some(parent) = &options.parent_pool { + assert!(options.max_connections <= parent.options().max_connections); + assert_eq!(options.fair, parent.options().fair); + // The child pool must steal permits from the parent + 0 + } else { + capacity + }; + + let pool = Self { + connect_options: RwLock::new(Arc::new(connect_options)), + idle_conns: ArrayQueue::new(capacity), + semaphore: AsyncSemaphore::new(options.fair, semaphore_capacity), + size: AtomicU32::new(0), + num_idle: AtomicUsize::new(0), + is_closed: AtomicBool::new(false), + on_closed: event_listener::Event::new(), + acquire_time_level: private_level_filter_to_trace_level(options.acquire_time_level), + acquire_slow_level: private_level_filter_to_trace_level(options.acquire_slow_level), + options, + }; + + let pool = Arc::new(pool); + + spawn_maintenance_tasks(&pool); + + pool + } + + pub(super) fn size(&self) -> u32 { + self.size.load(Ordering::Acquire) + } + + pub(super) fn num_idle(&self) -> usize { + // We don't use `self.idle_conns.len()` as it waits for the internal + // head and tail pointers to stop changing for a moment before calculating the length, + // which may take a long time at high levels of churn. + // + // By maintaining our own atomic count, we avoid that issue entirely. + self.num_idle.load(Ordering::Acquire) + } + + pub(super) fn is_closed(&self) -> bool { + self.is_closed.load(Ordering::Acquire) + } + + fn mark_closed(&self) { + self.is_closed.store(true, Ordering::Release); + self.on_closed.notify(usize::MAX); + } + + pub(super) fn close(self: &Arc) -> impl Future + '_ { + self.mark_closed(); + + async move { + // For child pools, we need to acquire permits we actually have rather than + // max_connections + let permits_to_acquire = if self.options.parent_pool.is_some() { + // Child pools start with 0 permits, so we acquire based on current size + self.size() + } else { + // Parent pools can acquire all max_connections permits + self.options.max_connections + }; + + let _permits = self.semaphore.acquire(permits_to_acquire).await; + + while let Some(idle) = self.idle_conns.pop() { + let _ = idle.live.raw.close().await; + } + + self.num_idle.store(0, Ordering::Release); + self.size.store(0, Ordering::Release); + } + } + + pub(crate) fn close_event(&self) -> CloseEvent { + CloseEvent { + listener: (!self.is_closed()).then(|| self.on_closed.listen()), + } + } + + /// Attempt to pull a permit from `self.semaphore` or steal one from the parent. + /// + /// If we steal a permit from the parent but *don't* open a connection, + /// it should be returned to the parent. + async fn acquire_permit(self: &Arc) -> Result, Error> { + let parent = self + .parent() + // If we're already at the max size, we shouldn't try to steal from the parent. + // This is just going to cause unnecessary churn in `acquire()`. + .filter(|_| self.size() < self.options.max_connections); + + let mut acquire_self = pin!(self.semaphore.acquire(1).fuse()); + let mut close_event = pin!(self.close_event()); + + if let Some(parent) = parent { + let mut acquire_parent = pin!(parent.0.semaphore.acquire(1)); + let mut parent_close_event = pin!(parent.0.close_event()); + + let mut poll_parent = false; + + future::poll_fn(|cx| { + if close_event.as_mut().poll(cx).is_ready() { + return Poll::Ready(Err(Error::PoolClosed)); + } + + if parent_close_event.as_mut().poll(cx).is_ready() { + // Propagate the parent's close event to the child. + self.mark_closed(); + return Poll::Ready(Err(Error::PoolClosed)); + } + + if let Poll::Ready(permit) = acquire_self.as_mut().poll(cx) { + return Poll::Ready(Ok(permit)); + } + + // Don't try the parent right away. + if poll_parent { + acquire_parent.as_mut().poll(cx).map(Ok) + } else { + poll_parent = true; + cx.waker().wake_by_ref(); + Poll::Pending + } + }) + .await + } else { + close_event.do_until(acquire_self).await + } + } + + fn parent(&self) -> Option<&Pool> { + self.options.parent_pool.as_ref() + } + + #[inline] + pub(super) fn try_acquire(self: &Arc) -> Option>> { + if self.is_closed() { + return None; + } + + let permit = self.semaphore.try_acquire(1)?; + + self.pop_idle(permit).ok() + } + + fn pop_idle<'a>( + self: &'a Arc, + permit: AsyncSemaphoreReleaser<'a>, + ) -> Result>, AsyncSemaphoreReleaser<'a>> { + if let Some(idle) = self.idle_conns.pop() { + self.num_idle.fetch_sub(1, Ordering::AcqRel); + Ok(Floating::from_idle(idle, (*self).clone(), permit)) + } else { + Err(permit) + } + } + + pub(super) fn release(&self, floating: Floating>) { + // `options.after_release` and other checks are in `PoolConnection::return_to_pool()`. + + let Floating { inner: idle, guard } = floating.into_idle(); + + let published = publish_idle_connection(&self.num_idle, move || { + // NOTE: we need to make sure we drop the permit *after* we push to the idle queue + // don't decrease the size + self.idle_conns.push(idle).map(|()| guard.release_permit()) + }); + + if published.is_err() { + panic!("BUG: connection queue overflow in release()"); + } + } + + /// Try to atomically increment the pool size for a new connection. + /// + /// Returns `Err` if the pool is at max capacity already or is closed. + pub(super) fn try_increment_size<'a>( + self: &'a Arc, + permit: AsyncSemaphoreReleaser<'a>, + ) -> Result, AsyncSemaphoreReleaser<'a>> { + let result = self + .size + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |size| { + if self.is_closed() { + return None; + } + + size.checked_add(1) + .filter(|size| size <= &self.options.max_connections) + }); + + match result { + // we successfully incremented the size + Ok(_) => Ok(DecrementSizeGuard::from_permit((*self).clone(), permit)), + // the pool is at max capacity or is closed + Err(_) => Err(permit), + } + } + + pub(super) async fn acquire(self: &Arc) -> Result>, Error> { + if self.is_closed() { + return Err(Error::PoolClosed); + } + + let acquire_started_at = Instant::now(); + let deadline = acquire_started_at + self.options.acquire_timeout; + + let acquired = crate::rt::timeout( + self.options.acquire_timeout, + async { + loop { + // Handles the close-event internally + let permit = self.acquire_permit().await?; + + + // First attempt to pop a connection from the idle queue. + let guard = match self.pop_idle(permit) { + + // Then, check that we can use it... + Ok(conn) => match check_idle_conn(conn, &self.options).await { + + // All good! + Ok(live) => return Ok(live), + + // if the connection isn't usable for one reason or another, + // we get the `DecrementSizeGuard` back to open a new one + Err(guard) => guard, + }, + Err(permit) => if let Ok(guard) = self.try_increment_size(permit) { + // we can open a new connection + guard + } else { + // This can happen for a child pool that's at its connection limit, + // or if the pool was closed between `acquire_permit()` and + // `try_increment_size()`. + tracing::debug!("woke but was unable to acquire idle connection or open new one; retrying"); + // If so, we're likely in the current-thread runtime if it's Tokio, + // and so we should yield to let any spawned return_to_pool() tasks + // execute. + crate::rt::yield_now().await; + continue; + } + }; + + // Attempt to connect... + return self.connect(deadline, guard).await; + } + } + ) + .await + .map_err(|_| Error::PoolTimedOut)??; + + let acquired_after = acquire_started_at.elapsed(); + + let acquire_slow_level = self + .acquire_slow_level + .filter(|_| acquired_after > self.options.acquire_slow_threshold); + + if let Some(level) = acquire_slow_level { + private_tracing_dynamic_event!( + target: "sqlx::pool::acquire", + level, + acquired_after_secs = acquired_after.as_secs_f64(), + slow_acquire_threshold_secs = self.options.acquire_slow_threshold.as_secs_f64(), + "acquired connection, but time to acquire exceeded slow threshold" + ); + } else if let Some(level) = self.acquire_time_level { + private_tracing_dynamic_event!( + target: "sqlx::pool::acquire", + level, + acquired_after_secs = acquired_after.as_secs_f64(), + "acquired connection" + ); + } + + Ok(acquired) + } + + pub(super) async fn connect( + self: &Arc, + deadline: Instant, + guard: DecrementSizeGuard, + ) -> Result>, Error> { + if self.is_closed() { + return Err(Error::PoolClosed); + } + + let mut backoff = Duration::from_millis(10); + let max_backoff = deadline_as_timeout(deadline)? / 5; + + loop { + let timeout = deadline_as_timeout(deadline)?; + + // clone the connect options arc so it can be used without holding the RwLockReadGuard + // across an async await point + let connect_options = self + .connect_options + .read() + .expect("write-lock holder panicked") + .clone(); + + // result here is `Result, TimeoutError>` + // if this block does not return, sleep for the backoff timeout and try again + match crate::rt::timeout(timeout, connect_options.connect()).await { + // successfully established connection + Ok(Ok(mut raw)) => { + // See comment on `PoolOptions::after_connect` + let meta = PoolConnectionMetadata { + age: Duration::ZERO, + idle_for: Duration::ZERO, + }; + + let res = if let Some(callback) = &self.options.after_connect { + callback(&mut raw, meta).await + } else { + Ok(()) + }; + + match res { + Ok(()) => return Ok(Floating::new_live(raw, guard)), + Err(error) => { + tracing::error!(%error, "error returned from after_connect"); + // The connection is broken, don't try to close nicely. + let _ = raw.close_hard().await; + + // Fall through to the backoff. + } + } + } + + // an IO error while connecting is assumed to be the system starting up + Ok(Err(Error::Io(e))) if e.kind() == std::io::ErrorKind::ConnectionRefused => (), + + // We got a transient database error, retry. + Ok(Err(Error::Database(error))) if error.is_transient_in_connect_phase() => (), + + // Any other error while connection should immediately + // terminate and bubble the error up + Ok(Err(e)) => return Err(e), + + // timed out + Err(_) => return Err(Error::PoolTimedOut), + } + + // If the connection is refused, wait in exponentially + // increasing steps for the server to come up, + // capped by a factor of the remaining time until the deadline + crate::rt::sleep(backoff).await; + backoff = cmp::min(backoff * 2, max_backoff); + } + } + + /// Try to maintain `min_connections`, returning any errors (including `PoolTimedOut`). + pub async fn try_min_connections(self: &Arc, deadline: Instant) -> Result<(), Error> { + while self.size() < self.options.min_connections { + // Don't wait for a semaphore permit. + // + // If no extra permits are available then we shouldn't be trying to spin up + // connections anyway. + let Some(permit) = self.semaphore.try_acquire(1) else { + return Ok(()); + }; + + // We must always obey `max_connections`. + let Some(guard) = self.try_increment_size(permit).ok() else { + return Ok(()); + }; + + // We skip `after_release` since the connection was never provided to user code + // besides `after_connect`, if they set it. + self.release(self.connect(deadline, guard).await?); + } + + Ok(()) + } + + /// Attempt to maintain `min_connections`, logging if unable. + pub async fn min_connections_maintenance(self: &Arc, deadline: Option) { + let deadline = deadline.unwrap_or_else(|| { + // Arbitrary default deadline if the caller doesn't care. + Instant::now() + Duration::from_secs(300) + }); + + match self.try_min_connections(deadline).await { + Ok(()) => (), + Err(Error::PoolClosed) => (), + Err(Error::PoolTimedOut) => { + tracing::debug!("unable to complete `min_connections` maintenance before deadline") + } + Err(error) => tracing::debug!(%error, "error while maintaining min_connections"), + } + } +} + +/// Reserves the idle-connection slot for a publication and runs `publish`. +/// +/// `publish` performs the actual publication (pushing onto `idle_conns` and +/// releasing the semaphore permit). The `num_idle` counter is reserved *before* +/// `publish` so a concurrent `pop_idle` cannot underflow it between the queue +/// push and the counter update. If `publish` fails (the idle queue rejects the +/// connection), the reservation is rolled back before the error is returned to +/// the caller. +fn publish_idle_connection(num_idle: &AtomicUsize, publish: F) -> Result<(), E> +where + F: FnOnce() -> Result<(), E>, +{ + num_idle.fetch_add(1, Ordering::AcqRel); + + if let Err(error) = publish() { + num_idle.fetch_sub(1, Ordering::AcqRel); + return Err(error); + } + + Ok(()) +} + +/// Bounds the number of idle connections inspected per maintenance cycle. +/// +/// `num_idle` can transiently exceed the number of connections actually queued +/// during a publication race, so the maintenance scan is capped by the pool +/// capacity to keep each cycle bounded. +fn maintenance_batch_size(num_idle: usize, capacity: usize) -> usize { + cmp::min(num_idle, capacity) +} + +impl Drop for PoolInner { + fn drop(&mut self) { + self.mark_closed(); + + if let Some(parent) = &self.options.parent_pool { + // Release the stolen permits. + parent.0.semaphore.release(self.semaphore.permits()); + } + } +} + +/// Returns `true` if the connection has exceeded `options.max_lifetime` if set, `false` otherwise. +pub(super) fn is_beyond_max_lifetime( + live: &Live, + options: &PoolOptions, +) -> bool { + options + .max_lifetime + .is_some_and(|max| live.created_at.elapsed() > max) +} + +/// Returns `true` if the connection has exceeded `options.idle_timeout` if set, `false` otherwise. +fn is_beyond_idle_timeout(idle: &Idle, options: &PoolOptions) -> bool { + options + .idle_timeout + .is_some_and(|timeout| idle.idle_since.elapsed() > timeout) +} + +async fn check_idle_conn( + mut conn: Floating>, + options: &PoolOptions, +) -> Result>, DecrementSizeGuard> { + if options.test_before_acquire { + // Check that the connection is still live + if let Err(error) = conn.ping().await { + // an error here means the other end has hung up or we lost connectivity + // either way we're fine to just discard the connection + // the error itself here isn't necessarily unexpected so WARN is too strong + tracing::info!(%error, "ping on idle connection returned error"); + // connection is broken so don't try to close nicely + return Err(conn.close_hard().await); + } + } + + if let Some(test) = &options.before_acquire { + let meta = conn.metadata(); + match test(&mut conn.live.raw, meta).await { + Ok(false) => { + // connection was rejected by user-defined hook, close nicely + return Err(conn.close().await); + } + + Err(error) => { + tracing::warn!(%error, "error from `before_acquire`"); + // connection is broken so don't try to close nicely + return Err(conn.close_hard().await); + } + + Ok(true) => {} + } + } + + // No need to re-connect; connection is alive or we don't care + Ok(conn.into_live()) +} + +fn spawn_maintenance_tasks(pool: &Arc>) { + // NOTE: use `pool_weak` for the maintenance tasks + // so they don't keep `PoolInner` from being dropped. + let pool_weak = Arc::downgrade(pool); + + let period = match (pool.options.max_lifetime, pool.options.idle_timeout) { + (Some(it), None) | (None, Some(it)) => it, + + (Some(a), Some(b)) => cmp::min(a, b), + + (None, None) => { + if pool.options.min_connections > 0 { + crate::rt::spawn(async move { + if let Some(pool) = pool_weak.upgrade() { + pool.min_connections_maintenance(None).await; + } + }); + } + + return; + } + }; + + // Immediately cancel this task if the pool is closed. + let mut close_event = pool.close_event(); + + crate::rt::spawn(async move { + let _ = close_event + .do_until(async { + // If the last handle to the pool was dropped while we were sleeping + while let Some(pool) = pool_weak.upgrade() { + if pool.is_closed() { + return; + } + + let next_run = Instant::now() + period; + + // Go over all idle connections, check for idleness and lifetime, + // and if we have fewer than min_connections after reaping a connection, + // open a new one immediately. Note that other connections may be popped from + // the queue in the meantime - that's fine, there is no harm in checking more + let batch_size = maintenance_batch_size( + pool.num_idle(), + pool.options.max_connections as usize, + ); + for _ in 0..batch_size { + if let Some(conn) = pool.try_acquire() { + if is_beyond_idle_timeout(&conn, &pool.options) + || is_beyond_max_lifetime(&conn, &pool.options) + { + let _ = conn.close().await; + pool.min_connections_maintenance(Some(next_run)).await; + } else { + pool.release(conn.into_live()); + } + } + } + + // Don't hold a reference to the pool while sleeping. + drop(pool); + + if let Some(duration) = next_run.checked_duration_since(Instant::now()) { + // `async-std` doesn't have a `sleep_until()` + crate::rt::sleep(duration).await; + } else { + // `next_run` is in the past, just yield. + crate::rt::yield_now().await; + } + } + }) + .await; + }); +} + +/// RAII guard returned by `Pool::try_increment_size()` and others. +/// +/// Will decrement the pool size if dropped, to avoid semantically "leaking" connections +/// (where the pool thinks it has more connections than it does). +pub(in crate::pool) struct DecrementSizeGuard { + pub(crate) pool: Arc>, + cancelled: bool, +} + +impl DecrementSizeGuard { + /// Create a new guard that will release a semaphore permit on-drop. + pub fn new_permit(pool: Arc>) -> Self { + Self { + pool, + cancelled: false, + } + } + + pub fn from_permit(pool: Arc>, permit: AsyncSemaphoreReleaser<'_>) -> Self { + // here we effectively take ownership of the permit + permit.disarm(); + Self::new_permit(pool) + } + + /// Release the semaphore permit without decreasing the pool size. + /// + /// If the permit was stolen from the pool's parent, it will be returned to the child's semaphore. + fn release_permit(self) { + self.pool.semaphore.release(1); + self.cancel(); + } + + pub fn cancel(mut self) { + self.cancelled = true; + } +} + +impl Drop for DecrementSizeGuard { + fn drop(&mut self) { + if !self.cancelled { + self.pool.size.fetch_sub(1, Ordering::AcqRel); + + // and here we release the permit we got on construction + self.pool.semaphore.release(1); + } + } +} + +#[cfg(test)] +mod tests { + use super::{maintenance_batch_size, publish_idle_connection}; + use crossbeam_queue::ArrayQueue; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier}; + use std::thread; + + #[test] + fn maintenance_batch_size_bounds_scan_by_capacity() { + let capacity = 8; + + assert_eq!(maintenance_batch_size(0, capacity), 0); + assert_eq!(maintenance_batch_size(1, capacity), 1); + assert_eq!(maintenance_batch_size(capacity, capacity), capacity); + assert_eq!(maintenance_batch_size(capacity + 1, capacity), capacity); + assert_eq!(maintenance_batch_size(usize::MAX, capacity), capacity); + } + + #[test] + fn publish_reserves_idle_counter_before_connection_is_visible() { + const ITEM: usize = 7; + + let queue: Arc> = Arc::new(ArrayQueue::new(4)); + let num_idle = Arc::new(AtomicUsize::new(0)); + let published = Arc::new(Barrier::new(2)); + let popped = Arc::new(Barrier::new(2)); + + let producer = { + let queue = Arc::clone(&queue); + let num_idle = Arc::clone(&num_idle); + let published = Arc::clone(&published); + let popped = Arc::clone(&popped); + thread::spawn(move || { + publish_idle_connection(num_idle.as_ref(), move || { + queue + .push(ITEM) + .expect("queue accepts published connection"); + // The consumer can only pop once the connection is queued. + published.wait(); + // Keep the closure open until the concurrent pop has happened so the + // counter is observed at the exact moment the connection was visible. + popped.wait(); + Ok::<(), ()>(()) + }) + .expect("publication succeeds"); + }) + }; + + let consumer = { + let queue = Arc::clone(&queue); + let num_idle = Arc::clone(&num_idle); + let published = Arc::clone(&published); + let popped = Arc::clone(&popped); + thread::spawn(move || { + published.wait(); + let item = queue.pop().expect("published connection is visible"); + let previous = num_idle.fetch_sub(1, Ordering::AcqRel); + // Do not assert here: on the buggy ordering the producer would still be + // waiting for this barrier and an early panic would deadlock the test. + popped.wait(); + (item, previous) + }) + }; + + let (item, previous) = consumer.join().expect("consumer does not panic"); + producer.join().expect("producer does not panic"); + + assert_eq!(item, ITEM); + assert!( + previous > 0, + "idle counter must be reserved before the connection is visible, saw {previous}" + ); + assert_eq!( + previous, 1, + "a single publication must reserve exactly one idle slot" + ); + assert_eq!( + num_idle.load(Ordering::Acquire), + 0, + "idle counter must settle back to zero" + ); + } + + #[test] + fn publish_rolls_back_idle_counter_when_publication_fails() { + // Production `release()` returns the rejected `Idle` as the error of + // this callback; a string error exercises the same helper contract + // without constructing a database connection. + let num_idle = AtomicUsize::new(0); + + let result: Result<(), &'static str> = + publish_idle_connection(&num_idle, || Err("publish failed")); + + assert_eq!(result, Err("publish failed")); + assert_eq!( + num_idle.load(Ordering::Acquire), + 0, + "failed publication must not leak an idle slot" + ); + } +} diff --git a/vendor/sqlx-core/src/pool/maybe.rs b/vendor/sqlx-core/src/pool/maybe.rs new file mode 100755 index 0000000..71a4872 --- /dev/null +++ b/vendor/sqlx-core/src/pool/maybe.rs @@ -0,0 +1,43 @@ +use crate::database::Database; +use crate::pool::PoolConnection; +use std::ops::{Deref, DerefMut}; + +pub enum MaybePoolConnection<'c, DB: Database> { + #[allow(dead_code)] + Connection(&'c mut DB::Connection), + PoolConnection(PoolConnection), +} + +impl Deref for MaybePoolConnection<'_, DB> { + type Target = DB::Connection; + + #[inline] + fn deref(&self) -> &Self::Target { + match self { + MaybePoolConnection::Connection(v) => v, + MaybePoolConnection::PoolConnection(v) => v, + } + } +} + +impl DerefMut for MaybePoolConnection<'_, DB> { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + match self { + MaybePoolConnection::Connection(v) => v, + MaybePoolConnection::PoolConnection(v) => v, + } + } +} + +impl From> for MaybePoolConnection<'_, DB> { + fn from(v: PoolConnection) -> Self { + MaybePoolConnection::PoolConnection(v) + } +} + +impl<'c, DB: Database> From<&'c mut DB::Connection> for MaybePoolConnection<'c, DB> { + fn from(v: &'c mut DB::Connection) -> Self { + MaybePoolConnection::Connection(v) + } +} diff --git a/vendor/sqlx-core/src/pool/mod.rs b/vendor/sqlx-core/src/pool/mod.rs new file mode 100755 index 0000000..f11ff1d --- /dev/null +++ b/vendor/sqlx-core/src/pool/mod.rs @@ -0,0 +1,668 @@ +//! Provides the connection pool for asynchronous SQLx connections. +//! +//! Opening a database connection for each and every operation to the database can quickly +//! become expensive. Furthermore, sharing a database connection between threads and functions +//! can be difficult to express in Rust. +//! +//! A connection pool is a standard technique that can manage opening and re-using connections. +//! Normally it also enforces a maximum number of connections as these are an expensive resource +//! on the database server. +//! +//! SQLx provides a canonical connection pool implementation intended to satisfy the majority +//! of use cases. +//! +//! See [Pool] for details. +//! +//! Type aliases are provided for each database to make it easier to sprinkle `Pool` through +//! your codebase: +//! +//! * [MssqlPool][crate::mssql::MssqlPool] (MSSQL) +//! * [MySqlPool][crate::mysql::MySqlPool] (MySQL) +//! * [PgPool][crate::postgres::PgPool] (PostgreSQL) +//! * [SqlitePool][crate::sqlite::SqlitePool] (SQLite) +//! +//! # Opening a connection pool +//! +//! A new connection pool with a default configuration can be created by supplying `Pool` +//! with the database driver and a connection string. +//! +//! ```rust,ignore +//! use sqlx::Pool; +//! use sqlx::postgres::Postgres; +//! +//! let pool = Pool::::connect("postgres://").await?; +//! ``` +//! +//! For convenience, database-specific type aliases are provided: +//! +//! ```rust,ignore +//! use sqlx::mssql::MssqlPool; +//! +//! let pool = MssqlPool::connect("mssql://").await?; +//! ``` +//! +//! # Using a connection pool +//! +//! A connection pool implements [`Executor`][crate::executor::Executor] and can be used directly +//! when executing a query. Notice that only an immutable reference (`&Pool`) is needed. +//! +//! ```rust,ignore +//! sqlx::query("DELETE FROM articles").execute(&pool).await?; +//! ``` +//! +//! A connection or transaction may also be manually acquired with +//! [`Pool::acquire`] or +//! [`Pool::begin`]. + +use std::fmt; +use std::future::Future; +use std::pin::{pin, Pin}; +use std::sync::Arc; +use std::task::{ready, Context, Poll}; +use std::time::{Duration, Instant}; + +use event_listener::EventListener; +use futures_core::FusedFuture; +use futures_util::FutureExt; + +use crate::connection::Connection; +use crate::database::Database; +use crate::error::Error; +use crate::sql_str::SqlSafeStr; +use crate::transaction::Transaction; + +pub use self::connection::PoolConnection; +use self::inner::PoolInner; +#[doc(hidden)] +pub use self::maybe::MaybePoolConnection; +pub use self::options::{PoolConnectionMetadata, PoolOptions}; + +#[macro_use] +mod executor; + +#[macro_use] +pub mod maybe; + +mod connection; +mod inner; +mod options; + +/// An asynchronous pool of SQLx database connections. +/// +/// Create a pool with [Pool::connect] or [Pool::connect_with] and then call [Pool::acquire] +/// to get a connection from the pool; when the connection is dropped it will return to the pool +/// so it can be reused. +/// +/// You can also pass `&Pool` directly anywhere an `Executor` is required; this will automatically +/// checkout a connection for you. +/// +/// See [the module documentation](crate::pool) for examples. +/// +/// The pool has a maximum connection limit that it will not exceed; if `acquire()` is called +/// when at this limit and all connections are checked out, the task will be made to wait until +/// a connection becomes available. +/// +/// You can configure the connection limit, and other parameters, using [PoolOptions]. +/// +/// Calls to `acquire()` are fair, i.e. fulfilled on a first-come, first-serve basis. +/// +/// `Pool` is `Send`, `Sync` and `Clone`. It is intended to be created once at the start of your +/// application/daemon/web server/etc. and then shared with all tasks throughout the process' +/// lifetime. How best to accomplish this depends on your program architecture. +/// +/// In Actix-Web, for example, you can efficiently share a single pool with all request handlers +/// using [web::ThinData]. +/// +/// Cloning `Pool` is cheap as it is simply a reference-counted handle to the inner pool state. +/// When the last remaining handle to the pool is dropped, the connections owned by the pool are +/// immediately closed (also by dropping). `PoolConnection` returned by [Pool::acquire] and +/// `Transaction` returned by [Pool::begin] both implicitly hold a reference to the pool for +/// their lifetimes. +/// +/// If you prefer to explicitly shutdown the pool and gracefully close its connections (which +/// depending on the database type, may include sending a message to the database server that the +/// connection is being closed), you can call [Pool::close] which causes all waiting and subsequent +/// calls to [Pool::acquire] to return [Error::PoolClosed], and waits until all connections have +/// been returned to the pool and gracefully closed. +/// +/// Type aliases are provided for each database to make it easier to sprinkle `Pool` through +/// your codebase: +/// +/// * [MssqlPool][crate::mssql::MssqlPool] (MSSQL) +/// * [MySqlPool][crate::mysql::MySqlPool] (MySQL) +/// * [PgPool][crate::postgres::PgPool] (PostgreSQL) +/// * [SqlitePool][crate::sqlite::SqlitePool] (SQLite) +/// +/// [web::ThinData]: https://docs.rs/actix-web/4.9.0/actix_web/web/struct.ThinData.html +/// +/// ### Note: Drop Behavior +/// Due to a lack of async `Drop`, dropping the last `Pool` handle may not immediately clean +/// up connections by itself. The connections will be dropped locally, which is sufficient for +/// SQLite, but for client/server databases like MySQL and Postgres, that only closes the +/// client side of the connection. The server will not know the connection is closed until +/// potentially much later: this is usually dictated by the TCP keepalive timeout in the server +/// settings. +/// +/// Because the connection may not be cleaned up immediately on the server side, you may run +/// into errors regarding connection limits if you are creating and dropping many pools in short +/// order. +/// +/// We recommend calling [`.close().await`] to gracefully close the pool and its connections +/// when you are done using it. This will also wake any tasks that are waiting on an `.acquire()` +/// call, so for long-lived applications it's a good idea to call `.close()` during shutdown. +/// +/// If you're writing tests, consider using `#[sqlx::test]` which handles the lifetime of +/// the pool for you. +/// +/// [`.close().await`]: Pool::close +/// +/// ### Why Use a Pool? +/// +/// A single database connection (in general) cannot be used by multiple threads simultaneously +/// for various reasons, but an application or web server will typically need to execute numerous +/// queries or commands concurrently (think of concurrent requests against a web server; many or all +/// of them will probably need to hit the database). +/// +/// You could place the connection in a `Mutex` but this will make it a huge bottleneck. +/// +/// Naively, you might also think to just open a new connection per request, but this +/// has a number of other caveats, generally due to the high overhead involved in working with +/// a fresh connection. Examples to follow. +/// +/// Connection pools facilitate reuse of connections to _amortize_ these costs, helping to ensure +/// that you're not paying for them each time you need a connection. +/// +/// ##### 1. Overhead of Opening a Connection +/// Opening a database connection is not exactly a cheap operation. +/// +/// For SQLite, it means numerous requests to the filesystem and memory allocations, while for +/// server-based databases it involves performing DNS resolution, opening a new TCP connection and +/// allocating buffers. +/// +/// Each connection involves a nontrivial allocation of resources for the database server, usually +/// including spawning a new thread or process specifically to handle the connection, both for +/// concurrency and isolation of faults. +/// +/// Additionally, database connections typically involve a complex handshake including +/// authentication, negotiation regarding connection parameters (default character sets, timezones, +/// locales, supported features) and upgrades to encrypted tunnels. +/// +/// If `acquire()` is called on a pool with all connections checked out but it is not yet at its +/// connection limit (see next section), then a new connection is immediately opened, so this pool +/// does not _automatically_ save you from the overhead of creating a new connection. +/// +/// However, because this pool by design enforces _reuse_ of connections, this overhead cost +/// is not paid each and every time you need a connection. In fact, if you set +/// [the `min_connections` option in PoolOptions][PoolOptions::min_connections], the pool will +/// create that many connections up-front so that they are ready to go when a request comes in, +/// and maintain that number on a best-effort basis for consistent performance. +/// +/// ##### 2. Connection Limits (MySQL, MSSQL, Postgres) +/// Database servers usually place hard limits on the number of connections that are allowed open at +/// any given time, to maintain performance targets and prevent excessive allocation of resources, +/// such as RAM, journal files, disk caches, etc. +/// +/// These limits have different defaults per database flavor, and may vary between different +/// distributions of the same database, but are typically configurable on server start; +/// if you're paying for managed database hosting then the connection limit will typically vary with +/// your pricing tier. +/// +/// In MySQL, the default limit is typically 150, plus 1 which is reserved for a user with the +/// `CONNECTION_ADMIN` privilege so you can still access the server to diagnose problems even +/// with all connections being used. +/// +/// In MSSQL the only documentation for the default maximum limit is that it depends on the version +/// and server configuration. +/// +/// In Postgres, the default limit is typically 100, minus 3 which are reserved for superusers +/// (putting the default limit for unprivileged users at 97 connections). +/// +/// In any case, exceeding these limits results in an error when opening a new connection, which +/// in a web server context will turn into a `500 Internal Server Error` if not handled, but should +/// be turned into either `403 Forbidden` or `429 Too Many Requests` depending on your rate-limiting +/// scheme. However, in a web context, telling a client "go away, maybe try again later" results in +/// a sub-optimal user experience. +/// +/// Instead, with a connection pool, clients are made to wait in a fair queue for a connection to +/// become available; by using a single connection pool for your whole application, you can ensure +/// that you don't exceed the connection limit of your database server while allowing response +/// time to degrade gracefully at high load. +/// +/// Of course, if multiple applications are connecting to the same database server, then you +/// should ensure that the connection limits for all applications add up to your server's maximum +/// connections or less. +/// +/// ##### 3. Resource Reuse +/// The first time you execute a query against your database, the database engine must first turn +/// the SQL into an actionable _query plan_ which it may then execute against the database. This +/// involves parsing the SQL query, validating and analyzing it, and in the case of Postgres 12+ and +/// SQLite, generating code to execute the query plan (native or bytecode, respectively). +/// +/// These database servers provide a way to amortize this overhead by _preparing_ the query, +/// associating it with an object ID and placing its query plan in a cache to be referenced when +/// it is later executed. +/// +/// Prepared statements have other features, like bind parameters, which make them safer and more +/// ergonomic to use as well. By design, SQLx pushes you towards using prepared queries/statements +/// via the [Query][crate::query::Query] API _et al._ and the `query!()` macro _et al._, for +/// reasons of safety, ergonomics, and efficiency. +/// +/// However, because database connections are typically isolated from each other in the database +/// server (either by threads or separate processes entirely), they don't typically share prepared +/// statements between connections so this work must be redone _for each connection_. +/// +/// As with section 1, by facilitating reuse of connections, `Pool` helps to ensure their prepared +/// statements (and thus cached query plans) can be reused as much as possible, thus amortizing +/// the overhead involved. +/// +/// Depending on the database server, a connection will have caches for all kinds of other data as +/// well and queries will generally benefit from these caches being "warm" (populated with data). +pub struct Pool(pub(crate) Arc>); + +/// A future that resolves when the pool is closed. +/// +/// See [`Pool::close_event()`] for details. +pub struct CloseEvent { + listener: Option, +} + +impl Pool { + /// Create a new connection pool with a default pool configuration and + /// the given connection URL, and immediately establish one connection. + /// + /// Refer to the relevant `ConnectOptions` impl for your database for the expected URL format: + /// + /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions] + /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions] + /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions] + /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions] + /// + /// The default configuration is mainly suited for testing and light-duty applications. + /// For production applications, you'll likely want to make at least few tweaks. + /// + /// See [`PoolOptions::new()`] for details. + pub async fn connect(url: &str) -> Result { + PoolOptions::::new().connect(url).await + } + + /// Create a new connection pool with a default pool configuration and + /// the given `ConnectOptions`, and immediately establish one connection. + /// + /// The default configuration is mainly suited for testing and light-duty applications. + /// For production applications, you'll likely want to make at least few tweaks. + /// + /// See [`PoolOptions::new()`] for details. + pub async fn connect_with( + options: ::Options, + ) -> Result { + PoolOptions::::new().connect_with(options).await + } + + /// Create a new connection pool with a default pool configuration and + /// the given connection URL. + /// + /// The pool will establish connections only as needed. + /// + /// Refer to the relevant [`ConnectOptions`][crate::connection::ConnectOptions] impl for your database for the expected URL format: + /// + /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions] + /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions] + /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions] + /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions] + /// + /// The default configuration is mainly suited for testing and light-duty applications. + /// For production applications, you'll likely want to make at least few tweaks. + /// + /// See [`PoolOptions::new()`] for details. + pub fn connect_lazy(url: &str) -> Result { + PoolOptions::::new().connect_lazy(url) + } + + /// Create a new connection pool with a default pool configuration and + /// the given `ConnectOptions`. + /// + /// The pool will establish connections only as needed. + /// + /// The default configuration is mainly suited for testing and light-duty applications. + /// For production applications, you'll likely want to make at least few tweaks. + /// + /// See [`PoolOptions::new()`] for details. + pub fn connect_lazy_with(options: ::Options) -> Self { + PoolOptions::::new().connect_lazy_with(options) + } + + /// Retrieves a connection from the pool. + /// + /// The total time this method is allowed to execute is capped by + /// [`PoolOptions::acquire_timeout`]. + /// If that timeout elapses, this will return [`Error::PoolClosed`]. + /// + /// ### Note: Cancellation/Timeout May Drop Connections + /// If `acquire` is cancelled or times out after it acquires a connection from the idle queue or + /// opens a new one, it will drop that connection because we don't want to assume it + /// is safe to return to the pool, and testing it to see if it's safe to release could introduce + /// subtle bugs if not implemented correctly. To avoid that entirely, we've decided to not + /// gracefully handle cancellation here. + /// + /// However, if your workload is sensitive to dropped connections such as using an in-memory + /// SQLite database with a pool size of 1, you can pretty easily ensure that a cancelled + /// `acquire()` call will never drop connections by tweaking your [`PoolOptions`]: + /// + /// * Set [`test_before_acquire(false)`][PoolOptions::test_before_acquire] + /// * Never set [`before_acquire`][PoolOptions::before_acquire] or + /// [`after_connect`][PoolOptions::after_connect]. + /// + /// This should eliminate any potential `.await` points between acquiring a connection and + /// returning it. + pub fn acquire(&self) -> impl Future, Error>> + 'static { + let shared = self.0.clone(); + async move { shared.acquire().await.map(|conn| conn.reattach()) } + } + + /// Attempts to retrieve a connection from the pool if there is one available. + /// + /// Returns `None` immediately if there are no idle connections available in the pool + /// or there are tasks waiting for a connection which have yet to wake. + pub fn try_acquire(&self) -> Option> { + self.0.try_acquire().map(|conn| conn.into_live().reattach()) + } + + /// Retrieves a connection and immediately begins a new transaction. + pub async fn begin(&self) -> Result, Error> { + Transaction::begin( + MaybePoolConnection::PoolConnection(self.acquire().await?), + None, + ) + .await + } + + /// Attempts to retrieve a connection and immediately begins a new transaction if successful. + pub async fn try_begin(&self) -> Result>, Error> { + match self.try_acquire() { + Some(conn) => Transaction::begin(MaybePoolConnection::PoolConnection(conn), None) + .await + .map(Some), + + None => Ok(None), + } + } + + /// Retrieves a connection and immediately begins a new transaction using `statement`. + pub async fn begin_with( + &self, + statement: impl SqlSafeStr, + ) -> Result, Error> { + Transaction::begin( + MaybePoolConnection::PoolConnection(self.acquire().await?), + Some(statement.into_sql_str()), + ) + .await + } + + /// Attempts to retrieve a connection and, if successful, immediately begins a new + /// transaction using `statement`. + pub async fn try_begin_with( + &self, + statement: impl SqlSafeStr, + ) -> Result>, Error> { + match self.try_acquire() { + Some(conn) => Transaction::begin( + MaybePoolConnection::PoolConnection(conn), + Some(statement.into_sql_str()), + ) + .await + .map(Some), + + None => Ok(None), + } + } + + /// Shut down the connection pool, immediately waking all tasks waiting for a connection. + /// + /// Upon calling this method, any currently waiting or subsequent calls to [`Pool::acquire`] and + /// the like will immediately return [`Error::PoolClosed`] and no new connections will be opened. + /// Checked-out connections are unaffected, but will be gracefully closed on-drop + /// rather than being returned to the pool. + /// + /// Returns a `Future` which can be `.await`ed to ensure all connections are + /// gracefully closed. It will first close any idle connections currently waiting in the pool, + /// then wait for all checked-out connections to be returned or closed. + /// + /// Waiting for connections to be gracefully closed is optional, but will allow the database + /// server to clean up the resources sooner rather than later. This is especially important + /// for tests that create a new pool every time, otherwise you may see errors about connection + /// limits being exhausted even when running tests in a single thread. + /// + /// If the returned `Future` is not run to completion, any remaining connections will be dropped + /// when the last handle for the given pool instance is dropped, which could happen in a task + /// spawned by `Pool` internally and so may be unpredictable otherwise. + /// + /// `.close()` may be safely called and `.await`ed on multiple handles concurrently. + pub fn close(&self) -> impl Future + '_ { + self.0.close() + } + + /// Returns `true` if [`.close()`][Pool::close] has been called on the pool, `false` otherwise. + pub fn is_closed(&self) -> bool { + self.0.is_closed() + } + + /// Get a future that resolves when [`Pool::close()`] is called. + /// + /// If the pool is already closed, the future resolves immediately. + /// + /// This can be used to cancel long-running operations that hold onto a [`PoolConnection`] + /// so they don't prevent the pool from closing (which would otherwise wait until all + /// connections are returned). + /// + /// Examples + /// ======== + /// These examples use Postgres and Tokio, but should suffice to demonstrate the concept. + /// + /// Do something when the pool is closed: + /// ```rust,no_run + /// # async fn bleh() -> sqlx::Result<()> { + /// use sqlx::PgPool; + /// + /// let pool = PgPool::connect("postgresql://...").await?; + /// + /// let pool2 = pool.clone(); + /// + /// tokio::spawn(async move { + /// // Demonstrates that `CloseEvent` is itself a `Future` you can wait on. + /// // This lets you implement any kind of on-close event that you like. + /// pool2.close_event().await; + /// + /// println!("Pool is closing!"); + /// + /// // Imagine maybe recording application statistics or logging a report, etc. + /// }); + /// + /// // The rest of the application executes normally... + /// + /// // Close the pool before the application exits... + /// pool.close().await; + /// + /// # Ok(()) + /// # } + /// ``` + /// + /// Cancel a long-running operation: + /// ```rust,no_run + /// # async fn bleh() -> sqlx::Result<()> { + /// use sqlx::{Executor, PgPool}; + /// + /// let pool = PgPool::connect("postgresql://...").await?; + /// + /// let pool2 = pool.clone(); + /// + /// tokio::spawn(async move { + /// // `do_until` yields the inner future's output wrapped in `sqlx::Result`, + /// // in this case giving a double-wrapped result. + /// let res: sqlx::Result> = pool2.close_event().do_until(async { + /// // This statement normally won't return for 30 days! + /// // (Assuming the connection doesn't time out first, of course.) + /// pool2.execute("SELECT pg_sleep('30 days')").await?; + /// + /// // If the pool is closed before the statement completes, this won't be printed. + /// // This is because `.do_until()` cancels the future it's given if the + /// // pool is closed first. + /// println!("Waited!"); + /// + /// Ok(()) + /// }).await; + /// + /// match res { + /// Ok(Ok(())) => println!("Wait succeeded"), + /// Ok(Err(e)) => println!("Error from inside do_until: {e:?}"), + /// Err(e) => println!("Error from do_until: {e:?}"), + /// } + /// }); + /// + /// // This normally wouldn't return until the above statement completed and the connection + /// // was returned to the pool. However, thanks to `.do_until()`, the operation was + /// // cancelled as soon as we called `.close().await`. + /// pool.close().await; + /// + /// # Ok(()) + /// # } + /// ``` + pub fn close_event(&self) -> CloseEvent { + self.0.close_event() + } + + /// Returns the number of connections currently active. This includes idle connections. + pub fn size(&self) -> u32 { + self.0.size() + } + + /// Returns the number of connections active and idle (not in use). + pub fn num_idle(&self) -> usize { + self.0.num_idle() + } + + /// Gets a clone of the connection options for this pool + pub fn connect_options(&self) -> Arc<::Options> { + self.0 + .connect_options + .read() + .expect("write-lock holder panicked") + .clone() + } + + /// Updates the connection options this pool will use when opening any future connections. Any + /// existing open connection in the pool will be left as-is. + pub fn set_connect_options(&self, connect_options: ::Options) { + // technically write() could also panic if the current thread already holds the lock, + // but because this method can't be re-entered by the same thread that shouldn't be a problem + let mut guard = self + .0 + .connect_options + .write() + .expect("write-lock holder panicked"); + *guard = Arc::new(connect_options); + } + + /// Get the options for this pool + pub fn options(&self) -> &PoolOptions { + &self.0.options + } +} + +/// Returns a new [Pool] tied to the same shared connection pool. +impl Clone for Pool { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl fmt::Debug for Pool { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt.debug_struct("Pool") + .field("size", &self.0.size()) + .field("num_idle", &self.0.num_idle()) + .field("is_closed", &self.0.is_closed()) + .field("options", &self.0.options) + .finish() + } +} + +impl CloseEvent { + /// Execute the given future until it returns or the pool is closed. + /// + /// Cancels the future and returns `Err(PoolClosed)` if/when the pool is closed. + /// If the pool was already closed, the future is never run. + pub async fn do_until(&mut self, fut: Fut) -> Result { + // Check that the pool wasn't closed already. + // + // We use `poll_immediate()` as it will use the correct waker instead of + // a no-op one like `.now_or_never()`, but it won't actually suspend execution here. + futures_util::future::poll_immediate(&mut *self) + .await + .map_or(Ok(()), |_| Err(Error::PoolClosed))?; + + let mut fut = pin!(fut); + + // I find that this is clearer in intent than `futures_util::future::select()` + // or `futures_util::select_biased!{}` (which isn't enabled anyway). + std::future::poll_fn(|cx| { + // Poll `fut` first as the wakeup event is more likely for it than `self`. + if let Poll::Ready(ret) = fut.as_mut().poll(cx) { + return Poll::Ready(Ok(ret)); + } + + // Can't really factor out mapping to `Err(Error::PoolClosed)` though it seems like + // we should because that results in a different `Ok` type each time. + // + // Ideally we'd map to something like `Result` but using `!` as a type + // is not allowed on stable Rust yet. + self.poll_unpin(cx).map(|_| Err(Error::PoolClosed)) + }) + .await + } +} + +impl Future for CloseEvent { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if let Some(listener) = &mut self.listener { + ready!(listener.poll_unpin(cx)); + } + + // `EventListener` doesn't like being polled after it yields, and even if it did it + // would probably just wait for the next event, neither of which we want. + // + // So this way, once we get our close event, we fuse this future to immediately return. + self.listener = None; + + Poll::Ready(()) + } +} + +impl FusedFuture for CloseEvent { + fn is_terminated(&self) -> bool { + self.listener.is_none() + } +} + +/// get the time between the deadline and now and use that as our timeout +/// +/// returns `Error::PoolTimedOut` if the deadline is in the past +fn deadline_as_timeout(deadline: Instant) -> Result { + deadline + .checked_duration_since(Instant::now()) + .ok_or(Error::PoolTimedOut) +} + +#[test] +#[allow(dead_code)] +fn assert_pool_traits() { + fn assert_send_sync() {} + fn assert_clone() {} + + fn assert_pool() { + assert_send_sync::>(); + assert_clone::>(); + } +} diff --git a/vendor/sqlx-core/src/pool/options.rs b/vendor/sqlx-core/src/pool/options.rs new file mode 100755 index 0000000..3d048f1 --- /dev/null +++ b/vendor/sqlx-core/src/pool/options.rs @@ -0,0 +1,596 @@ +use crate::connection::Connection; +use crate::database::Database; +use crate::error::Error; +use crate::pool::inner::PoolInner; +use crate::pool::Pool; +use futures_core::future::BoxFuture; +use log::LevelFilter; +use std::fmt::{self, Debug, Formatter}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// Configuration options for [`Pool`][super::Pool]. +/// +/// ### Callback Functions: Why Do I Need `Box::pin()`? +/// Essentially, because it's impossible to write generic bounds that describe a closure +/// with a higher-ranked lifetime parameter, returning a future with that same lifetime. +/// +/// Ideally, you could define it like this: +/// ```rust,ignore +/// async fn takes_foo_callback(f: impl for<'a> Fn(&'a mut Foo) -> impl Future<'a, Output = ()>) +/// ``` +/// +/// However, the compiler does not allow using `impl Trait` in the return type of an `impl Fn`. +/// +/// And if you try to do it like this: +/// ```rust,ignore +/// async fn takes_foo_callback(f: F) +/// where +/// F: for<'a> Fn(&'a mut Foo) -> Fut, +/// Fut: for<'a> Future + 'a +/// ``` +/// +/// There's no way to tell the compiler that those two `'a`s should be the same lifetime. +/// +/// It's possible to make this work with a custom trait, but it's fiddly and requires naming +/// the type of the closure parameter. +/// +/// Having the closure return `BoxFuture` allows us to work around this, as all the type information +/// fits into a single generic parameter. +/// +/// We still need to `Box` the future internally to give it a concrete type to avoid leaking a type +/// parameter everywhere, and `Box` is in the prelude so it doesn't need to be manually imported, +/// so having the closure return `Pin` directly is the path of least resistance from +/// the perspectives of both API designer and consumer. +pub struct PoolOptions { + pub(crate) test_before_acquire: bool, + pub(crate) after_connect: Option< + Arc< + dyn Fn(&mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'_, Result<(), Error>> + + 'static + + Send + + Sync, + >, + >, + pub(crate) before_acquire: Option< + Arc< + dyn Fn( + &mut DB::Connection, + PoolConnectionMetadata, + ) -> BoxFuture<'_, Result> + + 'static + + Send + + Sync, + >, + >, + pub(crate) after_release: Option< + Arc< + dyn Fn( + &mut DB::Connection, + PoolConnectionMetadata, + ) -> BoxFuture<'_, Result> + + 'static + + Send + + Sync, + >, + >, + pub(crate) max_connections: u32, + pub(crate) acquire_time_level: LevelFilter, + pub(crate) acquire_slow_level: LevelFilter, + pub(crate) acquire_slow_threshold: Duration, + pub(crate) acquire_timeout: Duration, + pub(crate) min_connections: u32, + pub(crate) max_lifetime: Option, + pub(crate) idle_timeout: Option, + pub(crate) fair: bool, + + pub(crate) parent_pool: Option>, +} + +// Manually implement `Clone` to avoid a trait bound issue. +// +// See: https://github.com/launchbadge/sqlx/issues/2548 +impl Clone for PoolOptions { + fn clone(&self) -> Self { + PoolOptions { + test_before_acquire: self.test_before_acquire, + after_connect: self.after_connect.clone(), + before_acquire: self.before_acquire.clone(), + after_release: self.after_release.clone(), + max_connections: self.max_connections, + acquire_time_level: self.acquire_time_level, + acquire_slow_threshold: self.acquire_slow_threshold, + acquire_slow_level: self.acquire_slow_level, + acquire_timeout: self.acquire_timeout, + min_connections: self.min_connections, + max_lifetime: self.max_lifetime, + idle_timeout: self.idle_timeout, + fair: self.fair, + parent_pool: self.parent_pool.clone(), + } + } +} + +/// Metadata for the connection being processed by a [`PoolOptions`] callback. +#[derive(Debug)] // Don't want to commit to any other trait impls yet. +#[non_exhaustive] // So we can safely add fields in the future. +pub struct PoolConnectionMetadata { + /// The duration since the connection was first opened. + /// + /// For [`after_connect`][PoolOptions::after_connect], this is [`Duration::ZERO`]. + pub age: Duration, + + /// The duration that the connection spent in the idle queue. + /// + /// Only relevant for [`before_acquire`][PoolOptions::before_acquire]. + /// For other callbacks, this is [`Duration::ZERO`]. + pub idle_for: Duration, +} + +impl Default for PoolOptions { + fn default() -> Self { + Self::new() + } +} + +impl PoolOptions { + /// Returns a default "sane" configuration, suitable for testing or light-duty applications. + /// + /// Production applications will likely want to at least modify + /// [`max_connections`][Self::max_connections]. + /// + /// See the source of this method for the current default values. + pub fn new() -> Self { + Self { + // User-specifiable routines + after_connect: None, + before_acquire: None, + after_release: None, + test_before_acquire: true, + // A production application will want to set a higher limit than this. + max_connections: 10, + min_connections: 0, + // Logging all acquires is opt-in + acquire_time_level: LevelFilter::Off, + // Default to warning, because an acquire timeout will be an error + acquire_slow_level: LevelFilter::Warn, + // Fast enough to catch problems (e.g. a full pool); slow enough + // to not flag typical time to add a new connection to a pool. + acquire_slow_threshold: Duration::from_secs(2), + acquire_timeout: Duration::from_secs(30), + idle_timeout: Some(Duration::from_secs(10 * 60)), + max_lifetime: Some(Duration::from_secs(30 * 60)), + fair: true, + parent_pool: None, + } + } + + /// Set the maximum number of connections that this pool should maintain. + /// + /// Be mindful of the connection limits for your database as well as other applications + /// which may want to connect to the same database (or even multiple instances of the same + /// application in high-availability deployments). + pub fn max_connections(mut self, max: u32) -> Self { + self.max_connections = max; + self + } + + /// Get the maximum number of connections that this pool should maintain + pub fn get_max_connections(&self) -> u32 { + self.max_connections + } + + /// Set the minimum number of connections to maintain at all times. + /// + /// When the pool is built, this many connections will be automatically spun up. + /// + /// If any connection is reaped by [`max_lifetime`] or [`idle_timeout`], or explicitly closed, + /// and it brings the connection count below this amount, a new connection will be opened to + /// replace it. + /// + /// This is only done on a best-effort basis, however. The routine that maintains this value + /// has a deadline so it doesn't wait forever if the database is being slow or returning errors. + /// + /// This value is clamped internally to not exceed [`max_connections`]. + /// + /// We've chosen not to assert `min_connections <= max_connections` anywhere + /// because it shouldn't break anything internally if the condition doesn't hold, + /// and if the application allows either value to be dynamically set + /// then it should be checking this condition itself and returning + /// a nicer error than a panic anyway. + /// + /// [`max_lifetime`]: Self::max_lifetime + /// [`idle_timeout`]: Self::idle_timeout + /// [`max_connections`]: Self::max_connections + pub fn min_connections(mut self, min: u32) -> Self { + self.min_connections = min; + self + } + + /// Get the minimum number of connections to maintain at all times. + pub fn get_min_connections(&self) -> u32 { + self.min_connections + } + + /// Enable logging of time taken to acquire a connection from the connection pool via + /// [`Pool::acquire()`]. + /// + /// If slow acquire logging is also enabled, this level is used for acquires that are not + /// considered slow. + pub fn acquire_time_level(mut self, level: LevelFilter) -> Self { + self.acquire_time_level = level; + self + } + + /// Log excessive time taken to acquire a connection at a different log level than time taken + /// for faster connection acquires via [`Pool::acquire()`]. + pub fn acquire_slow_level(mut self, level: LevelFilter) -> Self { + self.acquire_slow_level = level; + self + } + + /// Set a threshold for reporting excessive time taken to acquire a connection from + /// the connection pool via [`Pool::acquire()`]. When the threshold is exceeded, a warning is logged. + /// + /// Defaults to a value that should not typically be exceeded by the pool enlarging + /// itself with an additional new connection. + pub fn acquire_slow_threshold(mut self, threshold: Duration) -> Self { + self.acquire_slow_threshold = threshold; + self + } + + /// Get the threshold for reporting excessive time taken to acquire a connection via + /// [`Pool::acquire()`]. + pub fn get_acquire_slow_threshold(&self) -> Duration { + self.acquire_slow_threshold + } + + /// Set the maximum amount of time to spend waiting for a connection in [`Pool::acquire()`]. + /// + /// Caps the total amount of time `Pool::acquire()` can spend waiting across multiple phases: + /// + /// * First, it may need to wait for a permit from the semaphore, which grants it the privilege + /// of opening a connection or popping one from the idle queue. + /// * If an existing idle connection is acquired, by default it will be checked for liveness + /// and integrity before being returned, which may require executing a command on the + /// connection. This can be disabled with [`test_before_acquire(false)`][Self::test_before_acquire]. + /// * If [`before_acquire`][Self::before_acquire] is set, that will also be executed. + /// * If a new connection needs to be opened, that will obviously require I/O, handshaking, + /// and initialization commands. + /// * If [`after_connect`][Self::after_connect] is set, that will also be executed. + pub fn acquire_timeout(mut self, timeout: Duration) -> Self { + self.acquire_timeout = timeout; + self + } + + /// Get the maximum amount of time to spend waiting for a connection in [`Pool::acquire()`]. + pub fn get_acquire_timeout(&self) -> Duration { + self.acquire_timeout + } + + /// Set the maximum lifetime of individual connections. + /// + /// Any connection with a lifetime greater than this will be closed. + /// + /// When set to `None`, all connections live until either reaped by [`idle_timeout`] + /// or explicitly disconnected. + /// + /// Infinite connections are not recommended due to the unfortunate reality of memory/resource + /// leaks on the database-side. It is better to retire connections periodically + /// (even if only once daily) to allow the database the opportunity to clean up data structures + /// (parse trees, query metadata caches, thread-local storage, etc.) that are associated with a + /// session. + /// + /// [`idle_timeout`]: Self::idle_timeout + pub fn max_lifetime(mut self, lifetime: impl Into>) -> Self { + self.max_lifetime = lifetime.into(); + self + } + + /// Get the maximum lifetime of individual connections. + pub fn get_max_lifetime(&self) -> Option { + self.max_lifetime + } + + /// Set a maximum idle duration for individual connections. + /// + /// Any connection that remains in the idle queue longer than this will be closed. + /// + /// For usage-based database server billing, this can be a cost saver. + pub fn idle_timeout(mut self, timeout: impl Into>) -> Self { + self.idle_timeout = timeout.into(); + self + } + + /// Get the maximum idle duration for individual connections. + pub fn get_idle_timeout(&self) -> Option { + self.idle_timeout + } + + /// If true, the health of a connection will be verified by a call to [`Connection::ping`] + /// before returning the connection. + /// + /// Defaults to `true`. + pub fn test_before_acquire(mut self, test: bool) -> Self { + self.test_before_acquire = test; + self + } + + /// Get whether `test_before_acquire` is currently set. + pub fn get_test_before_acquire(&self) -> bool { + self.test_before_acquire + } + + /// If set to `true`, calls to `acquire()` are fair and connections are issued + /// in first-come-first-serve order. If `false`, "drive-by" tasks may steal idle connections + /// ahead of tasks that have been waiting. + /// + /// According to `sqlx-bench/benches/pg_pool` this may slightly increase time + /// to `acquire()` at low pool contention but at very high contention it helps + /// avoid tasks at the head of the waiter queue getting repeatedly preempted by + /// these "drive-by" tasks and tasks further back in the queue timing out because + /// the queue isn't moving. + /// + /// Currently only exposed for benchmarking; `fair = true` seems to be the superior option + /// in most cases. + #[doc(hidden)] + pub fn __fair(mut self, fair: bool) -> Self { + self.fair = fair; + self + } + + /// Perform an asynchronous action after connecting to the database. + /// + /// If the operation returns with an error then the error is logged, the connection is closed + /// and a new one is opened in its place and the callback is invoked again. + /// + /// This occurs in a backoff loop to avoid high CPU usage and spamming logs during a transient + /// error condition. + /// + /// Note that this may be called for internally opened connections, such as when maintaining + /// [`min_connections`][Self::min_connections], that are then immediately returned to the pool + /// without invoking [`after_release`][Self::after_release]. + /// + /// # Example: Additional Parameters + /// This callback may be used to set additional configuration parameters + /// that are not exposed by the database's `ConnectOptions`. + /// + /// This example is written for PostgreSQL but can likely be adapted to other databases. + /// + /// ```no_run + /// # async fn f() -> Result<(), Box> { + /// use sqlx::Executor; + /// use sqlx::postgres::PgPoolOptions; + /// + /// let pool = PgPoolOptions::new() + /// .after_connect(|conn, _meta| Box::pin(async move { + /// // When directly invoking `Executor` methods, + /// // it is possible to execute multiple statements with one call. + /// conn.execute("SET application_name = 'your_app'; SET search_path = 'my_schema';") + /// .await?; + /// + /// Ok(()) + /// })) + /// .connect("postgres:// …").await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// For a discussion on why `Box::pin()` is required, see [the type-level docs][Self]. + pub fn after_connect(mut self, callback: F) -> Self + where + // We're passing the `PoolConnectionMetadata` here mostly for future-proofing. + // `age` and `idle_for` are obviously not useful for fresh connections. + for<'c> F: Fn(&'c mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'c, Result<(), Error>> + + 'static + + Send + + Sync, + { + self.after_connect = Some(Arc::new(callback)); + self + } + + /// Perform an asynchronous action on a previously idle connection before giving it out. + /// + /// Alongside the connection, the closure gets [`PoolConnectionMetadata`] which contains + /// potentially useful information such as the connection's age and the duration it was + /// idle. + /// + /// If the operation returns `Ok(true)`, the connection is returned to the task that called + /// [`Pool::acquire`]. + /// + /// If the operation returns `Ok(false)` or an error, the error is logged (if applicable) + /// and then the connection is closed and [`Pool::acquire`] tries again with another idle + /// connection. If it runs out of idle connections, it opens a new connection instead. + /// + /// This is *not* invoked for new connections. Use [`after_connect`][Self::after_connect] + /// for those. + /// + /// # Example: Custom `test_before_acquire` Logic + /// If you only want to ping connections if they've been idle a certain amount of time, + /// you can implement your own logic here: + /// + /// This example is written for Postgres but should be trivially adaptable to other databases. + /// ```no_run + /// # async fn f() -> Result<(), Box> { + /// use sqlx::{Connection, Executor}; + /// use sqlx::postgres::PgPoolOptions; + /// + /// let pool = PgPoolOptions::new() + /// .test_before_acquire(false) + /// .before_acquire(|conn, meta| Box::pin(async move { + /// // One minute + /// if meta.idle_for.as_secs() > 60 { + /// conn.ping().await?; + /// } + /// + /// Ok(true) + /// })) + /// .connect("postgres:// …").await?; + /// # Ok(()) + /// # } + ///``` + /// + /// For a discussion on why `Box::pin()` is required, see [the type-level docs][Self]. + pub fn before_acquire(mut self, callback: F) -> Self + where + for<'c> F: Fn(&'c mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'c, Result> + + 'static + + Send + + Sync, + { + self.before_acquire = Some(Arc::new(callback)); + self + } + + /// Perform an asynchronous action on a connection before it is returned to the pool. + /// + /// Alongside the connection, the closure gets [`PoolConnectionMetadata`] which contains + /// potentially useful information such as the connection's age. + /// + /// If the operation returns `Ok(true)`, the connection is returned to the pool's idle queue. + /// If the operation returns `Ok(false)` or an error, the error is logged (if applicable) + /// and the connection is closed, allowing a task waiting on [`Pool::acquire`] to + /// open a new one in its place. + /// + /// # Example (Postgres): Close Memory-Hungry Connections + /// Instead of relying on [`max_lifetime`][Self::max_lifetime] to close connections, + /// we can monitor their memory usage directly and close any that have allocated too much. + /// + /// Note that this is purely an example showcasing a possible use for this callback + /// and may be flawed as it has not been tested. + /// + /// This example queries [`pg_backend_memory_contexts`](https://www.postgresql.org/docs/current/view-pg-backend-memory-contexts.html) + /// which is only allowed for superusers. + /// + /// ```no_run + /// # async fn f() -> Result<(), Box> { + /// use sqlx::{Connection, Executor}; + /// use sqlx::postgres::PgPoolOptions; + /// + /// let pool = PgPoolOptions::new() + /// // Let connections live as long as they want. + /// .max_lifetime(None) + /// .after_release(|conn, meta| Box::pin(async move { + /// // Only check connections older than 6 hours. + /// if meta.age.as_secs() < 6 * 60 * 60 { + /// return Ok(true); + /// } + /// + /// let total_memory_usage: i64 = sqlx::query_scalar( + /// "select sum(used_bytes) from pg_backend_memory_contexts" + /// ) + /// .fetch_one(conn) + /// .await?; + /// + /// // Close the connection if the backend memory usage exceeds 256 MiB. + /// Ok(total_memory_usage <= (1 << 28)) + /// })) + /// .connect("postgres:// …").await?; + /// # Ok(()) + /// # } + pub fn after_release(mut self, callback: F) -> Self + where + for<'c> F: Fn(&'c mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'c, Result> + + 'static + + Send + + Sync, + { + self.after_release = Some(Arc::new(callback)); + self + } + + /// Set the parent `Pool` from which the new pool will inherit its semaphore. + /// + /// This is currently an internal-only API. + /// + /// ### Panics + /// If `self.max_connections` is greater than the setting the given pool was created with, + /// or `self.fair` differs from the setting the given pool was created with. + #[doc(hidden)] + pub fn parent(mut self, pool: Pool) -> Self { + self.parent_pool = Some(pool); + self + } + + /// Create a new pool from this `PoolOptions` and immediately open at least one connection. + /// + /// This ensures the configuration is correct. + /// + /// The total number of connections opened is max(1, [min_connections][Self::min_connections]). + /// + /// Refer to the relevant `ConnectOptions` impl for your database for the expected URL format: + /// + /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions] + /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions] + /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions] + /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions] + pub async fn connect(self, url: &str) -> Result, Error> { + self.connect_with(url.parse()?).await + } + + /// Create a new pool from this `PoolOptions` and immediately open at least one connection. + /// + /// This ensures the configuration is correct. + /// + /// The total number of connections opened is max(1, [min_connections][Self::min_connections]). + pub async fn connect_with( + self, + options: ::Options, + ) -> Result, Error> { + // Don't take longer than `acquire_timeout` starting from when this is called. + let deadline = Instant::now() + self.acquire_timeout; + + let inner = PoolInner::new_arc(self, options); + + if inner.options.min_connections > 0 { + // If the idle reaper is spawned then this will race with the call from that task + // and may not report any connection errors. + inner.try_min_connections(deadline).await?; + } + + // If `min_connections` is nonzero then we'll likely just pull a connection + // from the idle queue here, but it should at least get tested first. + let conn = inner.acquire().await?; + inner.release(conn); + + Ok(Pool(inner)) + } + + /// Create a new pool from this `PoolOptions`, but don't open any connections right now. + /// + /// If [`min_connections`][Self::min_connections] is set, a background task will be spawned to + /// optimistically establish that many connections for the pool. + /// + /// Refer to the relevant `ConnectOptions` impl for your database for the expected URL format: + /// + /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions] + /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions] + /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions] + /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions] + pub fn connect_lazy(self, url: &str) -> Result, Error> { + Ok(self.connect_lazy_with(url.parse()?)) + } + + /// Create a new pool from this `PoolOptions`, but don't open any connections right now. + /// + /// If [`min_connections`][Self::min_connections] is set, a background task will be spawned to + /// optimistically establish that many connections for the pool. + pub fn connect_lazy_with(self, options: ::Options) -> Pool { + // `min_connections` is guaranteed by the idle reaper now. + Pool(PoolInner::new_arc(self, options)) + } +} + +impl Debug for PoolOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("PoolOptions") + .field("max_connections", &self.max_connections) + .field("min_connections", &self.min_connections) + .field("connect_timeout", &self.acquire_timeout) + .field("max_lifetime", &self.max_lifetime) + .field("idle_timeout", &self.idle_timeout) + .field("test_before_acquire", &self.test_before_acquire) + .finish() + } +} diff --git a/vendor/sqlx-core/src/query.rs b/vendor/sqlx-core/src/query.rs new file mode 100755 index 0000000..d549e3c --- /dev/null +++ b/vendor/sqlx-core/src/query.rs @@ -0,0 +1,691 @@ +use std::{future, marker::PhantomData}; + +use either::Either; +use futures_core::stream::BoxStream; +use futures_util::{StreamExt, TryFutureExt, TryStreamExt}; + +use crate::arguments::{Arguments, IntoArguments}; +use crate::database::{Database, HasStatementCache}; +use crate::encode::Encode; +use crate::error::{BoxDynError, Error}; +use crate::executor::{Execute, Executor}; +use crate::sql_str::{SqlSafeStr, SqlStr}; +use crate::statement::Statement; +use crate::types::Type; + +/// A single SQL query as a prepared statement. Returned by [`query()`]. +#[must_use = "query must be executed to affect database"] +pub struct Query<'q, DB: Database, A> { + pub(crate) statement: Either, + pub(crate) arguments: Option>, + pub(crate) database: PhantomData, + pub(crate) persistent: bool, +} + +/// A single SQL query that will map its results to an owned Rust type. +/// +/// Executes as a prepared statement. +/// +/// Returned by [`Query::try_map`], `query!()`, etc. Has most of the same methods as [`Query`] but +/// the return types are changed to reflect the mapping. However, there is no equivalent of +/// [`Query::execute`] as it doesn't make sense to map the result type and then ignore it. +/// +/// [`Query::bind`] is also omitted; stylistically we recommend placing your `.bind()` calls +/// before `.try_map()`. This is also to prevent adding superfluous binds to the result of +/// `query!()` et al. +#[must_use = "query must be executed to affect database"] +pub struct Map<'q, DB: Database, F, A> { + inner: Query<'q, DB, A>, + mapper: F, +} + +impl<'q, DB, A> Execute<'q, DB> for Query<'q, DB, A> +where + DB: Database, + A: Send + IntoArguments, +{ + #[inline] + fn sql(self) -> SqlStr { + match self.statement { + Either::Right(statement) => statement.sql().clone(), + Either::Left(sql) => sql, + } + } + + fn statement(&self) -> Option<&DB::Statement> { + match self.statement { + Either::Right(statement) => Some(statement), + Either::Left(_) => None, + } + } + + #[inline] + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + self.arguments + .take() + .transpose() + .map(|option| option.map(IntoArguments::into_arguments)) + } + + #[inline] + fn persistent(&self) -> bool { + self.persistent + } +} + +impl Query<'_, DB, ::Arguments> { + /// Bind a value for use with this SQL query. + /// + /// If the number of times this is called does not match the number of bind parameters that + /// appear in the query (`?` for most SQL flavors, `$1 .. $N` for Postgres) then an error + /// will be returned when this query is executed. + /// + /// There is no validation that the value is of the type expected by the query. Most SQL + /// flavors will perform type coercion (Postgres will return a database error). + /// + /// If encoding the value fails, the error is stored and later surfaced when executing the query. + pub fn bind<'t, T: Encode<'t, DB> + Type>(mut self, value: T) -> Self { + let Ok(arguments) = self.get_arguments() else { + return self; + }; + + let argument_number = arguments.len() + 1; + if let Err(error) = arguments.add(value) { + self.arguments = Some(Err(format!( + "Encoding argument ${argument_number} failed: {error}" + ) + .into())); + } + + self + } + + /// Like [`Query::bind`] but immediately returns an error if encoding a value failed. + pub fn try_bind<'t, T: Encode<'t, DB> + Type>( + &mut self, + value: T, + ) -> Result<(), BoxDynError> { + let arguments = self.get_arguments()?; + + arguments.add(value) + } + + fn get_arguments(&mut self) -> Result<&mut DB::Arguments, BoxDynError> { + let Some(Ok(arguments)) = self.arguments.as_mut().map(Result::as_mut) else { + return Err("A previous call to Query::bind produced an error" + .to_owned() + .into()); + }; + + Ok(arguments) + } +} + +impl Query<'_, DB, A> +where + DB: Database + HasStatementCache, +{ + /// If `true`, the statement will get prepared once and cached to the + /// connection's statement cache. + /// + /// If queried once with the flag set to `true`, all subsequent queries + /// matching the one with the flag will use the cached statement until the + /// cache is cleared. + /// + /// If `false`, the prepared statement will be closed after execution. + /// + /// Default: `true`. + pub fn persistent(mut self, value: bool) -> Self { + self.persistent = value; + self + } +} + +impl<'q, DB, A: Send> Query<'q, DB, A> +where + DB: Database, + A: 'q + IntoArguments, +{ + /// Map each row in the result to another type. + /// + /// See [`try_map`](Query::try_map) for a fallible version of this method. + /// + /// The [`query_as`](super::query_as::query_as) method will construct a mapped query using + /// a [`FromRow`](super::from_row::FromRow) implementation. + #[inline] + pub fn map( + self, + mut f: F, + ) -> Map<'q, DB, impl FnMut(DB::Row) -> Result + Send, A> + where + F: FnMut(DB::Row) -> O + Send, + O: Unpin, + { + self.try_map(move |row| Ok(f(row))) + } + + /// Map each row in the result to another type. + /// + /// The [`query_as`](super::query_as::query_as) method will construct a mapped query using + /// a [`FromRow`](super::from_row::FromRow) implementation. + #[inline] + pub fn try_map(self, f: F) -> Map<'q, DB, F, A> + where + F: FnMut(DB::Row) -> Result + Send, + O: Unpin, + { + Map { + inner: self, + mapper: f, + } + } + + /// Execute the query and return the total number of rows affected. + #[inline] + pub async fn execute<'e, 'c: 'e, E>(self, executor: E) -> Result + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.execute(self).await + } + + /// Execute multiple queries and return the rows affected from each query, in a stream. + #[inline] + #[deprecated = "Only the SQLite driver supports multiple statements in one prepared statement and that behavior is deprecated. Use `sqlx::raw_sql()` instead. See https://github.com/launchbadge/sqlx/issues/3108 for discussion."] + pub async fn execute_many<'e, 'c: 'e, E>( + self, + executor: E, + ) -> BoxStream<'e, Result> + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.execute_many(self) + } + + /// Execute the query and return the generated results as a stream. + #[inline] + pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result> + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.fetch(self) + } + + /// Execute multiple queries and return the generated results as a stream. + /// + /// For each query in the stream, any generated rows are returned first, + /// then the `QueryResult` with the number of rows affected. + #[inline] + #[deprecated = "Only the SQLite driver supports multiple statements in one prepared statement and that behavior is deprecated. Use `sqlx::raw_sql()` instead. See https://github.com/launchbadge/sqlx/issues/3108 for discussion."] + // TODO: we'll probably still want a way to get the `DB::QueryResult` at the end of a `fetch()` stream. + pub fn fetch_many<'e, 'c: 'e, E>( + self, + executor: E, + ) -> BoxStream<'e, Result, Error>> + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.fetch_many(self) + } + + /// Execute the query and return all the resulting rows collected into a [`Vec`]. + /// + /// ### Note: beware result set size. + /// This will attempt to collect the full result set of the query into memory. + /// + /// To avoid exhausting available memory, ensure the result set has a known upper bound, + /// e.g. using `LIMIT`. + #[inline] + pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.fetch_all(self).await + } + + /// Execute the query, returning the first row or [`Error::RowNotFound`] otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + #[inline] + pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.fetch_one(self).await + } + + /// Execute the query, returning the first row or `None` otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + #[inline] + pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + A: 'e, + E: Executor<'c, Database = DB>, + { + executor.fetch_optional(self).await + } +} + +impl<'q, DB, F: Send, A: Send> Execute<'q, DB> for Map<'q, DB, F, A> +where + DB: Database, + A: IntoArguments, +{ + #[inline] + fn sql(self) -> SqlStr { + self.inner.sql() + } + + #[inline] + fn statement(&self) -> Option<&DB::Statement> { + self.inner.statement() + } + + #[inline] + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + self.inner.take_arguments() + } + + #[inline] + fn persistent(&self) -> bool { + self.inner.arguments.is_some() + } +} + +impl<'q, DB, F, O, A> Map<'q, DB, F, A> +where + DB: Database, + F: FnMut(DB::Row) -> Result + Send, + O: Send + Unpin, + A: 'q + Send + IntoArguments, +{ + /// Map each row in the result to another type. + /// + /// See [`try_map`](Map::try_map) for a fallible version of this method. + /// + /// The [`query_as`](super::query_as::query_as) method will construct a mapped query using + /// a [`FromRow`](super::from_row::FromRow) implementation. + #[inline] + pub fn map( + self, + mut g: G, + ) -> Map<'q, DB, impl FnMut(DB::Row) -> Result + Send, A> + where + G: FnMut(O) -> P + Send, + P: Unpin, + { + self.try_map(move |data| Ok(g(data))) + } + + /// Map each row in the result to another type. + /// + /// The [`query_as`](super::query_as::query_as) method will construct a mapped query using + /// a [`FromRow`](super::from_row::FromRow) implementation. + #[inline] + pub fn try_map( + self, + mut g: G, + ) -> Map<'q, DB, impl FnMut(DB::Row) -> Result + Send, A> + where + G: FnMut(O) -> Result + Send, + P: Unpin, + { + let mut f = self.mapper; + Map { + inner: self.inner, + mapper: move |row| f(row).and_then(&mut g), + } + } + + /// Execute the query and return the generated results as a stream. + pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + F: 'e, + O: 'e, + { + // FIXME: this should have used `executor.fetch()` but that's a breaking change + // because this technically allows multiple statements in one query string. + #[allow(deprecated)] + self.fetch_many(executor) + .try_filter_map(|step| async move { + Ok(match step { + Either::Left(_) => None, + Either::Right(o) => Some(o), + }) + }) + .boxed() + } + + /// Execute multiple queries and return the generated results as a stream + /// from each query, in a stream. + #[deprecated = "Only the SQLite driver supports multiple statements in one prepared statement and that behavior is deprecated. Use `sqlx::raw_sql()` instead."] + pub fn fetch_many<'e, 'c: 'e, E>( + mut self, + executor: E, + ) -> BoxStream<'e, Result, Error>> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + F: 'e, + O: 'e, + { + Box::pin(try_stream! { + let mut s = executor.fetch_many(self.inner); + + while let Some(v) = s.try_next().await? { + r#yield!(match v { + Either::Left(v) => Either::Left(v), + Either::Right(row) => { + Either::Right((self.mapper)(row)?) + } + }); + } + + Ok(()) + }) + } + + /// Execute the query and return all the resulting rows collected into a [`Vec`]. + /// + /// ### Note: beware result set size. + /// This will attempt to collect the full result set of the query into memory. + /// + /// To avoid exhausting available memory, ensure the result set has a known upper bound, + /// e.g. using `LIMIT`. + pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + F: 'e, + O: 'e, + { + self.fetch(executor).try_collect().await + } + + /// Execute the query, returning the first row or [`Error::RowNotFound`] otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + F: 'e, + O: 'e, + { + self.fetch_optional(executor) + .and_then(|row| { + future::ready(match row { + Some(row) => Ok(row), + None => Err(Error::RowNotFound), + }) + }) + .await + } + + /// Execute the query, returning the first row or `None` otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + pub async fn fetch_optional<'e, 'c: 'e, E>(mut self, executor: E) -> Result, Error> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + F: 'e, + O: 'e, + { + let row = executor.fetch_optional(self.inner).await?; + + if let Some(row) = row { + (self.mapper)(row).map(Some) + } else { + Ok(None) + } + } +} + +/// Execute a single SQL query as a prepared statement (explicitly created). +pub fn query_statement(statement: &DB::Statement) -> Query<'_, DB, ::Arguments> +where + DB: Database, +{ + Query { + database: PhantomData, + arguments: Some(Ok(Default::default())), + statement: Either::Right(statement), + persistent: true, + } +} + +/// Execute a single SQL query as a prepared statement (explicitly created), with the given arguments. +pub fn query_statement_with(statement: &DB::Statement, arguments: A) -> Query<'_, DB, A> +where + DB: Database, + A: IntoArguments, +{ + Query { + database: PhantomData, + arguments: Some(Ok(arguments)), + statement: Either::Right(statement), + persistent: true, + } +} + +/// Execute a single SQL query as a prepared statement (transparently cached). +/// +/// The query string may only contain a single DML statement: `SELECT`, `INSERT`, `UPDATE`, `DELETE` and variants. +/// The SQLite driver does not currently follow this restriction, but that behavior is deprecated. +/// +/// The connection will transparently prepare and cache the statement, which means it only needs to be parsed once +/// in the connection's lifetime, and any generated query plans can be retained. +/// Thus, the overhead of executing the statement is amortized. +/// +/// Some third-party databases that speak a supported protocol, e.g. CockroachDB or PGBouncer that speak Postgres, +/// may have issues with the transparent caching of prepared statements. If you are having trouble, +/// try setting [`.persistent(false)`][Query::persistent]. +/// +/// See the [`Query`] type for the methods you may call. +/// +/// ### Dynamic Input: Use Query Parameters (Prevents SQL Injection) +/// At some point, you'll likely want to include some form of dynamic input in your query, possibly from the user. +/// +/// Your first instinct might be to do something like this: +/// ```rust,no_run +/// # async fn example() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// // Imagine this is input from the user, e.g. a search form on a website. +/// let user_input = "possibly untrustworthy input!"; +/// +/// // DO NOT DO THIS unless you're ABSOLUTELY CERTAIN it's what you need! +/// let query = format!("SELECT * FROM articles WHERE content LIKE '%{user_input}%'"); +/// // where `conn` is `PgConnection` or `MySqlConnection` +/// // or some other type that implements `Executor`. +/// let results = sqlx::query(sqlx::AssertSqlSafe(query)).fetch_all(&mut conn).await?; +/// # Ok(()) +/// # } +/// ``` +/// +/// The example above showcases a **SQL injection vulnerability**, because it's trivial for a malicious user to craft +/// an input that can "break out" of the string literal. +/// +/// For example, if they send the input `foo'; DELETE FROM articles; --` +/// then your application would send the following to the database server (line breaks added for clarity): +/// +/// ```sql +/// SELECT * FROM articles WHERE content LIKE '%foo'; +/// DELETE FROM articles; +/// --%' +/// ``` +/// +/// In this case, because this interface *always* uses prepared statements, you would likely be fine because prepared +/// statements _generally_ (see above) are only allowed to contain a single query. This would simply return an error. +/// +/// However, it would also break on legitimate user input. +/// What if someone wanted to search for the string `Alice's Apples`? It would also return an error because +/// the database would receive a query with a broken string literal (line breaks added for clarity): +/// +/// ```sql +/// SELECT * FROM articles WHERE content LIKE '%Alice' +/// s Apples%' +/// ``` +/// +/// Of course, it's possible to make this syntactically valid by escaping the apostrophe, but there's a better way. +/// +/// ##### You should always prefer query parameters for dynamic input. +/// +/// When using query parameters, you add placeholders to your query where a value +/// should be substituted at execution time, then call [`.bind()`][Query::bind] with that value. +/// +/// The syntax for placeholders is unfortunately not standardized and depends on the database: +/// +/// * Postgres and SQLite: use `$1`, `$2`, `$3`, etc. +/// * The number is the Nth bound value, starting from one. +/// * The same placeholder can be used arbitrarily many times to refer to the same bound value. +/// * SQLite technically supports MySQL's syntax as well as others, but we recommend using this syntax +/// as SQLx's SQLite driver is written with it in mind. +/// * MySQL and MariaDB: use `?`. +/// * Placeholders are purely positional, similar to `println!("{}, {}", foo, bar)`. +/// * The order of bindings must match the order of placeholders in the query. +/// * To use a value in multiple places, you must bind it multiple times. +/// +/// In both cases, the placeholder syntax acts as a variable expression representing the bound value: +/// +/// ```rust,no_run +/// # async fn example2() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// let user_input = "Alice's Apples"; +/// +/// // Postgres and SQLite +/// let results = sqlx::query( +/// // Notice how we only have to bind the argument once and we can use it multiple times: +/// "SELECT * FROM articles +/// WHERE title LIKE '%' || $1 || '%' +/// OR content LIKE '%' || $1 || '%'" +/// ) +/// .bind(user_input) +/// .fetch_all(&mut conn) +/// .await?; +/// +/// // MySQL and MariaDB +/// let results = sqlx::query( +/// "SELECT * FROM articles +/// WHERE title LIKE CONCAT('%', ?, '%') +/// OR content LIKE CONCAT('%', ?, '%')" +/// ) +/// // If we want to reference the same value multiple times, we have to bind it multiple times: +/// .bind(user_input) +/// .bind(user_input) +/// .fetch_all(&mut conn) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +/// ##### The value bound to a query parameter is entirely separate from the query and does not affect its syntax. +/// Thus, SQL injection is impossible (barring shenanigans like calling a SQL function that lets you execute a string +/// as a statement) and *all* strings are valid. +/// +/// This also means you cannot use query parameters to add conditional SQL fragments. +/// +/// **SQLx does not substitute placeholders on the client side**. It is done by the database server itself. +/// +/// ##### SQLx supports many different types for parameter binding, not just strings. +/// Any type that implements [`Encode`][Encode] and [`Type`] can be bound as a parameter. +/// +/// See [the `types` module][crate::types] (links to `sqlx_core::types` but you should use `sqlx::types`) for details. +/// +/// As an additional benefit, query parameters are usually sent in a compact binary encoding instead of a human-readable +/// text encoding, which saves bandwidth. +pub fn query<'a, DB>(sql: impl SqlSafeStr) -> Query<'a, DB, ::Arguments> +where + DB: Database, +{ + Query { + database: PhantomData, + arguments: Some(Ok(Default::default())), + statement: Either::Left(sql.into_sql_str()), + persistent: true, + } +} + +/// Execute a SQL query as a prepared statement (transparently cached), with the given arguments. +/// +/// See [`query()`][query] for details, such as supported syntax. +pub fn query_with<'q, DB, A>(sql: impl SqlSafeStr, arguments: A) -> Query<'q, DB, A> +where + DB: Database, + A: IntoArguments, +{ + query_with_result(sql, Ok(arguments)) +} + +/// Same as [`query_with`] but is initialized with a Result of arguments instead +pub fn query_with_result<'q, DB, A>( + sql: impl SqlSafeStr, + arguments: Result, +) -> Query<'q, DB, A> +where + DB: Database, + A: IntoArguments, +{ + Query { + database: PhantomData, + arguments: Some(arguments), + statement: Either::Left(sql.into_sql_str()), + persistent: true, + } +} diff --git a/vendor/sqlx-core/src/query_as.rs b/vendor/sqlx-core/src/query_as.rs new file mode 100755 index 0000000..00194cb --- /dev/null +++ b/vendor/sqlx-core/src/query_as.rs @@ -0,0 +1,413 @@ +use std::marker::PhantomData; + +use either::Either; +use futures_core::stream::BoxStream; +use futures_util::{StreamExt, TryStreamExt}; + +use crate::arguments::IntoArguments; +use crate::database::{Database, HasStatementCache}; +use crate::encode::Encode; +use crate::error::{BoxDynError, Error}; +use crate::executor::{Execute, Executor}; +use crate::from_row::FromRow; +use crate::query::{query, query_statement, query_statement_with, query_with_result, Query}; +use crate::sql_str::{SqlSafeStr, SqlStr}; +use crate::types::Type; + +/// A single SQL query as a prepared statement, mapping results using [`FromRow`]. +/// Returned by [`query_as()`]. +#[must_use = "query must be executed to affect database"] +pub struct QueryAs<'q, DB: Database, O, A> { + pub(crate) inner: Query<'q, DB, A>, + pub(crate) output: PhantomData, +} + +impl<'q, DB, O: Send, A: Send> Execute<'q, DB> for QueryAs<'q, DB, O, A> +where + DB: Database, + A: 'q + IntoArguments, +{ + #[inline] + fn sql(self) -> SqlStr { + self.inner.sql() + } + + #[inline] + fn statement(&self) -> Option<&DB::Statement> { + self.inner.statement() + } + + #[inline] + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + self.inner.take_arguments() + } + + #[inline] + fn persistent(&self) -> bool { + self.inner.persistent() + } +} + +impl<'q, DB: Database, O> QueryAs<'q, DB, O, ::Arguments> { + /// Bind a value for use with this SQL query. + /// + /// See [`Query::bind`](Query::bind). + pub fn bind + Type>(mut self, value: T) -> Self { + self.inner = self.inner.bind(value); + self + } +} + +impl QueryAs<'_, DB, O, A> +where + DB: Database + HasStatementCache, +{ + /// If `true`, the statement will get prepared once and cached to the + /// connection's statement cache. + /// + /// If queried once with the flag set to `true`, all subsequent queries + /// matching the one with the flag will use the cached statement until the + /// cache is cleared. + /// + /// If `false`, the prepared statement will be closed after execution. + /// + /// Default: `true`. + pub fn persistent(mut self, value: bool) -> Self { + self.inner = self.inner.persistent(value); + self + } +} + +// FIXME: This is very close, nearly 1:1 with `Map` +// noinspection DuplicatedCode +impl<'q, DB, O, A> QueryAs<'q, DB, O, A> +where + DB: Database, + A: 'q + IntoArguments, + O: Send + Unpin + for<'r> FromRow<'r, DB::Row>, +{ + /// Execute the query and return the generated results as a stream. + pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + executor + .fetch(self.inner) + .map(|row| O::from_row(&row?)) + .boxed() + } + + /// Execute multiple queries and return the generated results as a stream + /// from each query, in a stream. + #[deprecated = "Only the SQLite driver supports multiple statements in one prepared statement and that behavior is deprecated. Use `sqlx::raw_sql()` instead. See https://github.com/launchbadge/sqlx/issues/3108 for discussion."] + pub fn fetch_many<'e, 'c: 'e, E>( + self, + executor: E, + ) -> BoxStream<'e, Result, Error>> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + executor + .fetch_many(self.inner) + .map(|v| match v { + Ok(Either::Right(row)) => O::from_row(&row).map(Either::Right), + Ok(Either::Left(v)) => Ok(Either::Left(v)), + Err(e) => Err(e), + }) + .boxed() + } + + /// Execute the query and return all the resulting rows collected into a [`Vec`]. + /// + /// ### Note: beware result set size. + /// This will attempt to collect the full result set of the query into memory. + /// + /// To avoid exhausting available memory, ensure the result set has a known upper bound, + /// e.g. using `LIMIT`. + #[inline] + pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + self.fetch(executor).try_collect().await + } + + /// Execute the query, returning the first row or [`Error::RowNotFound`] otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + self.fetch_optional(executor) + .await + .and_then(|row| row.ok_or(Error::RowNotFound)) + } + + /// Execute the query, returning the first row or `None` otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + let row = executor.fetch_optional(self.inner).await?; + if let Some(row) = row { + O::from_row(&row).map(Some) + } else { + Ok(None) + } + } +} + +/// Execute a single SQL query as a prepared statement (transparently cached). +/// Maps rows to Rust types using [`FromRow`]. +/// +/// For details about prepared statements and allowed SQL syntax, see [`query()`][crate::query::query]. +/// +/// ### Example: Map Rows using Tuples +/// [`FromRow`] is implemented for tuples of up to 16 elements1. +/// Using a tuple of N elements will extract the first N columns from each row using [`Decode`][crate::decode::Decode]. +/// Any extra columns are ignored. +/// +/// See [`sqlx::types`][crate::types] for the types that can be used. +/// +/// The `FromRow` implementation will check [`Type::compatible()`] for each column to ensure a compatible type mapping +/// is used. If an incompatible mapping is detected, an error is returned. +/// To statically assert compatible types at compile time, see the `query!()` family of macros. +/// +/// **NOTE**: `SELECT *` is not recommended with this approach because the ordering of returned columns may be different +/// than expected, especially when using joins. +/// +/// ```rust,no_run +/// # async fn example1() -> sqlx::Result<()> { +/// use sqlx::Connection; +/// use sqlx::PgConnection; +/// +/// // This example can be applied to any database as it only uses standard types and syntax. +/// let mut conn: PgConnection = PgConnection::connect("").await?; +/// +/// sqlx::raw_sql( +/// "CREATE TABLE users(id INTEGER PRIMARY KEY, username TEXT UNIQUE, created_at TIMESTAMPTZ DEFAULT (now()))" +/// ) +/// .execute(&mut conn) +/// .await?; +/// +/// sqlx::query("INSERT INTO users(id, username) VALUES (1, 'alice'), (2, 'bob');") +/// .execute(&mut conn) +/// .await?; +/// +/// // Get the first row of the result (note the `LIMIT 1` for efficiency) +/// // This assumes the `time` feature of SQLx is enabled. +/// let oldest_user: (i32, String, time::OffsetDateTime) = sqlx::query_as( +/// "SELECT id, username, created_at FROM users ORDER BY created_at LIMIT 1" +/// ) +/// .fetch_one(&mut conn) +/// .await?; +/// +/// assert_eq!(oldest_user.0, 1); +/// assert_eq!(oldest_user.1, "alice"); +/// +/// // Get at most one row +/// let maybe_charlie: Option<(i32, String, time::OffsetDateTime)> = sqlx::query_as( +/// "SELECT id, username, created_at FROM users WHERE username = 'charlie'" +/// ) +/// .fetch_optional(&mut conn) +/// .await?; +/// +/// assert_eq!(maybe_charlie, None); +/// +/// // Get all rows in result (Beware of the size of the result set! Consider using `LIMIT`) +/// let users: Vec<(i32, String, time::OffsetDateTime)> = sqlx::query_as( +/// "SELECT id, username, created_at FROM users ORDER BY id" +/// ) +/// .fetch_all(&mut conn) +/// .await?; +/// +/// println!("{users:?}"); +/// # Ok(()) +/// # } +/// ``` +/// +/// 1: It's impossible in Rust to implement a trait for tuples of arbitrary size. +/// For larger result sets, either use an explicit struct (see below) or use [`query()`][crate::query::query] +/// instead and extract columns dynamically. +/// +/// ### Example: Map Rows using `#[derive(FromRow)]` +/// Using `#[derive(FromRow)]`, we can create a Rust struct to represent our row type +/// so we can look up fields by name instead of tuple index. +/// +/// When querying this way, columns will be matched up to the corresponding fields by name, so `SELECT *` is safe to use. +/// However, you will still want to be aware of duplicate column names in your query when using joins. +/// +/// The derived `FromRow` implementation will check [`Type::compatible()`] for each column to ensure a compatible type +/// mapping is used. If an incompatible mapping is detected, an error is returned. +/// To statically assert compatible types at compile time, see the `query!()` family of macros. +/// +/// An error will also be returned if an expected column is missing from the result set. +/// +/// `#[derive(FromRow)]` supports several control attributes which can be used to change how column names and types +/// are mapped. See [`FromRow`] for details. +/// +/// Using our previous table definition, we can convert our queries like so: +/// ```rust,no_run +/// # async fn example2() -> sqlx::Result<()> { +/// use sqlx::Connection; +/// use sqlx::PgConnection; +/// +/// use time::OffsetDateTime; +/// +/// #[derive(sqlx::FromRow, Debug, PartialEq, Eq)] +/// struct User { +/// id: i64, +/// username: String, +/// // Note: the derive won't compile if the `time` feature of SQLx is not enabled. +/// created_at: OffsetDateTime, +/// } +/// +/// let mut conn: PgConnection = PgConnection::connect("").await?; +/// +/// // Get the first row of the result (note the `LIMIT 1` for efficiency) +/// let oldest_user: User = sqlx::query_as( +/// "SELECT id, username, created_at FROM users ORDER BY created_at LIMIT 1" +/// ) +/// .fetch_one(&mut conn) +/// .await?; +/// +/// assert_eq!(oldest_user.id, 1); +/// assert_eq!(oldest_user.username, "alice"); +/// +/// // Get at most one row +/// let maybe_charlie: Option = sqlx::query_as( +/// "SELECT id, username, created_at FROM users WHERE username = 'charlie'" +/// ) +/// .fetch_optional(&mut conn) +/// .await?; +/// +/// assert_eq!(maybe_charlie, None); +/// +/// // Get all rows in result (Beware of the size of the result set! Consider using `LIMIT`) +/// let users: Vec = sqlx::query_as( +/// "SELECT id, username, created_at FROM users ORDER BY id" +/// ) +/// .fetch_all(&mut conn) +/// .await?; +/// +/// assert_eq!(users[1].id, 2); +/// assert_eq!(users[1].username, "bob"); +/// # Ok(()) +/// # } +/// +/// ``` +#[inline] +pub fn query_as<'q, DB, O>(sql: impl SqlSafeStr) -> QueryAs<'q, DB, O, ::Arguments> +where + DB: Database, + O: for<'r> FromRow<'r, DB::Row>, +{ + QueryAs { + inner: query(sql), + output: PhantomData, + } +} + +/// Execute a single SQL query, with the given arguments as a prepared statement (transparently cached). +/// Maps rows to Rust types using [`FromRow`]. +/// +/// For details about prepared statements and allowed SQL syntax, see [`query()`][crate::query::query]. +/// +/// For details about type mapping from [`FromRow`], see [`query_as()`]. +#[inline] +pub fn query_as_with<'q, DB, O, A>(sql: impl SqlSafeStr, arguments: A) -> QueryAs<'q, DB, O, A> +where + DB: Database, + A: IntoArguments, + O: for<'r> FromRow<'r, DB::Row>, +{ + query_as_with_result(sql, Ok(arguments)) +} + +/// Same as [`query_as_with`] but takes arguments as a Result +#[inline] +pub fn query_as_with_result<'q, DB, O, A>( + sql: impl SqlSafeStr, + arguments: Result, +) -> QueryAs<'q, DB, O, A> +where + DB: Database, + A: IntoArguments, + O: for<'r> FromRow<'r, DB::Row>, +{ + QueryAs { + inner: query_with_result(sql, arguments), + output: PhantomData, + } +} + +// Make a SQL query from a statement, that is mapped to a concrete type. +pub fn query_statement_as( + statement: &DB::Statement, +) -> QueryAs<'_, DB, O, ::Arguments> +where + DB: Database, + O: for<'r> FromRow<'r, DB::Row>, +{ + QueryAs { + inner: query_statement(statement), + output: PhantomData, + } +} + +// Make a SQL query from a statement, with the given arguments, that is mapped to a concrete type. +pub fn query_statement_as_with<'q, DB, O, A>( + statement: &'q DB::Statement, + arguments: A, +) -> QueryAs<'q, DB, O, A> +where + DB: Database, + A: IntoArguments, + O: for<'r> FromRow<'r, DB::Row>, +{ + QueryAs { + inner: query_statement_with(statement, arguments), + output: PhantomData, + } +} diff --git a/vendor/sqlx-core/src/query_builder.rs b/vendor/sqlx-core/src/query_builder.rs new file mode 100755 index 0000000..25aa500 --- /dev/null +++ b/vendor/sqlx-core/src/query_builder.rs @@ -0,0 +1,614 @@ +//! Runtime query-builder API. + +use std::fmt::Display; +use std::fmt::Write; +use std::marker::PhantomData; +use std::sync::Arc; + +use crate::arguments::{Arguments, IntoArguments}; +use crate::database::Database; +use crate::encode::Encode; +use crate::from_row::FromRow; +use crate::query::Query; +use crate::query_as::QueryAs; +use crate::query_scalar::QueryScalar; +use crate::sql_str::AssertSqlSafe; +use crate::sql_str::SqlSafeStr; +use crate::sql_str::SqlStr; +use crate::types::Type; +use crate::Either; + +/// A builder type for constructing queries at runtime. +/// +/// See [`.push_values()`][Self::push_values] for an example of building a bulk `INSERT` statement. +/// Note, however, that with Postgres you can get much better performance by using arrays +/// and `UNNEST()`. [See our FAQ] for details. +/// +/// [See our FAQ]: https://github.com/launchbadge/sqlx/blob/master/FAQ.md#how-can-i-bind-an-array-to-a-values-clause-how-can-i-do-bulk-inserts +pub struct QueryBuilder +where + DB: Database, +{ + query: Arc, + init_len: usize, + arguments: Option<::Arguments>, +} + +impl Default for QueryBuilder { + fn default() -> Self { + QueryBuilder { + init_len: 0, + query: Default::default(), + arguments: Some(Default::default()), + } + } +} + +const ERROR: &str = "BUG: query must not be shared at this point in time"; + +impl QueryBuilder +where + DB: Database, +{ + // `init` is provided because a query will almost always start with a constant fragment + // such as `INSERT INTO ...` or `SELECT ...`, etc. + /// Start building a query with an initial SQL fragment, which may be an empty string. + pub fn new(init: impl Into) -> Self + where + ::Arguments: Default, + { + let init = init.into(); + + QueryBuilder { + init_len: init.len(), + query: init.into(), + arguments: Some(Default::default()), + } + } + + /// Construct a `QueryBuilder` with existing SQL and arguments. + /// + /// ### Note + /// This does *not* check if `arguments` is valid for the given SQL. + pub fn with_arguments(init: impl Into, arguments: A) -> Self + where + DB: Database, + A: IntoArguments, + { + let init = init.into(); + + QueryBuilder { + init_len: init.len(), + query: init.into(), + arguments: Some(arguments.into_arguments()), + } + } + + #[inline] + fn sanity_check(&self) { + assert!( + self.arguments.is_some(), + "QueryBuilder must be reset before reuse after `.build()`" + ); + } + + /// Append a SQL fragment to the query. + /// + /// May be a string or anything that implements `Display`. + /// You can also use `format_args!()` here to push a formatted string without an intermediate + /// allocation. + /// + /// ### Warning: Beware SQL Injection Vulnerabilities and Untrusted Input! + /// You should *not* use this to insert input directly into the query from an untrusted user as + /// this can be used by an attacker to extract sensitive data or take over your database. + /// + /// Security breaches due to SQL injection can cost your organization a lot of money from + /// damage control and lost clients, betray the trust of your users in your system, and are just + /// plain embarrassing. If you are unfamiliar with the threat that SQL injection imposes, you + /// should take some time to learn more about it before proceeding: + /// + /// * [SQL Injection on OWASP.org](https://owasp.org/www-community/attacks/SQL_Injection) + /// * [SQL Injection on Wikipedia](https://en.wikipedia.org/wiki/SQL_injection) + /// * See "Examples" for notable instances of security breaches due to SQL injection. + /// + /// This method does *not* perform sanitization. Instead, you should use + /// [`.push_bind()`][Self::push_bind] which inserts a placeholder into the query and then + /// sends the possibly untrustworthy value separately (called a "bind argument") so that it + /// cannot be misinterpreted by the database server. + /// + /// Note that you should still at least have some sort of sanity checks on the values you're + /// sending as that's just good practice and prevent other types of attacks against your system, + /// e.g. check that strings aren't too long, numbers are within expected ranges, etc. + pub fn push(&mut self, sql: impl Display) -> &mut Self { + self.sanity_check(); + let query: &mut String = Arc::get_mut(&mut self.query).expect(ERROR); + + write!(query, "{sql}").expect("error formatting `sql`"); + + self + } + + /// Push a bind argument placeholder (`?` or `$N` for Postgres) and bind a value to it. + /// + /// ### Note: Database-specific Limits + /// Note that every database has a practical limit on the number of bind parameters + /// you can add to a single query. This varies by database. + /// + /// While you should consult the manual of your specific database version and/or current + /// configuration for the exact value as it may be different than listed here, + /// the defaults for supported databases as of writing are as follows: + /// + /// * Postgres and MySQL: 65535 + /// * You may find sources that state that Postgres has a limit of 32767, + /// but that is a misinterpretation of the specification by the JDBC driver implementation + /// as discussed in [this Github issue][postgres-limit-issue]. Postgres itself + /// asserts that the number of parameters is in the range `[0, 65535)`. + /// * SQLite: 32766 (configurable by [`SQLITE_LIMIT_VARIABLE_NUMBER`]) + /// * SQLite prior to 3.32.0: 999 + /// * MSSQL: 2100 + /// + /// Exceeding these limits may panic (as a sanity check) or trigger a database error at runtime + /// depending on the implementation. + /// + /// [`SQLITE_LIMIT_VARIABLE_NUMBER`]: https://www.sqlite.org/limits.html#max_variable_number + /// [postgres-limit-issue]: https://github.com/launchbadge/sqlx/issues/671#issuecomment-687043510 + pub fn push_bind<'t, T>(&mut self, value: T) -> &mut Self + where + T: Encode<'t, DB> + Type, + { + self.sanity_check(); + + let arguments = self + .arguments + .as_mut() + .expect("BUG: Arguments taken already"); + arguments.add(value).expect("Failed to add argument"); + + let query: &mut String = Arc::get_mut(&mut self.query).expect(ERROR); + arguments + .format_placeholder(query) + .expect("error in format_placeholder"); + + self + } + + /// Start a list separated by `separator`. + /// + /// The returned type exposes identical [`.push()`][Separated::push] and + /// [`.push_bind()`][Separated::push_bind] methods which push `separator` to the query + /// before their normal behavior. [`.push_unseparated()`][Separated::push_unseparated] and [`.push_bind_unseparated()`][Separated::push_bind_unseparated] are also + /// provided to push a SQL fragment without the separator. + /// + /// ```rust + /// # #[cfg(feature = "mysql")] { + /// use sqlx::{Execute, MySql, QueryBuilder}; + /// let foods = vec!["pizza".to_string(), "chips".to_string()]; + /// let mut query_builder: QueryBuilder = QueryBuilder::new( + /// "SELECT * from food where name in (" + /// ); + /// // One element vector is handled correctly but an empty vector + /// // would cause a sql syntax error + /// let mut separated = query_builder.separated(", "); + /// for value_type in foods.iter() { + /// separated.push_bind(value_type); + /// } + /// separated.push_unseparated(") "); + /// + /// let mut query = query_builder.build(); + /// let sql = query.sql(); + /// assert!(sql.ends_with("in (?, ?) ")); + /// # } + /// ``` + pub fn separated(&mut self, separator: Sep) -> Separated<'_, DB, Sep> + where + Sep: Display, + { + self.sanity_check(); + + Separated { + query_builder: self, + separator, + push_separator: false, + } + } + + // Most of the `QueryBuilder` API is purposefully very low-level but this was a commonly + // requested use-case so it made sense to support. + /// Push a `VALUES` clause where each item in `tuples` represents a tuple/row in the clause. + /// + /// This can be used to construct a bulk `INSERT` statement, although keep in mind that all + /// databases have some practical limit on the number of bind arguments in a single query. + /// See [`.push_bind()`][Self::push_bind] for details. + /// + /// To be safe, you can do `tuples.into_iter().take(N)` where `N` is the limit for your database + /// divided by the number of fields in each tuple; since integer division always rounds down, + /// this will ensure that you don't exceed the limit. + /// + /// ### Notes + /// + /// If `tuples` is empty, this will likely produce a syntactically invalid query as `VALUES` + /// generally expects to be followed by at least 1 tuple. + /// + /// If `tuples` can have many different lengths, you may want to call + /// [`.persistent(false)`][Query::persistent] after [`.build()`][Self::build] to avoid + /// filling up the connection's prepared statement cache. + /// + /// Because the `Arguments` API has a lifetime that must live longer than `Self`, you cannot + /// bind by-reference from an iterator unless that iterator yields references that live + /// longer than `Self`, even if the specific `Arguments` implementation doesn't actually + /// borrow the values (like `MySqlArguments` and `PgArguments` immediately encode the arguments + /// and don't borrow them past the `.add()` call). + /// + /// So basically, if you want to bind by-reference you need an iterator that yields references, + /// e.g. if you have values in a `Vec` you can do `.iter()` instead of `.into_iter()`. The + /// example below uses an iterator that creates values on the fly + /// and so cannot bind by-reference. + /// + /// ### Example (MySQL) + /// + /// ```rust + /// # #[cfg(feature = "mysql")] + /// # { + /// use sqlx::{Execute, MySql, QueryBuilder}; + /// + /// struct User { + /// id: i32, + /// username: String, + /// email: String, + /// password: String, + /// } + /// + /// // The number of parameters in MySQL must fit in a `u16`. + /// const BIND_LIMIT: usize = 65535; + /// + /// // This would normally produce values forever! + /// let users = (0..).map(|i| User { + /// id: i, + /// username: format!("test_user_{i}"), + /// email: format!("test-user-{i}@example.com"), + /// password: format!("Test!User@Password#{i}"), + /// }); + /// + /// let mut query_builder: QueryBuilder = QueryBuilder::new( + /// // Note the trailing space; most calls to `QueryBuilder` don't automatically insert + /// // spaces as that might interfere with identifiers or quoted strings where exact + /// // values may matter. + /// "INSERT INTO users(id, username, email, password) " + /// ); + /// + /// // Note that `.into_iter()` wasn't needed here since `users` is already an iterator. + /// query_builder.push_values(users.take(BIND_LIMIT / 4), |mut b, user| { + /// // If you wanted to bind these by-reference instead of by-value, + /// // you'd need an iterator that yields references that live as long as `query_builder`, + /// // e.g. collect it to a `Vec` first. + /// b.push_bind(user.id) + /// .push_bind(user.username) + /// .push_bind(user.email) + /// .push_bind(user.password); + /// }); + /// + /// let mut query = query_builder.build(); + /// + /// // You can then call `query.execute()`, `.fetch_one()`, `.fetch_all()`, etc. + /// // For the sake of demonstration though, we're just going to assert the contents + /// // of the query. + /// + /// // These are methods of the `Execute` trait, not normally meant to be called in user code. + /// let sql = query.sql(); + /// let arguments = query.take_arguments().unwrap(); + /// + /// assert!(sql.starts_with( + /// "INSERT INTO users(id, username, email, password) VALUES (?, ?, ?, ?), (?, ?, ?, ?)" + /// )); + /// + /// assert!(sql.ends_with("(?, ?, ?, ?)")); + /// + /// // Not a normally exposed function, only used for this doctest. + /// // 65535 / 4 = 16383 (rounded down) + /// // 16383 * 4 = 65532 + /// assert_eq!(arguments.len(), 65532); + /// # } + /// ``` + pub fn push_values(&mut self, tuples: I, mut push_tuple: F) -> &mut Self + where + I: IntoIterator, + F: FnMut(Separated<'_, DB, &'static str>, I::Item), + { + self.sanity_check(); + + self.push("VALUES "); + + let mut separated = self.separated(", "); + + for tuple in tuples { + separated.push("("); + + // use a `Separated` with a separate (hah) internal state + push_tuple(separated.query_builder.separated(", "), tuple); + + separated.push_unseparated(")"); + } + + debug_assert!( + separated.push_separator, + "No value being pushed. QueryBuilder may not build correct sql query!" + ); + + separated.query_builder + } + + /// Creates `((a, b), (..)` statements, from `tuples`. + /// + /// This can be used to construct a bulk `SELECT` statement like this: + /// ```sql + /// SELECT * FROM users WHERE (id, username) IN ((1, "test_user_1"), (2, "test_user_2")) + /// ``` + /// + /// Although keep in mind that all + /// databases have some practical limit on the number of bind arguments in a single query. + /// See [`.push_bind()`][Self::push_bind] for details. + /// + /// To be safe, you can do `tuples.into_iter().take(N)` where `N` is the limit for your database + /// divided by the number of fields in each tuple; since integer division always rounds down, + /// this will ensure that you don't exceed the limit. + /// + /// ### Notes + /// + /// If `tuples` is empty, this will likely produce a syntactically invalid query + /// + /// ### Example (MySQL) + /// + /// ```rust + /// # #[cfg(feature = "mysql")] + /// # { + /// use sqlx::{Execute, MySql, QueryBuilder}; + /// + /// struct User { + /// id: i32, + /// username: String, + /// email: String, + /// password: String, + /// } + /// + /// // The number of parameters in MySQL must fit in a `u16`. + /// const BIND_LIMIT: usize = 65535; + /// + /// // This would normally produce values forever! + /// let users = (0..).map(|i| User { + /// id: i, + /// username: format!("test_user_{i}"), + /// email: format!("test-user-{i}@example.com"), + /// password: format!("Test!User@Password#{i}"), + /// }); + /// + /// let mut query_builder: QueryBuilder = QueryBuilder::new( + /// // Note the trailing space; most calls to `QueryBuilder` don't automatically insert + /// // spaces as that might interfere with identifiers or quoted strings where exact + /// // values may matter. + /// "SELECT * FROM users WHERE (id, username, email, password) in" + /// ); + /// + /// // Note that `.into_iter()` wasn't needed here since `users` is already an iterator. + /// query_builder.push_tuples(users.take(BIND_LIMIT / 4), |mut b, user| { + /// // If you wanted to bind these by-reference instead of by-value, + /// // you'd need an iterator that yields references that live as long as `query_builder`, + /// // e.g. collect it to a `Vec` first. + /// b.push_bind(user.id) + /// .push_bind(user.username) + /// .push_bind(user.email) + /// .push_bind(user.password); + /// }); + /// + /// let mut query = query_builder.build(); + /// + /// // You can then call `query.execute()`, `.fetch_one()`, `.fetch_all()`, etc. + /// // For the sake of demonstration though, we're just going to assert the contents + /// // of the query. + /// + /// // These are methods of the `Execute` trait, not normally meant to be called in user code. + /// let sql = query.sql(); + /// let arguments = query.take_arguments().unwrap(); + /// + /// assert!(sql.starts_with( + /// "SELECT * FROM users WHERE (id, username, email, password) in ((?, ?, ?, ?), (?, ?, ?, ?), " + /// )); + /// + /// assert!(sql.ends_with("(?, ?, ?, ?)) ")); + /// + /// // Not a normally exposed function, only used for this doctest. + /// // 65535 / 4 = 16383 (rounded down) + /// // 16383 * 4 = 65532 + /// assert_eq!(arguments.len(), 65532); + /// } + /// ``` + pub fn push_tuples(&mut self, tuples: I, mut push_tuple: F) -> &mut Self + where + I: IntoIterator, + F: FnMut(Separated<'_, DB, &'static str>, I::Item), + { + self.sanity_check(); + + self.push(" ("); + + let mut separated = self.separated(", "); + + for tuple in tuples { + separated.push("("); + + push_tuple(separated.query_builder.separated(", "), tuple); + + separated.push_unseparated(")"); + } + separated.push_unseparated(") "); + + separated.query_builder + } + + /// Produce an executable query from this builder. + /// + /// ### Note: Query is not Checked + /// It is your responsibility to ensure that you produce a syntactically correct query here, + /// this API has no way to check it for you. + /// + /// ### Note: Reuse + /// You can reuse this builder afterwards to amortize the allocation overhead of the query + /// string, however you must call [`.reset()`][Self::reset] first, which returns `Self` + /// to the state it was in immediately after [`new()`][Self::new]. + /// + /// Calling any other method but `.reset()` after `.build()` will panic for sanity reasons. + pub fn build(&mut self) -> Query<'_, DB, ::Arguments> { + self.sanity_check(); + + Query { + statement: Either::Left(self.sql()), + arguments: self.arguments.take().map(Ok), + database: PhantomData, + persistent: true, + } + } + + /// Produce an executable query from this builder. + /// + /// ### Note: Query is not Checked + /// It is your responsibility to ensure that you produce a syntactically correct query here, + /// this API has no way to check it for you. + /// + /// ### Note: Reuse + /// You can reuse this builder afterwards to amortize the allocation overhead of the query + /// string, however you must call [`.reset()`][Self::reset] first, which returns `Self` + /// to the state it was in immediately after [`new()`][Self::new]. + /// + /// Calling any other method but `.reset()` after `.build()` will panic for sanity reasons. + pub fn build_query_as<'q, T: FromRow<'q, DB::Row>>( + &'q mut self, + ) -> QueryAs<'q, DB, T, ::Arguments> { + QueryAs { + inner: self.build(), + output: PhantomData, + } + } + + /// Produce an executable query from this builder. + /// + /// ### Note: Query is not Checked + /// It is your responsibility to ensure that you produce a syntactically correct query here, + /// this API has no way to check it for you. + /// + /// ### Note: Reuse + /// You can reuse this builder afterwards to amortize the allocation overhead of the query + /// string, however you must call [`.reset()`][Self::reset] first, which returns `Self` + /// to the state it was in immediately after [`new()`][Self::new]. + /// + /// Calling any other method but `.reset()` after `.build()` will panic for sanity reasons. + pub fn build_query_scalar<'q, T>( + &'q mut self, + ) -> QueryScalar<'q, DB, T, ::Arguments> + where + DB: Database, + (T,): for<'r> FromRow<'r, DB::Row>, + { + QueryScalar { + inner: self.build_query_as(), + } + } + + /// Reset this `QueryBuilder` back to its initial state. + /// + /// The query is truncated to the initial fragment provided to [`new()`][Self::new] and + /// the bind arguments are reset. + pub fn reset(&mut self) -> &mut Self { + // Someone can hold onto a clone of `self.query`, to avoid panicking here we should just + // allocate a new `String`. + let query: &mut String = Arc::make_mut(&mut self.query); + query.truncate(self.init_len); + self.arguments = Some(Default::default()); + + self + } + + /// Get the current build SQL; **note**: may not be syntactically correct. + pub fn sql(&self) -> SqlStr { + AssertSqlSafe(self.query.clone()).into_sql_str() + } + + /// Deconstruct this `QueryBuilder`, returning the built SQL. May not be syntactically correct. + pub fn into_string(self) -> String { + Arc::unwrap_or_clone(self.query) + } + + /// Deconstruct this `QueryBuilder`, returning the built SQL. May not be syntactically correct. + pub fn into_sql(self) -> SqlStr { + AssertSqlSafe(self.query).into_sql_str() + } +} + +/// A wrapper around `QueryBuilder` for creating comma(or other token)-separated lists. +/// +/// See [`QueryBuilder::separated()`] for details. +#[allow(explicit_outlives_requirements)] +pub struct Separated<'qb, DB, Sep> +where + DB: Database, +{ + query_builder: &'qb mut QueryBuilder, + separator: Sep, + push_separator: bool, +} + +impl Separated<'_, DB, Sep> +where + DB: Database, + Sep: Display, +{ + /// Push the separator if applicable, and then the given SQL fragment. + /// + /// See [`QueryBuilder::push()`] for details. + pub fn push(&mut self, sql: impl Display) -> &mut Self { + if self.push_separator { + self.query_builder + .push(format_args!("{}{}", self.separator, sql)); + } else { + self.query_builder.push(sql); + self.push_separator = true; + } + + self + } + + /// Push a SQL fragment without a separator. + /// + /// Simply calls [`QueryBuilder::push()`] directly. + pub fn push_unseparated(&mut self, sql: impl Display) -> &mut Self { + self.query_builder.push(sql); + self + } + + /// Push the separator if applicable, then append a bind argument. + /// + /// See [`QueryBuilder::push_bind()`] for details. + pub fn push_bind<'t, T>(&mut self, value: T) -> &mut Self + where + T: Encode<'t, DB> + Type, + { + if self.push_separator { + self.query_builder.push(&self.separator); + } + + self.query_builder.push_bind(value); + self.push_separator = true; + + self + } + + /// Push a bind argument placeholder (`?` or `$N` for Postgres) and bind a value to it + /// without a separator. + /// + /// Simply calls [`QueryBuilder::push_bind()`] directly. + pub fn push_bind_unseparated<'t, T>(&mut self, value: T) -> &mut Self + where + T: Encode<'t, DB> + Type, + { + self.query_builder.push_bind(value); + self + } +} diff --git a/vendor/sqlx-core/src/query_scalar.rs b/vendor/sqlx-core/src/query_scalar.rs new file mode 100755 index 0000000..f760158 --- /dev/null +++ b/vendor/sqlx-core/src/query_scalar.rs @@ -0,0 +1,395 @@ +use either::Either; +use futures_core::stream::BoxStream; +use futures_util::{StreamExt, TryFutureExt, TryStreamExt}; + +use crate::arguments::IntoArguments; +use crate::database::{Database, HasStatementCache}; +use crate::encode::Encode; +use crate::error::{BoxDynError, Error}; +use crate::executor::{Execute, Executor}; +use crate::from_row::FromRow; +use crate::query_as::{ + query_as, query_as_with_result, query_statement_as, query_statement_as_with, QueryAs, +}; +use crate::sql_str::{SqlSafeStr, SqlStr}; +use crate::types::Type; + +/// A single SQL query as a prepared statement which extracts only the first column of each row. +/// Returned by [`query_scalar()`]. +#[must_use = "query must be executed to affect database"] +pub struct QueryScalar<'q, DB: Database, O, A> { + pub(crate) inner: QueryAs<'q, DB, (O,), A>, +} + +impl<'q, DB: Database, O: Send, A: Send> Execute<'q, DB> for QueryScalar<'q, DB, O, A> +where + A: 'q + IntoArguments, +{ + #[inline] + fn sql(self) -> SqlStr { + self.inner.sql() + } + + fn statement(&self) -> Option<&DB::Statement> { + self.inner.statement() + } + + #[inline] + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + self.inner.take_arguments() + } + + #[inline] + fn persistent(&self) -> bool { + Execute::persistent(&self.inner) + } +} + +impl<'q, DB: Database, O> QueryScalar<'q, DB, O, ::Arguments> { + /// Bind a value for use with this SQL query. + /// + /// See [`Query::bind`](crate::query::Query::bind). + pub fn bind + Type>(mut self, value: T) -> Self { + self.inner = self.inner.bind(value); + self + } +} + +impl QueryScalar<'_, DB, O, A> +where + DB: Database + HasStatementCache, +{ + /// If `true`, the statement will get prepared once and cached to the + /// connection's statement cache. + /// + /// If queried once with the flag set to `true`, all subsequent queries + /// matching the one with the flag will use the cached statement until the + /// cache is cleared. + /// + /// If `false`, the prepared statement will be closed after execution. + /// + /// Default: `true`. + pub fn persistent(mut self, value: bool) -> Self { + self.inner = self.inner.persistent(value); + self + } +} + +// FIXME: This is very close, nearly 1:1 with `Map` +// noinspection DuplicatedCode +impl<'q, DB, O, A> QueryScalar<'q, DB, O, A> +where + DB: Database, + O: Send + Unpin, + A: 'q + IntoArguments, + (O,): Send + Unpin + for<'r> FromRow<'r, DB::Row>, +{ + /// Execute the query and return the generated results as a stream. + #[inline] + pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + A: 'e, + O: 'e, + { + self.inner.fetch(executor).map_ok(|it| it.0).boxed() + } + + /// Execute multiple queries and return the generated results as a stream + /// from each query, in a stream. + #[inline] + #[deprecated = "Only the SQLite driver supports multiple statements in one prepared statement and that behavior is deprecated. Use `sqlx::raw_sql()` instead. See https://github.com/launchbadge/sqlx/issues/3108 for discussion."] + pub fn fetch_many<'e, 'c: 'e, E>( + self, + executor: E, + ) -> BoxStream<'e, Result, Error>> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + A: 'e, + O: 'e, + { + #[allow(deprecated)] + self.inner + .fetch_many(executor) + .map_ok(|v| v.map_right(|it| it.0)) + .boxed() + } + + /// Execute the query and return all the resulting rows collected into a [`Vec`]. + /// + /// ### Note: beware result set size. + /// This will attempt to collect the full result set of the query into memory. + /// + /// To avoid exhausting available memory, ensure the result set has a known upper bound, + /// e.g. using `LIMIT`. + #[inline] + pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + (O,): 'e, + A: 'e, + { + self.inner + .fetch(executor) + .map_ok(|it| it.0) + .try_collect() + .await + } + + /// Execute the query, returning the first row or [`Error::RowNotFound`] otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + #[inline] + pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + self.inner.fetch_one(executor).map_ok(|it| it.0).await + } + + /// Execute the query, returning the first row or `None` otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns at most one row + /// can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + #[inline] + pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result, Error> + where + 'q: 'e, + E: 'e + Executor<'c, Database = DB>, + DB: 'e, + O: 'e, + A: 'e, + { + Ok(self.inner.fetch_optional(executor).await?.map(|it| it.0)) + } +} + +/// Execute a single SQL query as a prepared statement (transparently cached) and extract the first +/// column of each row. +/// +/// Extracts the first column of each row. Additional columns are ignored. +/// Any type that implements `Type + Decode` may be used. +/// +/// For details about prepared statements and allowed SQL syntax, see [`query()`][crate::query::query]. +/// +/// ### Example: Simple Lookup +/// If you just want to look up a single value with little fanfare, this API is perfect for you: +/// +/// ```rust,no_run +/// # async fn example_lookup() -> Result<(), Box> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// use uuid::Uuid; +/// +/// // MySQL and MariaDB: use `?` +/// let user_id: Option = sqlx::query_scalar("SELECT user_id FROM users WHERE username = $1") +/// .bind("alice") +/// // Use `&mut` where `conn` is a connection or a transaction, or use `&` for a `Pool`. +/// .fetch_optional(&mut conn) +/// .await?; +/// +/// let user_id = user_id.ok_or("unknown user")?; +/// +/// # Ok(()) +/// # } +/// ``` +/// +/// Note how we're using `.fetch_optional()` because the lookup may return no results, +/// in which case we need to be able to handle an empty result set. +/// Any rows after the first are ignored. +/// +/// ### Example: `COUNT` +/// This API is the easiest way to invoke an aggregate query like `SELECT COUNT(*)`, because you +/// can conveniently extract the result: +/// +/// ```rust,no_run +/// # async fn example_count() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// // Note that `usize` is not used here because unsigned integers are generally not supported, +/// // and `usize` doesn't even make sense as a mapping because the database server may have +/// // a completely different architecture. +/// // +/// // `i64` is generally a safe choice for `COUNT`. +/// let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users WHERE accepted_tos IS TRUE") +/// // Use `&mut` where `conn` is a connection or a transaction, or use `&` for a `Pool`. +/// .fetch_one(&mut conn) +/// .await?; +/// +/// // The above is functionally equivalent to the following: +/// // Note the trailing comma, required for the compiler to recognize a 1-element tuple. +/// let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users WHERE accepted_tos IS TRUE") +/// .fetch_one(&mut conn) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +/// +/// ### Example: `EXISTS` +/// To test if a row exists or not, use `SELECT EXISTS()`: +/// +/// ```rust,no_run +/// # async fn example_exists() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// // MySQL and MariaDB: use `?` +/// let username_taken: bool = sqlx::query_scalar( +/// "SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)" +/// ) +/// .bind("alice") +/// // Use `&mut` where `conn` is a connection or a transaction, or use `&` for a `Pool`. +/// .fetch_one(&mut conn) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +/// +/// ### Example: Other Aggregates +/// Be aware that most other aggregate functions return `NULL` if the query yields an empty set: +/// +/// ```rust,no_run +/// # async fn example_aggregate() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// let max_upvotes: Option = sqlx::query_scalar("SELECT MAX(upvotes) FROM posts") +/// // Use `&mut` where `conn` is a connection or a transaction, or use `&` for a `Pool`. +/// .fetch_one(&mut conn) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +/// +/// Note how we're using `Option` with `.fetch_one()`, because we're always expecting one row +/// but the column value may be `NULL`. If no rows are returned, this will error. +/// +/// This is in contrast to using `.fetch_optional()` with `Option`, which implies that +/// we're expecting _either_ a row with a `i64` (`BIGINT`), _or_ no rows at all. +/// +/// Either way, any rows after the first are ignored. +/// +/// ### Example: `Vec` of Scalars +/// If you want to collect a single column from a query into a vector, +/// try `.fetch_all()`: +/// +/// ```rust,no_run +/// # async fn example_vec() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// let top_users: Vec = sqlx::query_scalar( +/// // Note the `LIMIT` to ensure that this doesn't return *all* users: +/// "SELECT username +/// FROM ( +/// SELECT SUM(upvotes) total, user_id +/// FROM posts +/// GROUP BY user_id +/// ) top_users +/// INNER JOIN users USING (user_id) +/// ORDER BY total DESC +/// LIMIT 10" +/// ) +/// // Use `&mut` where `conn` is a connection or a transaction, or use `&` for a `Pool`. +/// .fetch_all(&mut conn) +/// .await?; +/// +/// // `top_users` could be empty, too. +/// assert!(top_users.len() <= 10); +/// # Ok(()) +/// # } +/// ``` +#[inline] +pub fn query_scalar<'q, DB, O>( + sql: impl SqlSafeStr, +) -> QueryScalar<'q, DB, O, ::Arguments> +where + DB: Database, + (O,): for<'r> FromRow<'r, DB::Row>, +{ + QueryScalar { + inner: query_as(sql), + } +} + +/// Execute a SQL query as a prepared statement (transparently cached), with the given arguments, +/// and extract the first column of each row. +/// +/// See [`query_scalar()`] for details. +/// +/// For details about prepared statements and allowed SQL syntax, see [`query()`][crate::query::query]. +#[inline] +pub fn query_scalar_with<'q, DB, O, A>( + sql: impl SqlSafeStr, + arguments: A, +) -> QueryScalar<'q, DB, O, A> +where + DB: Database, + A: IntoArguments, + (O,): for<'r> FromRow<'r, DB::Row>, +{ + query_scalar_with_result(sql, Ok(arguments)) +} + +/// Same as [`query_scalar_with`] but takes arguments as Result +#[inline] +pub fn query_scalar_with_result<'q, DB, O, A>( + sql: impl SqlSafeStr, + arguments: Result, +) -> QueryScalar<'q, DB, O, A> +where + DB: Database, + A: IntoArguments, + (O,): for<'r> FromRow<'r, DB::Row>, +{ + QueryScalar { + inner: query_as_with_result(sql, arguments), + } +} + +// Make a SQL query from a statement, that is mapped to a concrete value. +pub fn query_statement_scalar( + statement: &DB::Statement, +) -> QueryScalar<'_, DB, O, ::Arguments> +where + DB: Database, + (O,): for<'r> FromRow<'r, DB::Row>, +{ + QueryScalar { + inner: query_statement_as(statement), + } +} + +// Make a SQL query from a statement, with the given arguments, that is mapped to a concrete value. +pub fn query_statement_scalar_with<'q, DB, O, A>( + statement: &'q DB::Statement, + arguments: A, +) -> QueryScalar<'q, DB, O, A> +where + DB: Database, + A: IntoArguments, + (O,): for<'r> FromRow<'r, DB::Row>, +{ + QueryScalar { + inner: query_statement_as_with(statement, arguments), + } +} diff --git a/vendor/sqlx-core/src/raw_sql.rs b/vendor/sqlx-core/src/raw_sql.rs new file mode 100755 index 0000000..0292885 --- /dev/null +++ b/vendor/sqlx-core/src/raw_sql.rs @@ -0,0 +1,250 @@ +use either::Either; +use futures_core::future::BoxFuture; +use futures_core::stream::BoxStream; + +use crate::database::Database; +use crate::error::BoxDynError; +use crate::executor::{Execute, Executor}; +use crate::sql_str::{SqlSafeStr, SqlStr}; +use crate::Error; + +// AUTHOR'S NOTE: I was just going to call this API `sql()` and `Sql`, respectively, +// but realized that would be extremely annoying to deal with as a SQLite user +// because IDE smart completion would always recommend the `Sql` type first. +// +// It doesn't really need a super convenient name anyway as it's not meant to be used very often. + +/// One or more raw SQL statements, separated by semicolons (`;`). +/// +/// See [`raw_sql()`] for details. +pub struct RawSql(SqlStr); + +/// Execute one or more statements as raw SQL, separated by semicolons (`;`). +/// +/// This interface can be used to execute both DML +/// (Data Manipulation Language: `SELECT`, `INSERT`, `UPDATE`, `DELETE` and variants) +/// as well as DDL (Data Definition Language: `CREATE TABLE`, `ALTER TABLE`, etc). +/// +/// This will not create or cache any prepared statements. +/// +/// ### Note: singular DML queries, prefer `query()` +/// This API does not use prepared statements, so usage of it is missing out on their benefits. +/// +/// Prefer [`query()`][crate::query::query] instead if executing a single query. +/// +/// It's also possible to combine multiple DML queries into one for use with `query()`: +/// +/// ##### Common Table Expressions (CTEs: i.e The `WITH` Clause) +/// Common Table Expressions effectively allow you to define aliases for queries +/// that can be referenced like temporary tables: +/// +/// ```sql +/// WITH inserted_foos AS ( +/// -- Note that only Postgres allows data-modifying statements in CTEs +/// INSERT INTO foo (bar_id) VALUES ($1) +/// RETURNING foo_id, bar_id +/// ) +/// SELECT foo_id, bar_id, bar +/// FROM inserted_foos +/// INNER JOIN bar USING (bar_id) +/// ``` +/// +/// It's important to note that data modifying statements (`INSERT`, `UPDATE`, `DELETE`) may +/// behave differently than expected. In Postgres, all data-modifying subqueries in a `WITH` +/// clause execute with the same view of the data; they *cannot* see each other's modifications. +/// +/// MySQL, MariaDB and SQLite appear to *only* allow `SELECT` statements in CTEs. +/// +/// See the appropriate entry in your database's manual for details: +/// * [MySQL](https://dev.mysql.com/doc/refman/8.0/en/with.html) +/// * [MariaDB](https://mariadb.com/kb/en/with/) +/// * [Postgres](https://www.postgresql.org/docs/current/queries-with.html) +/// * [SQLite](https://www.sqlite.org/lang_with.html) +/// +/// ##### `UNION`/`INTERSECT`/`EXCEPT` +/// You can also use various set-theory operations on queries, +/// including `UNION ALL` which simply concatenates their results. +/// +/// See the appropriate entry in your database's manual for details: +/// * [MySQL](https://dev.mysql.com/doc/refman/8.0/en/set-operations.html) +/// * [MariaDB](https://mariadb.com/kb/en/joins-subqueries/) +/// * [Postgres](https://www.postgresql.org/docs/current/queries-union.html) +/// * [SQLite](https://www.sqlite.org/lang_select.html#compound_select_statements) +/// +/// ### Note: query parameters are not supported. +/// Query parameters require the use of prepared statements which this API does support. +/// +/// If you require dynamic input data in your SQL, you can use `format!()` but **be very careful +/// doing this with user input**. SQLx does **not** provide escaping or sanitization for inserting +/// dynamic input into queries this way. +/// +/// See [`query()`][crate::query::query] for details. +/// +/// ### Note: multiple statements and autocommit. +/// By default, when you use this API to execute a SQL string containing multiple statements +/// separated by semicolons (`;`), the database server will treat those statements as all executing +/// within the same transaction block, i.e. wrapped in `BEGIN` and `COMMIT`: +/// +/// ```rust,no_run +/// # async fn example() -> sqlx::Result<()> { +/// let mut conn: sqlx::PgConnection = todo!("e.g. PgConnection::connect()"); +/// +/// sqlx::raw_sql( +/// // Imagine we're moving data from one table to another: +/// // Implicit `BEGIN;` +/// "UPDATE foo SET bar = foobar.bar FROM foobar WHERE foobar.foo_id = foo.id;\ +/// DELETE FROM foobar;" +/// // Implicit `COMMIT;` +/// ) +/// .execute(&mut conn) +/// .await?; +/// +/// # Ok(()) +/// # } +/// ``` +/// +/// If one statement triggers an error, the whole script aborts and rolls back. +/// You can include explicit `BEGIN` and `COMMIT` statements in the SQL string +/// to designate units that can be committed or rolled back piecemeal. +/// +/// This also allows for a rudimentary form of pipelining as the whole SQL string is sent in one go. +/// +/// ##### MySQL and MariaDB: DDL implicitly commits! +/// MySQL and MariaDB do not support DDL in transactions. Instead, any active transaction is +/// immediately and implicitly committed by the database server when executing a DDL statement. +/// Beware of this behavior. +/// +/// See [MySQL manual, section 13.3.3: Statements That Cause an Implicit Commit](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html) for details. +/// See also: [MariaDB manual: SQL statements That Cause an Implicit Commit](https://mariadb.com/kb/en/sql-statements-that-cause-an-implicit-commit/). +pub fn raw_sql(sql: impl SqlSafeStr) -> RawSql { + RawSql(sql.into_sql_str()) +} + +impl Execute<'_, DB> for RawSql { + fn sql(self) -> SqlStr { + self.0 + } + + fn statement(&self) -> Option<&::Statement> { + None + } + + fn take_arguments(&mut self) -> Result::Arguments>, BoxDynError> { + Ok(None) + } + + fn persistent(&self) -> bool { + false + } +} + +impl RawSql { + /// Execute the SQL string and return the total number of rows affected. + #[inline] + pub async fn execute<'e, E, DB>(self, executor: E) -> crate::Result + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.execute(self).await + } + + /// Execute the SQL string. Returns a stream which gives the number of rows affected for each statement in the string. + #[inline] + pub fn execute_many<'e, E, DB>( + self, + executor: E, + ) -> BoxStream<'e, crate::Result> + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.execute_many(self) + } + + /// Execute the SQL string and return the generated results as a stream. + /// + /// If the string contains multiple statements, their results will be concatenated together. + #[inline] + pub fn fetch<'e, E, DB>(self, executor: E) -> BoxStream<'e, Result> + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.fetch(self) + } + + /// Execute the SQL string and return the generated results as a stream. + /// + /// For each query in the stream, any generated rows are returned first, + /// then the `QueryResult` with the number of rows affected. + #[inline] + pub fn fetch_many<'e, E, DB>( + self, + executor: E, + ) -> BoxStream<'e, Result, Error>> + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.fetch_many(self) + } + + /// Execute the SQL string and return all the resulting rows collected into a [`Vec`]. + /// + /// ### Note: beware result set size. + /// This will attempt to collect the full result set of the query into memory. + /// + /// To avoid exhausting available memory, ensure the result set has a known upper bound, + /// e.g. using `LIMIT`. + #[inline] + pub fn fetch_all<'e, E, DB>(self, executor: E) -> BoxFuture<'e, crate::Result>> + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.fetch_all(self) + } + + /// Execute the SQL string, returning the first row or [`Error::RowNotFound`] otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns + /// at most one row can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + #[inline] + pub fn fetch_one<'e, E, DB>(self, executor: E) -> BoxFuture<'e, crate::Result> + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.fetch_one(self) + } + + /// Execute the SQL string, returning the first row or [`None`] otherwise. + /// + /// ### Note: for best performance, ensure the query returns at most one row. + /// Depending on the driver implementation, if your query can return more than one row, + /// it may lead to wasted CPU time and bandwidth on the database server. + /// + /// Even when the driver implementation takes this into account, ensuring the query returns + /// at most one row can result in a more optimal query plan. + /// + /// If your query has a `WHERE` clause filtering a unique column by a single value, you're good. + /// + /// Otherwise, you might want to add `LIMIT 1` to your query. + #[inline] + pub async fn fetch_optional<'e, E, DB>(self, executor: E) -> crate::Result> + where + DB: Database, + E: Executor<'e, Database = DB>, + { + executor.fetch_optional(self).await + } +} diff --git a/vendor/sqlx-core/src/row.rs b/vendor/sqlx-core/src/row.rs new file mode 100755 index 0000000..6077b9a --- /dev/null +++ b/vendor/sqlx-core/src/row.rs @@ -0,0 +1,208 @@ +use crate::column::{Column, ColumnIndex}; +use crate::database::Database; +use crate::decode::Decode; +use crate::error::{mismatched_types, Error}; + +use crate::type_checking::TypeChecking; +use crate::type_info::TypeInfo; +use crate::types::Type; +use crate::value::ValueRef; + +/// Represents a single row from the database. +/// +/// [`FromRow`]: crate::row::FromRow +/// [`Query::fetch`]: crate::query::Query::fetch +pub trait Row: Unpin + Send + Sync + 'static { + type Database: Database; + + /// Returns `true` if this row has no columns. + #[inline] + fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the number of columns in this row. + #[inline] + fn len(&self) -> usize { + self.columns().len() + } + + /// Gets the column information at `index`. + /// + /// A string index can be used to access a column by name and a `usize` index + /// can be used to access a column by position. + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// See [`try_column`](Self::try_column) for a non-panicking version. + fn column(&self, index: I) -> &::Column + where + I: ColumnIndex, + { + self.try_column(index).unwrap() + } + + /// Gets the column information at `index` or a `ColumnIndexOutOfBounds` error if out of bounds. + fn try_column(&self, index: I) -> Result<&::Column, Error> + where + I: ColumnIndex, + { + Ok(&self.columns()[index.index(self)?]) + } + + /// Gets all columns in this statement. + fn columns(&self) -> &[::Column]; + + /// Index into the database row and decode a single value. + /// + /// A string index can be used to access a column by name and a `usize` index + /// can be used to access a column by position. + /// + /// # Panics + /// + /// Panics if the column does not exist or its value cannot be decoded into the requested type. + /// See [`try_get`](Self::try_get) for a non-panicking version. + /// + #[inline] + #[track_caller] + fn get<'r, T, I>(&'r self, index: I) -> T + where + I: ColumnIndex, + T: Decode<'r, Self::Database> + Type, + { + self.try_get::(index).unwrap() + } + + /// Index into the database row and decode a single value. + /// + /// Unlike [`get`](Self::get), this method does not check that the type + /// being returned from the database is compatible with the Rust type and blindly tries + /// to decode the value. + /// + /// # Panics + /// + /// Panics if the column does not exist or its value cannot be decoded into the requested type. + /// See [`try_get_unchecked`](Self::try_get_unchecked) for a non-panicking version. + /// + #[inline] + fn get_unchecked<'r, T, I>(&'r self, index: I) -> T + where + I: ColumnIndex, + T: Decode<'r, Self::Database>, + { + self.try_get_unchecked::(index).unwrap() + } + + /// Index into the database row and decode a single value. + /// + /// A string index can be used to access a column by name and a `usize` index + /// can be used to access a column by position. + /// + /// # Errors + /// + /// * [`ColumnNotFound`] if the column by the given name was not found. + /// * [`ColumnIndexOutOfBounds`] if the `usize` index was greater than the number of columns in the row. + /// * [`ColumnDecode`] if the value could not be decoded into the requested type. + /// + /// [`ColumnDecode`]: Error::ColumnDecode + /// [`ColumnNotFound`]: Error::ColumnNotFound + /// [`ColumnIndexOutOfBounds`]: Error::ColumnIndexOutOfBounds + /// + fn try_get<'r, T, I>(&'r self, index: I) -> Result + where + I: ColumnIndex, + T: Decode<'r, Self::Database> + Type, + { + let value = self.try_get_raw(&index)?; + + if !value.is_null() { + let ty = value.type_info(); + + if !ty.is_null() && !T::compatible(&ty) { + return Err(Error::ColumnDecode { + index: format!("{index:?}"), + source: mismatched_types::(&ty), + }); + } + } + + T::decode(value).map_err(|source| Error::ColumnDecode { + index: format!("{index:?}"), + source, + }) + } + + /// Index into the database row and decode a single value. + /// + /// Unlike [`try_get`](Self::try_get), this method does not check that the type + /// being returned from the database is compatible with the Rust type and blindly tries + /// to decode the value. + /// + /// # Errors + /// + /// * [`ColumnNotFound`] if the column by the given name was not found. + /// * [`ColumnIndexOutOfBounds`] if the `usize` index was greater than the number of columns in the row. + /// * [`ColumnDecode`] if the value could not be decoded into the requested type. + /// + /// [`ColumnDecode`]: Error::ColumnDecode + /// [`ColumnNotFound`]: Error::ColumnNotFound + /// [`ColumnIndexOutOfBounds`]: Error::ColumnIndexOutOfBounds + /// + #[inline] + fn try_get_unchecked<'r, T, I>(&'r self, index: I) -> Result + where + I: ColumnIndex, + T: Decode<'r, Self::Database>, + { + let value = self.try_get_raw(&index)?; + + T::decode(value).map_err(|source| Error::ColumnDecode { + index: format!("{index:?}"), + source, + }) + } + + /// Index into the database row and decode a single value. + /// + /// # Errors + /// + /// * [`ColumnNotFound`] if the column by the given name was not found. + /// * [`ColumnIndexOutOfBounds`] if the `usize` index was greater than the number of columns in the row. + /// + /// [`ColumnNotFound`]: Error::ColumnNotFound + /// [`ColumnIndexOutOfBounds`]: Error::ColumnIndexOutOfBounds + /// + fn try_get_raw(&self, index: I) -> Result<::ValueRef<'_>, Error> + where + I: ColumnIndex; +} + +pub fn debug_row(row: &R, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result +where + R: Row, + usize: ColumnIndex, + ::Database: TypeChecking, +{ + write!(f, "{} ", std::any::type_name::())?; + + let mut debug_map = f.debug_map(); + + for column in row.columns().iter() { + match row.try_get_raw(column.ordinal()) { + Ok(value) => { + debug_map.entry( + &column.name(), + &::Database::fmt_value_debug( + &<::Database as Database>::ValueRef::to_owned(&value), + ), + ); + } + Err(error) => { + debug_map.entry(&column.name(), &format!("decode error: {error:?}")); + } + } + } + + debug_map.finish() +} diff --git a/vendor/sqlx-core/src/rt/mod.rs b/vendor/sqlx-core/src/rt/mod.rs new file mode 100755 index 0000000..273a1bf --- /dev/null +++ b/vendor/sqlx-core/src/rt/mod.rs @@ -0,0 +1,214 @@ +use std::future::Future; +use std::marker::PhantomData; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + +use cfg_if::cfg_if; + +#[cfg(feature = "_rt-async-io")] +pub mod rt_async_io; + +#[cfg(feature = "_rt-tokio")] +pub mod rt_tokio; + +#[derive(Debug, thiserror::Error)] +#[error("operation timed out")] +pub struct TimeoutError; + +pub enum JoinHandle { + #[cfg(feature = "_rt-async-std")] + AsyncStd(async_std::task::JoinHandle), + + #[cfg(feature = "_rt-tokio")] + Tokio(tokio::task::JoinHandle), + + // Implementation shared by `smol` and `async-global-executor` + #[cfg(feature = "_rt-async-task")] + AsyncTask(Option>), + + // `PhantomData` requires `T: Unpin` + _Phantom(PhantomData T>), +} + +pub async fn timeout(duration: Duration, f: F) -> Result { + #[cfg(debug_assertions)] + let f = Box::pin(f); + + #[cfg(feature = "_rt-tokio")] + if rt_tokio::available() { + return tokio::time::timeout(duration, f) + .await + .map_err(|_| TimeoutError); + } + + cfg_if! { + if #[cfg(feature = "_rt-async-io")] { + rt_async_io::timeout(duration, f).await + } else { + missing_rt((duration, f)) + } + } +} + +pub async fn sleep(duration: Duration) { + #[cfg(feature = "_rt-tokio")] + if rt_tokio::available() { + return tokio::time::sleep(duration).await; + } + + cfg_if! { + if #[cfg(feature = "_rt-async-io")] { + rt_async_io::sleep(duration).await + } else { + missing_rt(duration) + } + } +} + +#[track_caller] +pub fn spawn(fut: F) -> JoinHandle +where + F: Future + Send + 'static, + F::Output: Send + 'static, +{ + #[cfg(feature = "_rt-tokio")] + if let Ok(handle) = tokio::runtime::Handle::try_current() { + return JoinHandle::Tokio(handle.spawn(fut)); + } + + cfg_if! { + if #[cfg(feature = "_rt-async-global-executor")] { + JoinHandle::AsyncTask(Some(async_global_executor::spawn(fut))) + } else if #[cfg(feature = "_rt-smol")] { + JoinHandle::AsyncTask(Some(smol::spawn(fut))) + } else if #[cfg(feature = "_rt-async-std")] { + JoinHandle::AsyncStd(async_std::task::spawn(fut)) + } else { + missing_rt(fut) + } + } +} + +#[track_caller] +pub fn spawn_blocking(f: F) -> JoinHandle +where + F: FnOnce() -> R + Send + 'static, + R: Send + 'static, +{ + #[cfg(feature = "_rt-tokio")] + if let Ok(handle) = tokio::runtime::Handle::try_current() { + return JoinHandle::Tokio(handle.spawn_blocking(f)); + } + + cfg_if! { + if #[cfg(feature = "_rt-async-global-executor")] { + JoinHandle::AsyncTask(Some(async_global_executor::spawn_blocking(f))) + } else if #[cfg(feature = "_rt-smol")] { + JoinHandle::AsyncTask(Some(smol::unblock(f))) + } else if #[cfg(feature = "_rt-async-std")] { + JoinHandle::AsyncStd(async_std::task::spawn_blocking(f)) + } else { + missing_rt(f) + } + } +} + +pub async fn yield_now() { + #[cfg(feature = "_rt-tokio")] + if rt_tokio::available() { + return tokio::task::yield_now().await; + } + + // `smol`, `async-global-executor`, and `async-std` all have the same implementation for this. + // + // By immediately signaling the waker and then returning `Pending`, + // this essentially just moves the task to the back of the runnable queue. + // + // There isn't any special integration with the runtime, so we can save code by rolling our own. + // + // (Tokio's implementation is nearly identical too, + // but has additional integration with `tracing` which may be useful for debugging.) + let mut yielded = false; + + std::future::poll_fn(|cx| { + if !yielded { + yielded = true; + cx.waker().wake_by_ref(); + Poll::Pending + } else { + Poll::Ready(()) + } + }) + .await +} + +#[track_caller] +pub fn test_block_on(f: F) -> F::Output { + cfg_if! { + if #[cfg(feature = "_rt-async-io")] { + async_io::block_on(f) + } else if #[cfg(feature = "_rt-tokio")] { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("failed to start Tokio runtime") + .block_on(f) + } else { + missing_rt(f) + } + } +} + +#[track_caller] +pub const fn missing_rt(_unused: T) -> ! { + if cfg!(feature = "_rt-tokio") { + panic!("this functionality requires a Tokio context") + } + + panic!("one of the `runtime` features of SQLx must be enabled") +} + +impl Future for JoinHandle { + type Output = T; + + #[track_caller] + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + match &mut *self { + #[cfg(feature = "_rt-async-std")] + Self::AsyncStd(handle) => Pin::new(handle).poll(cx), + + #[cfg(feature = "_rt-async-task")] + Self::AsyncTask(task) => Pin::new(task) + .as_pin_mut() + .expect("BUG: task taken") + .poll(cx), + + #[cfg(feature = "_rt-tokio")] + Self::Tokio(handle) => Pin::new(handle) + .poll(cx) + .map(|res| res.expect("spawned task panicked")), + + Self::_Phantom(_) => { + let _ = cx; + unreachable!("runtime should have been checked on spawn") + } + } + } +} + +impl Drop for JoinHandle { + fn drop(&mut self) { + match self { + // `async_task` cancels on-drop by default. + // We need to explicitly detach to match Tokio and `async-std`. + #[cfg(feature = "_rt-async-task")] + Self::AsyncTask(task) => { + if let Some(task) = task.take() { + task.detach(); + } + } + _ => (), + } + } +} diff --git a/vendor/sqlx-core/src/rt/rt_async_io/mod.rs b/vendor/sqlx-core/src/rt/rt_async_io/mod.rs new file mode 100755 index 0000000..5e4d707 --- /dev/null +++ b/vendor/sqlx-core/src/rt/rt_async_io/mod.rs @@ -0,0 +1,4 @@ +mod socket; + +mod timeout; +pub use timeout::*; diff --git a/vendor/sqlx-core/src/rt/rt_async_io/socket.rs b/vendor/sqlx-core/src/rt/rt_async_io/socket.rs new file mode 100755 index 0000000..5837d30 --- /dev/null +++ b/vendor/sqlx-core/src/rt/rt_async_io/socket.rs @@ -0,0 +1,55 @@ +use crate::net::Socket; + +use std::io; +use std::io::{Read, Write}; +use std::net::{Shutdown, TcpStream}; +use std::task::{Context, Poll}; + +use async_io::Async; + +use crate::io::ReadBuf; + +impl Socket for Async { + fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result { + self.get_ref().read(buf.init_mut()) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + self.get_ref().write(buf) + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_readable(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_writable(cx) + } + + fn poll_shutdown(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(self.get_ref().shutdown(Shutdown::Both)) + } +} + +#[cfg(unix)] +impl Socket for Async { + fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result { + self.get_ref().read(buf.init_mut()) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + self.get_ref().write(buf) + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_readable(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.poll_writable(cx) + } + + fn poll_shutdown(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(self.get_ref().shutdown(Shutdown::Both)) + } +} diff --git a/vendor/sqlx-core/src/rt/rt_async_io/timeout.rs b/vendor/sqlx-core/src/rt/rt_async_io/timeout.rs new file mode 100755 index 0000000..b4a7790 --- /dev/null +++ b/vendor/sqlx-core/src/rt/rt_async_io/timeout.rs @@ -0,0 +1,20 @@ +use std::{future::Future, pin::pin, time::Duration}; + +use futures_util::future::{select, Either}; + +use crate::rt::TimeoutError; + +pub async fn sleep(duration: Duration) { + timeout_future(duration).await; +} + +pub async fn timeout(duration: Duration, future: F) -> Result { + match select(pin!(future), timeout_future(duration)).await { + Either::Left((result, _)) => Ok(result), + Either::Right(_) => Err(TimeoutError), + } +} + +fn timeout_future(duration: Duration) -> impl Future { + async_io::Timer::after(duration) +} diff --git a/vendor/sqlx-core/src/rt/rt_tokio/mod.rs b/vendor/sqlx-core/src/rt/rt_tokio/mod.rs new file mode 100755 index 0000000..ce69945 --- /dev/null +++ b/vendor/sqlx-core/src/rt/rt_tokio/mod.rs @@ -0,0 +1,5 @@ +mod socket; + +pub fn available() -> bool { + tokio::runtime::Handle::try_current().is_ok() +} diff --git a/vendor/sqlx-core/src/rt/rt_tokio/socket.rs b/vendor/sqlx-core/src/rt/rt_tokio/socket.rs new file mode 100755 index 0000000..bb57cbf --- /dev/null +++ b/vendor/sqlx-core/src/rt/rt_tokio/socket.rs @@ -0,0 +1,55 @@ +use std::io; +use std::pin::Pin; +use std::task::{Context, Poll}; + +use tokio::io::AsyncWrite; +use tokio::net::TcpStream; + +use crate::io::ReadBuf; +use crate::net::Socket; + +impl Socket for TcpStream { + fn try_read(&mut self, mut buf: &mut dyn ReadBuf) -> io::Result { + // Requires `&mut impl BufMut` + self.try_read_buf(&mut buf) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + (*self).try_write(buf) + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + (*self).poll_read_ready(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + (*self).poll_write_ready(cx) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll> { + Pin::new(self).poll_shutdown(cx) + } +} + +#[cfg(unix)] +impl Socket for tokio::net::UnixStream { + fn try_read(&mut self, mut buf: &mut dyn ReadBuf) -> io::Result { + self.try_read_buf(&mut buf) + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result { + (*self).try_write(buf) + } + + fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + (*self).poll_read_ready(cx) + } + + fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + (*self).poll_write_ready(cx) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll> { + Pin::new(self).poll_shutdown(cx) + } +} diff --git a/vendor/sqlx-core/src/sql_str.rs b/vendor/sqlx-core/src/sql_str.rs new file mode 100755 index 0000000..53e4042 --- /dev/null +++ b/vendor/sqlx-core/src/sql_str.rs @@ -0,0 +1,210 @@ +use std::borrow::{Borrow, Cow}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +/// A SQL string that is safe to execute on a database connection. +/// +/// A "safe" SQL string is one that is unlikely to contain a [SQL injection vulnerability][injection]. +/// +/// In practice, this means a string type that is unlikely to contain dynamic data or user input. +/// +/// `&'static str` is the only string type that satisfies the requirements of this trait +/// (ignoring [`String::leak()`] which has niche use-cases) and so is the only string type that +/// natively implements this trait by default. +/// +/// For other string types, use [`AssertSqlSafe`] to assert this property. +/// This is the only intended way to pass an owned `String` to [`query()`] and its related functions +/// as well as [`raw_sql()`]. +/// +/// The maintainers of SQLx take no responsibility for any data leaks or loss resulting from misuse +/// of this API. +/// +/// ### Motivation +/// This is designed to act as a speed bump against naively using `format!()` to add dynamic data +/// or user input to a query, which is a classic vector for SQL injection as SQLx does not +/// provide any sort of escaping or sanitization (which would have to be specially implemented +/// for each database flavor/locale). +/// +/// The recommended way to incorporate dynamic data or user input in a query is to use +/// bind parameters, which requires the query to execute as a prepared statement. +/// See [`query()`] for details. +/// +/// This trait and [`AssertSqlSafe`] are intentionally analogous to +/// [`std::panic::UnwindSafe`] and [`std::panic::AssertUnwindSafe`], respectively. +/// +/// [injection]: https://en.wikipedia.org/wiki/SQL_injection +/// [`query()`]: crate::query::query +/// [`raw_sql()`]: crate::raw_sql::raw_sql +#[diagnostic::on_unimplemented( + label = "dynamic SQL string", + message = "dynamic SQL strings should be audited for possible injections", + note = "prefer literal SQL strings with bind parameters or `QueryBuilder` to add dynamic data to a query. + +To bypass this error, manually audit for potential injection vulnerabilities and wrap with `AssertSqlSafe()`. +For details, see the docs for `SqlSafeStr`.\n", + note = "this trait is only implemented for `&'static str`, not all `&str` like the compiler error may suggest" +)] +pub trait SqlSafeStr { + /// Convert `self` to a [`SqlStr`]. + fn into_sql_str(self) -> SqlStr; +} + +impl SqlSafeStr for &'static str { + #[inline] + fn into_sql_str(self) -> SqlStr { + SqlStr(Repr::Static(self)) + } +} + +/// Assert that a query string is safe to execute on a database connection. +/// +/// Using this API means that **you** have made sure that the string contents do not contain a +/// [SQL injection vulnerability][injection]. It means that, if the string was constructed +/// dynamically, and/or from user input, you have taken care to sanitize the input yourself. +/// SQLx does not provide any sort of sanitization; the design of SQLx prefers the use +/// of prepared statements for dynamic input. +/// +/// The maintainers of SQLx take no responsibility for any data leaks or loss resulting from misuse +/// of this API. **Use at your own risk.** +/// +/// Note that `&'static str` implements [`SqlSafeStr`] directly and so does not need to be wrapped +/// with this type. +/// +/// [injection]: https://en.wikipedia.org/wiki/SQL_injection +pub struct AssertSqlSafe(pub T); + +/// Note: copies the string. +/// +/// It is recommended to pass one of the supported owned string types instead. +impl SqlSafeStr for AssertSqlSafe<&str> { + #[inline] + fn into_sql_str(self) -> SqlStr { + SqlStr(Repr::Arced(self.0.into())) + } +} +impl SqlSafeStr for AssertSqlSafe { + #[inline] + fn into_sql_str(self) -> SqlStr { + SqlStr(Repr::Owned(self.0)) + } +} + +impl SqlSafeStr for AssertSqlSafe> { + #[inline] + fn into_sql_str(self) -> SqlStr { + SqlStr(Repr::Boxed(self.0)) + } +} + +// Note: this is not implemented for `Rc` because it would make `QueryString: !Send`. +impl SqlSafeStr for AssertSqlSafe> { + #[inline] + fn into_sql_str(self) -> SqlStr { + SqlStr(Repr::Arced(self.0)) + } +} + +impl SqlSafeStr for AssertSqlSafe> { + #[inline] + fn into_sql_str(self) -> SqlStr { + SqlStr(Repr::ArcString(self.0)) + } +} + +impl SqlSafeStr for AssertSqlSafe> { + fn into_sql_str(self) -> SqlStr { + match self.0 { + Cow::Borrowed(str) => str.into_sql_str(), + Cow::Owned(str) => AssertSqlSafe(str).into_sql_str(), + } + } +} + +/// A SQL string that is ready to execute on a database connection. +/// +/// This is essentially `Cow<'static, str>` but which can be constructed from additional types +/// without copying. +/// +/// See [`SqlSafeStr`] for details. +#[derive(Debug)] +pub struct SqlStr(Repr); + +#[derive(Debug)] +enum Repr { + /// We need a variant to memoize when we already have a static string, so we don't copy it. + Static(&'static str), + /// Thanks to the new niche in `String`, this doesn't increase the size beyond 3 words. + /// We essentially get all these variants for free. + Owned(String), + Boxed(Box), + Arced(Arc), + /// Allows for dynamic shared ownership with `query_builder`. + ArcString(Arc), +} + +impl Clone for SqlStr { + fn clone(&self) -> Self { + Self(match &self.0 { + Repr::Static(s) => Repr::Static(s), + Repr::Arced(s) => Repr::Arced(s.clone()), + // If `.clone()` gets called once, assume it might get called again. + _ => Repr::Arced(self.as_str().into()), + }) + } +} + +impl SqlSafeStr for SqlStr { + #[inline] + fn into_sql_str(self) -> SqlStr { + self + } +} + +impl SqlStr { + /// Borrow the inner query string. + #[inline] + pub fn as_str(&self) -> &str { + match &self.0 { + Repr::Static(s) => s, + Repr::Owned(s) => s, + Repr::Boxed(s) => s, + Repr::Arced(s) => s, + Repr::ArcString(s) => s, + } + } + + pub const fn from_static(sql: &'static str) -> Self { + SqlStr(Repr::Static(sql)) + } +} + +impl AsRef for SqlStr { + #[inline] + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl Borrow for SqlStr { + #[inline] + fn borrow(&self) -> &str { + self.as_str() + } +} + +impl PartialEq for SqlStr +where + T: AsRef, +{ + fn eq(&self, other: &T) -> bool { + self.as_str() == other.as_ref() + } +} + +impl Eq for SqlStr {} + +impl Hash for SqlStr { + fn hash(&self, state: &mut H) { + self.as_str().hash(state) + } +} diff --git a/vendor/sqlx-core/src/statement.rs b/vendor/sqlx-core/src/statement.rs new file mode 100755 index 0000000..92ae8a6 --- /dev/null +++ b/vendor/sqlx-core/src/statement.rs @@ -0,0 +1,173 @@ +use crate::arguments::IntoArguments; +use crate::column::ColumnIndex; +use crate::database::Database; +use crate::error::Error; +use crate::from_row::FromRow; +use crate::query::Query; +use crate::query_as::QueryAs; +use crate::query_scalar::QueryScalar; +use crate::sql_str::SqlStr; +use either::Either; + +/// An explicitly prepared statement. +/// +/// Statements are prepared and cached by default, per connection. This type allows you to +/// look at that cache in-between the statement being prepared and it being executed. This contains +/// the expected columns to be returned and the expected parameter types (if available). +/// +/// Statements can be re-used with any connection and on first-use it will be re-prepared and +/// cached within the connection. +pub trait Statement: Send + Sync + Clone { + type Database: Database; + + /// Get the original SQL text used to create this statement. + fn into_sql(self) -> SqlStr; + + /// Get the original SQL text used to create this statement. + fn sql(&self) -> &SqlStr; + + /// Get the expected parameters for this statement. + /// + /// The information returned depends on what is available from the driver. SQLite can + /// only tell us the number of parameters. PostgreSQL can give us full type information. + fn parameters(&self) -> Option::TypeInfo], usize>>; + + /// Get the columns expected to be returned by executing this statement. + fn columns(&self) -> &[::Column]; + + /// Gets the column information at `index`. + /// + /// A string index can be used to access a column by name and a `usize` index + /// can be used to access a column by position. + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// See [`try_column`](Self::try_column) for a non-panicking version. + fn column(&self, index: I) -> &::Column + where + I: ColumnIndex, + { + self.try_column(index).unwrap() + } + + /// Gets the column information at `index` or a `ColumnIndexOutOfBounds` error if out of bounds. + fn try_column(&self, index: I) -> Result<&::Column, Error> + where + I: ColumnIndex, + { + Ok(&self.columns()[index.index(self)?]) + } + + fn query(&self) -> Query<'_, Self::Database, ::Arguments>; + + fn query_with(&self, arguments: A) -> Query<'_, Self::Database, A> + where + A: IntoArguments; + + fn query_as( + &self, + ) -> QueryAs<'_, Self::Database, O, ::Arguments> + where + O: for<'r> FromRow<'r, ::Row>; + + fn query_as_with<'s, O, A>(&'s self, arguments: A) -> QueryAs<'s, Self::Database, O, A> + where + O: for<'r> FromRow<'r, ::Row>, + A: IntoArguments; + + fn query_scalar( + &self, + ) -> QueryScalar<'_, Self::Database, O, ::Arguments> + where + (O,): for<'r> FromRow<'r, ::Row>; + + fn query_scalar_with<'s, O, A>(&'s self, arguments: A) -> QueryScalar<'s, Self::Database, O, A> + where + (O,): for<'r> FromRow<'r, ::Row>, + A: IntoArguments; +} + +#[macro_export] +macro_rules! impl_statement_query { + ($A:ty) => { + #[inline] + fn query(&self) -> $crate::query::Query<'_, Self::Database, $A> { + $crate::query::query_statement(self) + } + + #[inline] + fn query_with(&self, arguments: A) -> $crate::query::Query<'_, Self::Database, A> + where + A: $crate::arguments::IntoArguments, + { + $crate::query::query_statement_with(self, arguments) + } + + #[inline] + fn query_as( + &self, + ) -> $crate::query_as::QueryAs< + '_, + Self::Database, + O, + ::Arguments, + > + where + O: for<'r> $crate::from_row::FromRow< + 'r, + ::Row, + >, + { + $crate::query_as::query_statement_as(self) + } + + #[inline] + fn query_as_with<'s, O, A>( + &'s self, + arguments: A, + ) -> $crate::query_as::QueryAs<'s, Self::Database, O, A> + where + O: for<'r> $crate::from_row::FromRow< + 'r, + ::Row, + >, + A: $crate::arguments::IntoArguments, + { + $crate::query_as::query_statement_as_with(self, arguments) + } + + #[inline] + fn query_scalar( + &self, + ) -> $crate::query_scalar::QueryScalar< + '_, + Self::Database, + O, + ::Arguments, + > + where + (O,): for<'r> $crate::from_row::FromRow< + 'r, + ::Row, + >, + { + $crate::query_scalar::query_statement_scalar(self) + } + + #[inline] + fn query_scalar_with<'s, O, A>( + &'s self, + arguments: A, + ) -> $crate::query_scalar::QueryScalar<'s, Self::Database, O, A> + where + (O,): for<'r> $crate::from_row::FromRow< + 'r, + ::Row, + >, + A: $crate::arguments::IntoArguments, + { + $crate::query_scalar::query_statement_scalar_with(self, arguments) + } + }; +} diff --git a/vendor/sqlx-core/src/sync.rs b/vendor/sqlx-core/src/sync.rs new file mode 100755 index 0000000..ed082f7 --- /dev/null +++ b/vendor/sqlx-core/src/sync.rs @@ -0,0 +1,206 @@ +use cfg_if::cfg_if; + +// For types with identical signatures that don't require runtime support, +// we can just arbitrarily pick one to use based on what's enabled. +// +// We'll generally lean towards Tokio's types as those are more featureful +// (including `tokio-console` support) and more widely deployed. + +pub struct AsyncSemaphore { + // We use the semaphore from futures-intrusive as the one from async-lock + // is missing the ability to add arbitrary permits, and is not guaranteed to be fair: + // * https://github.com/smol-rs/async-lock/issues/22 + // * https://github.com/smol-rs/async-lock/issues/23 + // + // We're on the look-out for a replacement, however, as futures-intrusive is not maintained + // and there are some soundness concerns (although it turns out any intrusive future is unsound + // in MIRI due to the necessitated mutable aliasing): + // https://github.com/launchbadge/sqlx/issues/1668 + #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] + inner: futures_intrusive::sync::Semaphore, + + #[cfg(feature = "_rt-tokio")] + inner: tokio::sync::Semaphore, +} + +impl AsyncSemaphore { + #[track_caller] + pub fn new(fair: bool, permits: usize) -> Self { + if cfg!(not(any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol", + feature = "_rt-tokio" + ))) { + crate::rt::missing_rt((fair, permits)); + } + + AsyncSemaphore { + #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] + inner: futures_intrusive::sync::Semaphore::new(fair, permits), + #[cfg(feature = "_rt-tokio")] + inner: { + debug_assert!(fair, "Tokio only has fair permits"); + tokio::sync::Semaphore::new(permits) + }, + } + } + + pub fn permits(&self) -> usize { + cfg_if! { + if #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] { + self.inner.permits() + } else if #[cfg(feature = "_rt-tokio")] { + self.inner.available_permits() + } else { + crate::rt::missing_rt(()) + } + } + } + + pub async fn acquire(&self, permits: u32) -> AsyncSemaphoreReleaser<'_> { + cfg_if! { + if #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] { + AsyncSemaphoreReleaser { + inner: self.inner.acquire(permits as usize).await, + } + } else if #[cfg(feature = "_rt-tokio")] { + AsyncSemaphoreReleaser { + inner: self + .inner + // Weird quirk: `tokio::sync::Semaphore` mostly uses `usize` for permit counts, + // but `u32` for this and `try_acquire_many()`. + .acquire_many(permits) + .await + .expect("BUG: we do not expose the `.close()` method"), + } + } else { + crate::rt::missing_rt(permits) + } + } + } + + pub fn try_acquire(&self, permits: u32) -> Option> { + cfg_if! { + if #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] { + Some(AsyncSemaphoreReleaser { + inner: self.inner.try_acquire(permits as usize)?, + }) + } else if #[cfg(feature = "_rt-tokio")] { + Some(AsyncSemaphoreReleaser { + inner: self.inner.try_acquire_many(permits).ok()?, + }) + } else { + crate::rt::missing_rt(permits) + } + } + } + + pub fn release(&self, permits: usize) { + cfg_if! { + if #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] { + self.inner.release(permits); + } else if #[cfg(feature = "_rt-tokio")] { + self.inner.add_permits(permits); + } else { + crate::rt::missing_rt(permits); + } + } + } +} + +pub struct AsyncSemaphoreReleaser<'a> { + // We use the semaphore from futures-intrusive as the one from async-std + // is missing the ability to add arbitrary permits, and is not guaranteed to be fair: + // * https://github.com/smol-rs/async-lock/issues/22 + // * https://github.com/smol-rs/async-lock/issues/23 + // + // We're on the look-out for a replacement, however, as futures-intrusive is not maintained + // and there are some soundness concerns (although it turns out any intrusive future is unsound + // in MIRI due to the necessitated mutable aliasing): + // https://github.com/launchbadge/sqlx/issues/1668 + #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] + inner: futures_intrusive::sync::SemaphoreReleaser<'a>, + + #[cfg(feature = "_rt-tokio")] + inner: tokio::sync::SemaphorePermit<'a>, + + #[cfg(not(any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol", + feature = "_rt-tokio" + )))] + _phantom: std::marker::PhantomData<&'a ()>, +} + +impl AsyncSemaphoreReleaser<'_> { + pub fn disarm(self) { + cfg_if! { + if #[cfg(all( + any( + feature = "_rt-async-global-executor", + feature = "_rt-async-std", + feature = "_rt-smol" + ), + not(feature = "_rt-tokio") + ))] { + let mut this = self; + this.inner.disarm(); + } else if #[cfg(feature = "_rt-tokio")] { + self.inner.forget(); + } else { + crate::rt::missing_rt(()); + } + } + } +} diff --git a/vendor/sqlx-core/src/testing/fixtures.rs b/vendor/sqlx-core/src/testing/fixtures.rs new file mode 100755 index 0000000..17f67e0 --- /dev/null +++ b/vendor/sqlx-core/src/testing/fixtures.rs @@ -0,0 +1,282 @@ +//! TODO: automatic test fixture capture + +use crate::database::Database; + +use crate::query_builder::QueryBuilder; + +use indexmap::set::IndexSet; +use std::cmp; +use std::collections::{BTreeMap, HashMap}; +use std::marker::PhantomData; +use std::sync::Arc; + +pub type Result = std::result::Result; + +/// A snapshot of the current state of the database. +/// +/// Can be used to generate an `INSERT` fixture for populating an empty database, +/// or in the future it may be possible to generate a fixture from the difference between +/// two snapshots. +pub struct FixtureSnapshot { + tables: BTreeMap, + db: PhantomData, +} + +#[derive(Debug, thiserror::Error)] +#[error("could not create fixture: {0}")] +pub struct FixtureError(String); + +pub struct Fixture { + ops: Vec, + db: PhantomData, +} + +enum FixtureOp { + Insert { + table: TableName, + columns: Vec, + rows: Vec>, + }, + // TODO: handle updates and deletes by diffing two snapshots +} + +type TableName = Arc; +type ColumnName = Arc; +type Value = String; + +struct Table { + name: TableName, + columns: IndexSet, + rows: Vec>, + foreign_keys: HashMap, +} + +macro_rules! fixture_assert ( + ($cond:expr, $msg:literal $($arg:tt)*) => { + if !($cond) { + return Err(FixtureError(format!($msg $($arg)*))) + } + } +); + +impl FixtureSnapshot { + /// Generate a fixture to reproduce this snapshot from an empty database using `INSERT`s. + /// + /// Note that this doesn't take into account any triggers that might modify the data before + /// it's stored. + /// + /// The `INSERT` statements are ordered on a best-effort basis to satisfy any foreign key + /// constraints (data from tables with no foreign keys are inserted first, then the tables + /// that reference those tables, and so on). + /// + /// If a cycle in foreign-key constraints is detected, this returns with an error. + pub fn additive_fixture(&self) -> Result> { + let visit_order = self.calculate_visit_order()?; + + let mut ops = Vec::new(); + + for table_name in visit_order { + let table = self.tables.get(&table_name).unwrap(); + + ops.push(FixtureOp::Insert { + table: table_name, + columns: table.columns.iter().cloned().collect(), + rows: table.rows.clone(), + }); + } + + Ok(Fixture { ops, db: self.db }) + } + + /// Determine an order for outputting `INSERTS` for each table by calculating the max + /// length of all its foreign key chains. + /// + /// This should hopefully ensure that there are no foreign-key errors. + fn calculate_visit_order(&self) -> Result> { + let mut table_depths = HashMap::with_capacity(self.tables.len()); + let mut visited_set = IndexSet::with_capacity(self.tables.len()); + + for table in self.tables.values() { + foreign_key_depth(&self.tables, table, &mut table_depths, &mut visited_set)?; + visited_set.clear(); + } + + let mut table_names: Vec = table_depths.keys().cloned().collect(); + table_names.sort_by_key(|name| table_depths.get(name).unwrap()); + Ok(table_names) + } +} + +/// Implements `ToString` but not `Display` because it uses [`QueryBuilder`] internally, +/// which appends to an internal string. +#[allow(clippy::to_string_trait_impl)] +impl ToString for Fixture +where + for<'a> ::Arguments: Default, +{ + fn to_string(&self) -> String { + let mut query = QueryBuilder::::new(""); + + for op in &self.ops { + match op { + FixtureOp::Insert { + table, + columns, + rows, + } => { + // Sanity check, empty tables shouldn't appear in snapshots anyway. + if columns.is_empty() || rows.is_empty() { + continue; + } + + query.push(format_args!("INSERT INTO {table} (")); + + let mut separated = query.separated(", "); + + for column in columns { + separated.push(column); + } + + query.push(")\n"); + + query.push_values(rows, |mut separated, row| { + for value in row { + separated.push(value); + } + }); + + query.push(";\n"); + } + } + } + + query.into_string() + } +} + +fn foreign_key_depth( + tables: &BTreeMap, + table: &Table, + depths: &mut HashMap, + visited_set: &mut IndexSet, +) -> Result { + if let Some(&depth) = depths.get(&table.name) { + return Ok(depth); + } + + // This keeps us from looping forever. + fixture_assert!( + visited_set.insert(table.name.clone()), + "foreign key cycle detected: {:?} -> {:?}", + visited_set, + table.name + ); + + let mut refdepth = 0; + + for (colname, (refname, refcol)) in &table.foreign_keys { + let referenced = tables.get(refname).ok_or_else(|| { + FixtureError(format!( + "table {:?} in foreign key `{}.{} references {}.{}` does not exist", + refname, table.name, colname, refname, refcol + )) + })?; + + refdepth = cmp::max( + refdepth, + foreign_key_depth(tables, referenced, depths, visited_set)?, + ); + } + + let depth = refdepth + 1; + + depths.insert(table.name.clone(), depth); + + Ok(depth) +} + +#[test] +#[cfg(feature = "any")] +fn test_additive_fixture() -> Result<()> { + // Just need something that implements `Database` + use crate::any::Any; + + let mut snapshot = FixtureSnapshot { + tables: BTreeMap::new(), + db: PhantomData::, + }; + + snapshot.tables.insert( + "foo".into(), + Table { + name: "foo".into(), + columns: ["foo_id", "foo_a", "foo_b"] + .into_iter() + .map(Arc::::from) + .collect(), + rows: vec![vec!["1".into(), "'asdf'".into(), "true".into()]], + foreign_keys: HashMap::new(), + }, + ); + + // foreign-keyed to `foo` + // since `tables` is a `BTreeMap` we would expect a naive algorithm to visit this first. + snapshot.tables.insert( + "bar".into(), + Table { + name: "bar".into(), + columns: ["bar_id", "foo_id", "bar_a", "bar_b"] + .into_iter() + .map(Arc::::from) + .collect(), + rows: vec![vec![ + "1234".into(), + "1".into(), + "'2022-07-22 23:27:48.775113301+00:00'".into(), + "3.14".into(), + ]], + foreign_keys: [("foo_id".into(), ("foo".into(), "foo_id".into()))] + .into_iter() + .collect(), + }, + ); + + // foreign-keyed to both `foo` and `bar` + snapshot.tables.insert( + "baz".into(), + Table { + name: "baz".into(), + columns: ["baz_id", "bar_id", "foo_id", "baz_a", "baz_b"] + .into_iter() + .map(Arc::::from) + .collect(), + rows: vec![vec![ + "5678".into(), + "1234".into(), + "1".into(), + "'2022-07-22 23:27:48.775113301+00:00'".into(), + "3.14".into(), + ]], + foreign_keys: [ + ("foo_id".into(), ("foo".into(), "foo_id".into())), + ("bar_id".into(), ("bar".into(), "bar_id".into())), + ] + .into_iter() + .collect(), + }, + ); + + let fixture = snapshot.additive_fixture()?; + + assert_eq!( + fixture.to_string(), + "INSERT INTO foo (foo_id, foo_a, foo_b)\n\ + VALUES (1, 'asdf', true);\n\ + INSERT INTO bar (bar_id, foo_id, bar_a, bar_b)\n\ + VALUES (1234, 1, '2022-07-22 23:27:48.775113301+00:00', 3.14);\n\ + INSERT INTO baz (baz_id, bar_id, foo_id, baz_a, baz_b)\n\ + VALUES (5678, 1234, 1, '2022-07-22 23:27:48.775113301+00:00', 3.14);\n" + ); + + Ok(()) +} diff --git a/vendor/sqlx-core/src/testing/mod.rs b/vendor/sqlx-core/src/testing/mod.rs new file mode 100755 index 0000000..379fac6 --- /dev/null +++ b/vendor/sqlx-core/src/testing/mod.rs @@ -0,0 +1,275 @@ +use std::future::Future; +use std::time::Duration; + +use base64::{engine::general_purpose::URL_SAFE, Engine as _}; +pub use fixtures::FixtureSnapshot; +use sha2::{Digest, Sha512}; + +use crate::connection::{ConnectOptions, Connection}; +use crate::database::Database; +use crate::error::Error; +use crate::executor::Executor; +use crate::migrate::{Migrate, Migrator}; +use crate::pool::{Pool, PoolConnection, PoolOptions}; + +mod fixtures; + +pub trait TestSupport: Database { + /// Get parameters to construct a `Pool` suitable for testing. + /// + /// This `Pool` instance will behave somewhat specially: + /// * all handles share a single global semaphore to avoid exceeding the connection limit + /// on the database server. + /// * each invocation results in a different temporary database. + /// + /// The implementation may require `DATABASE_URL` to be set in order to manage databases. + /// The user credentials it contains must have the privilege to create and drop databases. + fn test_context( + args: &TestArgs, + ) -> impl Future, Error>> + Send + '_; + + fn cleanup_test(db_name: &str) -> impl Future> + Send + '_; + + /// Cleanup any test databases that are no longer in-use. + /// + /// Returns a count of the databases deleted, if possible. + /// + /// The implementation may require `DATABASE_URL` to be set in order to manage databases. + /// The user credentials it contains must have the privilege to create and drop databases. + fn cleanup_test_dbs() -> impl Future, Error>> + Send + 'static; + + /// Take a snapshot of the current state of the database (data only). + /// + /// This snapshot can then be used to generate test fixtures. + fn snapshot( + conn: &mut Self::Connection, + ) -> impl Future, Error>> + Send + '_; + + /// Generate a unique database name for the given test path. + fn db_name(args: &TestArgs) -> String { + let mut hasher = Sha512::new(); + hasher.update(args.test_path.as_bytes()); + let hash = hasher.finalize(); + let hash = URL_SAFE.encode(&hash[..39]); + let db_name = format!("_sqlx_test_{}", hash).replace('-', "_"); + debug_assert!(db_name.len() == 63); + db_name + } +} + +pub struct TestFixture { + pub path: &'static str, + pub contents: &'static str, +} + +pub struct TestArgs { + pub test_path: &'static str, + pub migrator: Option<&'static Migrator>, + pub fixtures: &'static [TestFixture], +} + +pub trait TestFn { + type Output; + + fn run_test(self, args: TestArgs) -> Self::Output; +} + +pub trait TestTermination { + fn is_success(&self) -> bool; +} + +pub struct TestContext { + pub pool_opts: PoolOptions, + pub connect_opts: ::Options, + pub db_name: String, +} + +impl TestFn for fn(Pool) -> Fut +where + DB: TestSupport + Database, + DB::Connection: Migrate, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + Fut: Future, + Fut::Output: TestTermination, +{ + type Output = Fut::Output; + + fn run_test(self, args: TestArgs) -> Self::Output { + run_test_with_pool(args, self) + } +} + +impl TestFn for fn(PoolConnection) -> Fut +where + DB: TestSupport + Database, + DB::Connection: Migrate, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + Fut: Future, + Fut::Output: TestTermination, +{ + type Output = Fut::Output; + + fn run_test(self, args: TestArgs) -> Self::Output { + run_test_with_pool(args, |pool| async move { + let conn = pool + .acquire() + .await + .expect("failed to acquire test pool connection"); + let res = (self)(conn).await; + pool.close().await; + res + }) + } +} + +impl TestFn for fn(PoolOptions, ::Options) -> Fut +where + DB: Database + TestSupport, + DB::Connection: Migrate, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + Fut: Future, + Fut::Output: TestTermination, +{ + type Output = Fut::Output; + + fn run_test(self, args: TestArgs) -> Self::Output { + run_test(args, self) + } +} + +impl TestFn for fn() -> Fut +where + Fut: Future, +{ + type Output = Fut::Output; + + fn run_test(self, args: TestArgs) -> Self::Output { + assert!( + args.fixtures.is_empty(), + "fixtures cannot be applied for a bare function" + ); + crate::rt::test_block_on(self()) + } +} + +impl TestArgs { + pub fn new(test_path: &'static str) -> Self { + TestArgs { + test_path, + migrator: None, + fixtures: &[], + } + } + + pub fn migrator(&mut self, migrator: &'static Migrator) { + self.migrator = Some(migrator); + } + + pub fn fixtures(&mut self, fixtures: &'static [TestFixture]) { + self.fixtures = fixtures; + } +} + +impl TestTermination for () { + fn is_success(&self) -> bool { + true + } +} + +impl TestTermination for Result { + fn is_success(&self) -> bool { + self.is_ok() + } +} + +fn run_test_with_pool(args: TestArgs, test_fn: F) -> Fut::Output +where + DB: TestSupport, + DB::Connection: Migrate, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + F: FnOnce(Pool) -> Fut, + Fut: Future, + Fut::Output: TestTermination, +{ + let test_path = args.test_path; + run_test::(args, |pool_opts, connect_opts| async move { + let pool = pool_opts + .connect_with(connect_opts) + .await + .expect("failed to connect test pool"); + + let res = test_fn(pool.clone()).await; + + let close_timed_out = crate::rt::timeout(Duration::from_secs(10), pool.close()) + .await + .is_err(); + + if close_timed_out { + eprintln!("test {test_path} held onto Pool after exiting"); + } + + res + }) +} + +fn run_test(args: TestArgs, test_fn: F) -> Fut::Output +where + DB: TestSupport, + DB::Connection: Migrate, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + F: FnOnce(PoolOptions, ::Options) -> Fut, + Fut: Future, + Fut::Output: TestTermination, +{ + crate::rt::test_block_on(async move { + let test_context = DB::test_context(&args) + .await + .expect("failed to connect to setup test database"); + + setup_test_db::(&test_context.connect_opts, &args).await; + + let res = test_fn(test_context.pool_opts, test_context.connect_opts).await; + + if res.is_success() { + if let Err(e) = DB::cleanup_test(&DB::db_name(&args)).await { + eprintln!( + "failed to delete database {:?}: {}", + test_context.db_name, e + ); + } + } + + res + }) +} + +async fn setup_test_db( + copts: &::Options, + args: &TestArgs, +) where + DB::Connection: Migrate + Sized, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, +{ + let mut conn = copts + .connect() + .await + .expect("failed to connect to test database"); + + if let Some(migrator) = args.migrator { + migrator + .run_direct(None, &mut conn, false) + .await + .expect("failed to apply migrations"); + } + + for fixture in args.fixtures { + (&mut conn) + .execute(fixture.contents) + .await + .unwrap_or_else(|e| panic!("failed to apply test fixture {:?}: {:?}", fixture.path, e)); + } + + conn.close() + .await + .expect("failed to close setup connection"); +} diff --git a/vendor/sqlx-core/src/transaction.rs b/vendor/sqlx-core/src/transaction.rs new file mode 100755 index 0000000..46f89d2 --- /dev/null +++ b/vendor/sqlx-core/src/transaction.rs @@ -0,0 +1,308 @@ +use std::fmt::{self, Debug, Formatter}; +use std::future::{self, Future}; +use std::ops::{Deref, DerefMut}; + +use futures_core::future::BoxFuture; + +use crate::database::Database; +use crate::error::Error; +use crate::pool::MaybePoolConnection; +use crate::sql_str::{AssertSqlSafe, SqlSafeStr, SqlStr}; + +/// Generic management of database transactions. +/// +/// This trait should not be used, except when implementing [`Connection`]. +pub trait TransactionManager { + type Database: Database; + + /// Begin a new transaction or establish a savepoint within the active transaction. + /// + /// If this is a new transaction, `statement` may be used instead of the + /// default "BEGIN" statement. + /// + /// If we are already inside a transaction and `statement.is_some()`, then + /// `Error::InvalidSavePoint` is returned without running any statements. + fn begin( + conn: &mut ::Connection, + statement: Option, + ) -> impl Future> + Send + '_; + + /// Commit the active transaction or release the most recent savepoint. + fn commit( + conn: &mut ::Connection, + ) -> impl Future> + Send + '_; + + /// Abort the active transaction or restore from the most recent savepoint. + fn rollback( + conn: &mut ::Connection, + ) -> impl Future> + Send + '_; + + /// Starts to abort the active transaction or restore from the most recent snapshot. + fn start_rollback(conn: &mut ::Connection); + + /// Returns the current transaction depth. + /// + /// Transaction depth indicates the level of nested transactions: + /// - Level 0: No active transaction. + /// - Level 1: A transaction is active. + /// - Level 2 or higher: A transaction is active and one or more SAVEPOINTs have been created within it. + fn get_transaction_depth(conn: &::Connection) -> usize; +} + +/// An in-progress database transaction or savepoint. +/// +/// A transaction starts with a call to [`Pool::begin`] or [`Connection::begin`]. +/// +/// A transaction should end with a call to [`commit`] or [`rollback`]. If neither are called +/// before the transaction goes out-of-scope, [`rollback`] is called. In other +/// words, [`rollback`] is called on `drop` if the transaction is still in-progress. +/// +/// A savepoint is a special mark inside a transaction that allows all commands that are +/// executed after it was established to be rolled back, restoring the transaction state to +/// what it was at the time of the savepoint. +/// +/// A transaction can be used as an [`Executor`] when performing queries: +/// ```rust,no_run +/// # use sqlx_core::acquire::Acquire; +/// # async fn example() -> sqlx::Result<()> { +/// # let id = 1; +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// let mut tx = conn.begin().await?; +/// +/// let result = sqlx::query("DELETE FROM \"testcases\" WHERE id = $1") +/// .bind(id) +/// .execute(&mut *tx) +/// .await? +/// .rows_affected(); +/// +/// tx.commit().await +/// # } +/// ``` +/// [`Executor`]: crate::executor::Executor +/// [`Connection::begin`]: crate::connection::Connection::begin() +/// [`Pool::begin`]: crate::pool::Pool::begin() +/// [`commit`]: Self::commit() +/// [`rollback`]: Self::rollback() +pub struct Transaction<'c, DB> +where + DB: Database, +{ + connection: MaybePoolConnection<'c, DB>, + open: bool, +} + +impl<'c, DB> Transaction<'c, DB> +where + DB: Database, +{ + #[doc(hidden)] + pub fn begin( + conn: impl Into>, + statement: Option, + ) -> BoxFuture<'c, Result> { + let conn = conn.into(); + + Box::pin(async move { + let mut tx = Self { + connection: conn, + + // If the call to `begin` fails or doesn't complete we want to attempt a rollback in case the transaction was started. + open: true, + }; + + DB::TransactionManager::begin(&mut tx.connection, statement).await?; + + Ok(tx) + }) + } + + /// Commits this transaction or savepoint. + pub async fn commit(mut self) -> Result<(), Error> { + DB::TransactionManager::commit(&mut self.connection).await?; + self.open = false; + + Ok(()) + } + + /// Aborts this transaction or savepoint. + pub async fn rollback(mut self) -> Result<(), Error> { + DB::TransactionManager::rollback(&mut self.connection).await?; + self.open = false; + + Ok(()) + } +} + +// NOTE: fails to compile due to lack of lazy normalization +// impl<'c, 't, DB: Database> crate::executor::Executor<'t> +// for &'t mut crate::transaction::Transaction<'c, DB> +// where +// &'c mut DB::Connection: Executor<'c, Database = DB>, +// { +// type Database = DB; +// +// +// +// fn fetch_many<'e, 'q: 'e, E: 'q>( +// self, +// query: E, +// ) -> futures_core::stream::BoxStream< +// 'e, +// Result< +// crate::Either<::QueryResult, DB::Row>, +// crate::error::Error, +// >, +// > +// where +// 't: 'e, +// E: crate::executor::Execute<'q, Self::Database>, +// { +// (&mut **self).fetch_many(query) +// } +// +// fn fetch_optional<'e, 'q: 'e, E: 'q>( +// self, +// query: E, +// ) -> futures_core::future::BoxFuture<'e, Result, crate::error::Error>> +// where +// 't: 'e, +// E: crate::executor::Execute<'q, Self::Database>, +// { +// (&mut **self).fetch_optional(query) +// } +// +// fn prepare_with<'e, 'q: 'e>( +// self, +// sql: &'q str, +// parameters: &'e [::TypeInfo], +// ) -> futures_core::future::BoxFuture< +// 'e, +// Result< +// ::Statement<'q>, +// crate::error::Error, +// >, +// > +// where +// 't: 'e, +// { +// (&mut **self).prepare_with(sql, parameters) +// } +// +// #[doc(hidden)] +// #[cfg(feature = "offline")] +// fn describe<'e, 'q: 'e>( +// self, +// query: &'q str, +// ) -> futures_core::future::BoxFuture< +// 'e, +// Result, crate::error::Error>, +// > +// where +// 't: 'e, +// { +// (&mut **self).describe(query) +// } +// } + +impl Debug for Transaction<'_, DB> +where + DB: Database, +{ + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + // TODO: Show the full type <..<..<.. + f.debug_struct("Transaction").finish() + } +} + +impl Deref for Transaction<'_, DB> +where + DB: Database, +{ + type Target = DB::Connection; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.connection + } +} + +impl DerefMut for Transaction<'_, DB> +where + DB: Database, +{ + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.connection + } +} + +// Implement `AsMut` so `Transaction` can be given to a +// `PgAdvisoryLockGuard`. +// +// See: https://github.com/launchbadge/sqlx/issues/2520 +impl AsMut for Transaction<'_, DB> { + fn as_mut(&mut self) -> &mut DB::Connection { + &mut self.connection + } +} + +impl<'t, DB: Database> crate::acquire::Acquire<'t> for &'t mut Transaction<'_, DB> { + type Database = DB; + + type Connection = &'t mut ::Connection; + + #[inline] + fn acquire(self) -> BoxFuture<'t, Result> { + Box::pin(future::ready(Ok(&mut **self))) + } + + #[inline] + fn begin(self) -> BoxFuture<'t, Result, Error>> { + Transaction::begin(&mut **self, None) + } +} + +impl Drop for Transaction<'_, DB> +where + DB: Database, +{ + fn drop(&mut self) { + if self.open { + // starts a rollback operation + + // what this does depends on the database but generally this means we queue a rollback + // operation that will happen on the next asynchronous invocation of the underlying + // connection (including if the connection is returned to a pool) + + DB::TransactionManager::start_rollback(&mut self.connection); + } + } +} + +pub fn begin_ansi_transaction_sql(depth: usize) -> SqlStr { + if depth == 0 { + "BEGIN".into_sql_str() + } else { + AssertSqlSafe(format!("SAVEPOINT _sqlx_savepoint_{depth}")).into_sql_str() + } +} + +pub fn commit_ansi_transaction_sql(depth: usize) -> SqlStr { + if depth == 1 { + "COMMIT".into_sql_str() + } else { + AssertSqlSafe(format!("RELEASE SAVEPOINT _sqlx_savepoint_{}", depth - 1)).into_sql_str() + } +} + +pub fn rollback_ansi_transaction_sql(depth: usize) -> SqlStr { + if depth == 1 { + "ROLLBACK".into_sql_str() + } else { + AssertSqlSafe(format!( + "ROLLBACK TO SAVEPOINT _sqlx_savepoint_{}", + depth - 1 + )) + .into_sql_str() + } +} diff --git a/vendor/sqlx-core/src/type_checking.rs b/vendor/sqlx-core/src/type_checking.rs new file mode 100755 index 0000000..a3ded72 --- /dev/null +++ b/vendor/sqlx-core/src/type_checking.rs @@ -0,0 +1,522 @@ +use crate::config::macros::PreferredCrates; +use crate::database::Database; +use crate::decode::Decode; +use crate::type_info::TypeInfo; +use crate::value::Value; +use std::any::Any; +use std::fmt; +use std::fmt::{Debug, Formatter}; + +/// The type of query parameter checking done by a SQL database. +#[derive(PartialEq, Eq)] +pub enum ParamChecking { + /// Parameter checking is weak or nonexistent (uses coercion or allows mismatches). + Weak, + /// Parameter checking is strong (types must match exactly). + Strong, +} + +/// Type-checking extensions for the `Database` trait. +/// +/// Mostly supporting code for the macros, and for `Debug` impls. +pub trait TypeChecking: Database { + /// Describes how the database in question typechecks query parameters. + const PARAM_CHECKING: ParamChecking; + + /// Get the full path of the Rust type that corresponds to the given `TypeInfo`, if applicable. + /// + /// If the type has a borrowed equivalent suitable for query parameters, + /// this is that borrowed type. + fn param_type_for_id( + id: &Self::TypeInfo, + preferred_crates: &PreferredCrates, + ) -> Result<&'static str, Error>; + + /// Get the full path of the Rust type that corresponds to the given `TypeInfo`, if applicable. + /// + /// Always returns the owned version of the type, suitable for decoding from `Row`. + fn return_type_for_id( + id: &Self::TypeInfo, + preferred_crates: &PreferredCrates, + ) -> Result<&'static str, Error>; + + /// Get the name of the Cargo feature gate that must be enabled to process the given `TypeInfo`, + /// if applicable. + fn get_feature_gate(info: &Self::TypeInfo) -> Option<&'static str>; + + /// If `value` is a well-known type, decode and format it using `Debug`. + /// + /// If `value` is not a well-known type or could not be decoded, the reason is printed instead. + fn fmt_value_debug(value: &::Value) -> FmtValue<'_, Self>; +} + +pub type Result = std::result::Result; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("no built-in mapping found for SQL type; a type override may be required")] + NoMappingFound, + #[error("Cargo feature for configured `macros.preferred-crates.date-time` not enabled")] + DateTimeCrateFeatureNotEnabled, + #[error("Cargo feature for configured `macros.preferred-crates.numeric` not enabled")] + NumericCrateFeatureNotEnabled, + #[error("multiple date-time types are possible; falling back to `{fallback}`")] + AmbiguousDateTimeType { fallback: &'static str }, + #[error("multiple numeric types are possible; falling back to `{fallback}`")] + AmbiguousNumericType { fallback: &'static str }, +} + +/// An adapter for [`Value`] which attempts to decode the value and format it when printed using [`Debug`]. +pub struct FmtValue<'v, DB> +where + DB: Database, +{ + value: &'v ::Value, + fmt: fn(&'v ::Value, &mut Formatter<'_>) -> fmt::Result, +} + +impl<'v, DB> FmtValue<'v, DB> +where + DB: Database, +{ + // This API can't take `ValueRef` directly as it would need to pass it to `Decode` by-value, + // which means taking ownership of it. We cannot rely on a `Clone` impl because `SqliteValueRef` doesn't have one. + /// When printed with [`Debug`], attempt to decode `value` as the given type `T` and format it using [`Debug`]. + /// + /// If `value` could not be decoded as `T`, the reason is printed instead. + pub fn debug(value: &'v ::Value) -> Self + where + T: Decode<'v, DB> + Debug + Any, + { + Self { + value, + fmt: |value, f| { + let info = value.type_info(); + + match T::decode(value.as_ref()) { + Ok(value) => Debug::fmt(&value, f), + Err(e) => { + if e.is::() { + f.write_str("NULL") + } else { + f.write_fmt(format_args!( + "(error decoding SQL type {} as {}: {e:?})", + info.name(), + std::any::type_name::() + )) + } + } + } + }, + } + } + + /// If the type to be decoded is not known or not supported, print the SQL type instead, + /// as well as any applicable SQLx feature that needs to be enabled. + pub fn unknown(value: &'v ::Value) -> Self + where + DB: TypeChecking, + { + Self { + value, + fmt: |value, f| { + let info = value.type_info(); + + if let Some(feature_gate) = ::get_feature_gate(&info) { + return f.write_fmt(format_args!( + "(unknown SQL type {}: SQLx feature {feature_gate} not enabled)", + info.name() + )); + } + + f.write_fmt(format_args!("(unknown SQL type {})", info.name())) + }, + } + } +} + +impl Debug for FmtValue<'_, DB> +where + DB: Database, +{ + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + (self.fmt)(self.value, f) + } +} + +#[doc(hidden)] +#[macro_export] +macro_rules! select_input_type { + ($ty:ty, $input:ty) => { + stringify!($input) + }; + ($ty:ty) => { + stringify!($ty) + }; +} + +#[macro_export] +macro_rules! impl_type_checking { + ( + $database:path { + $($(#[$meta:meta])? $ty:ty $(| $input:ty)?),*$(,)? + }, + ParamChecking::$param_checking:ident, + feature-types: $ty_info:ident => $get_gate:expr, + datetime-types: { + chrono: { + $($chrono_ty:ty $(| $chrono_input:ty)?),*$(,)? + }, + time: { + $($time_ty:ty $(| $time_input:ty)?),*$(,)? + }, + }, + numeric-types: { + bigdecimal: { + $($bigdecimal_ty:ty $(| $bigdecimal_input:ty)?),*$(,)? + }, + rust_decimal: { + $($rust_decimal_ty:ty $(| $rust_decimal_input:ty)?),*$(,)? + }, + }, + ) => { + impl $crate::type_checking::TypeChecking for $database { + const PARAM_CHECKING: $crate::type_checking::ParamChecking = $crate::type_checking::ParamChecking::$param_checking; + + fn param_type_for_id( + info: &Self::TypeInfo, + preferred_crates: &$crate::config::macros::PreferredCrates, + ) -> Result<&'static str, $crate::type_checking::Error> { + use $crate::config::macros::{DateTimeCrate, NumericCrate}; + use $crate::type_checking::Error; + + // Check non-special types + // --------------------- + $( + $(#[$meta])? + if <$ty as sqlx_core::types::Type<$database>>::type_info() == *info { + return Ok($crate::select_input_type!($ty $(, $input)?)); + } + )* + + $( + $(#[$meta])? + if <$ty as sqlx_core::types::Type<$database>>::compatible(info) { + return Ok($crate::select_input_type!($ty $(, $input)?)); + } + )* + + // Check `macros.preferred-crates.date-time` + // + // Due to legacy reasons, `time` takes precedent over `chrono` if both are enabled. + // Any crates added later should be _lower_ priority than `chrono` to avoid breakages. + // ---------------------------------------- + #[cfg(feature = "time")] + if matches!(preferred_crates.date_time, DateTimeCrate::Time | DateTimeCrate::Inferred) { + $( + if <$time_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + if cfg!(feature = "chrono") { + return Err($crate::type_checking::Error::AmbiguousDateTimeType { + fallback: $crate::select_input_type!($time_ty $(, $time_input)?), + }); + } + + return Ok($crate::select_input_type!($time_ty $(, $time_input)?)); + } + )* + + $( + if <$time_ty as sqlx_core::types::Type<$database>>::compatible(info) { + if cfg!(feature = "chrono") { + return Err($crate::type_checking::Error::AmbiguousDateTimeType { + fallback: $crate::select_input_type!($time_ty $(, $time_input)?), + }); + } + + return Ok($crate::select_input_type!($time_ty $(, $time_input)?)); + } + )* + } + + #[cfg(not(feature = "time"))] + if preferred_crates.date_time == DateTimeCrate::Time { + return Err(Error::DateTimeCrateFeatureNotEnabled); + } + + #[cfg(feature = "chrono")] + if matches!(preferred_crates.date_time, DateTimeCrate::Chrono | DateTimeCrate::Inferred) { + $( + if <$chrono_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + return Ok($crate::select_input_type!($chrono_ty $(, $chrono_input)?)); + } + )* + + $( + if <$chrono_ty as sqlx_core::types::Type<$database>>::compatible(info) { + return Ok($crate::select_input_type!($chrono_ty $(, $chrono_input)?)); + } + )* + } + + #[cfg(not(feature = "chrono"))] + if preferred_crates.date_time == DateTimeCrate::Chrono { + return Err(Error::DateTimeCrateFeatureNotEnabled); + } + + // Check `macros.preferred-crates.numeric` + // + // Due to legacy reasons, `bigdecimal` takes precedent over `rust_decimal` if + // both are enabled. + // ---------------------------------------- + #[cfg(feature = "bigdecimal")] + if matches!(preferred_crates.numeric, NumericCrate::BigDecimal | NumericCrate::Inferred) { + $( + if <$bigdecimal_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + if cfg!(feature = "rust_decimal") { + return Err($crate::type_checking::Error::AmbiguousNumericType { + fallback: $crate::select_input_type!($bigdecimal_ty $(, $bigdecimal_input)?), + }); + } + + return Ok($crate::select_input_type!($bigdecimal_ty $(, $bigdecimal_input)?)); + } + )* + + $( + if <$bigdecimal_ty as sqlx_core::types::Type<$database>>::compatible(info) { + if cfg!(feature = "rust_decimal") { + return Err($crate::type_checking::Error::AmbiguousNumericType { + fallback: $crate::select_input_type!($bigdecimal_ty $(, $bigdecimal_input)?), + }); + } + + return Ok($crate::select_input_type!($bigdecimal_ty $(, $bigdecimal_input)?)); + } + )* + } + + #[cfg(not(feature = "bigdecimal"))] + if preferred_crates.numeric == NumericCrate::BigDecimal { + return Err(Error::NumericCrateFeatureNotEnabled); + } + + #[cfg(feature = "rust_decimal")] + if matches!(preferred_crates.numeric, NumericCrate::RustDecimal | NumericCrate::Inferred) { + $( + if <$rust_decimal_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + return Ok($crate::select_input_type!($rust_decimal_ty $(, $rust_decimal_input)?)); + } + )* + + $( + if <$rust_decimal_ty as sqlx_core::types::Type<$database>>::compatible(info) { + return Ok($crate::select_input_type!($rust_decimal_ty $(, $rust_decimal_input)?)); + } + )* + } + + #[cfg(not(feature = "rust_decimal"))] + if preferred_crates.numeric == NumericCrate::RustDecimal { + return Err(Error::NumericCrateFeatureNotEnabled); + } + + Err(Error::NoMappingFound) + } + + fn return_type_for_id( + info: &Self::TypeInfo, + preferred_crates: &$crate::config::macros::PreferredCrates, + ) -> Result<&'static str, $crate::type_checking::Error> { + use $crate::config::macros::{DateTimeCrate, NumericCrate}; + use $crate::type_checking::Error; + + // Check non-special types + // --------------------- + $( + $(#[$meta])? + if <$ty as sqlx_core::types::Type<$database>>::type_info() == *info { + return Ok(stringify!($ty)); + } + )* + + $( + $(#[$meta])? + if <$ty as sqlx_core::types::Type<$database>>::compatible(info) { + return Ok(stringify!($ty)); + } + )* + + // Check `macros.preferred-crates.date-time` + // + // Due to legacy reasons, `time` takes precedent over `chrono` if both are enabled. + // Any crates added later should be _lower_ priority than `chrono` to avoid breakages. + // ---------------------------------------- + #[cfg(feature = "time")] + if matches!(preferred_crates.date_time, DateTimeCrate::Time | DateTimeCrate::Inferred) { + $( + if <$time_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + if cfg!(feature = "chrono") { + return Err($crate::type_checking::Error::AmbiguousDateTimeType { + fallback: stringify!($time_ty), + }); + } + + return Ok(stringify!($time_ty)); + } + )* + + $( + if <$time_ty as sqlx_core::types::Type<$database>>::compatible(info) { + if cfg!(feature = "chrono") { + return Err($crate::type_checking::Error::AmbiguousDateTimeType { + fallback: stringify!($time_ty), + }); + } + + return Ok(stringify!($time_ty)); + } + )* + } + + #[cfg(not(feature = "time"))] + if preferred_crates.date_time == DateTimeCrate::Time { + return Err(Error::DateTimeCrateFeatureNotEnabled); + } + + #[cfg(feature = "chrono")] + if matches!(preferred_crates.date_time, DateTimeCrate::Chrono | DateTimeCrate::Inferred) { + $( + if <$chrono_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + return Ok(stringify!($chrono_ty)); + } + )* + + $( + if <$chrono_ty as sqlx_core::types::Type<$database>>::compatible(info) { + return Ok(stringify!($chrono_ty)); + } + )* + } + + #[cfg(not(feature = "chrono"))] + if preferred_crates.date_time == DateTimeCrate::Chrono { + return Err(Error::DateTimeCrateFeatureNotEnabled); + } + + // Check `macros.preferred-crates.numeric` + // + // Due to legacy reasons, `bigdecimal` takes precedent over `rust_decimal` if + // both are enabled. + // ---------------------------------------- + #[cfg(feature = "bigdecimal")] + if matches!(preferred_crates.numeric, NumericCrate::BigDecimal | NumericCrate::Inferred) { + $( + if <$bigdecimal_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + if cfg!(feature = "rust_decimal") { + return Err($crate::type_checking::Error::AmbiguousNumericType { + fallback: stringify!($bigdecimal_ty), + }); + } + + return Ok(stringify!($bigdecimal_ty)); + } + )* + + $( + if <$bigdecimal_ty as sqlx_core::types::Type<$database>>::compatible(info) { + if cfg!(feature = "rust_decimal") { + return Err($crate::type_checking::Error::AmbiguousNumericType { + fallback: stringify!($bigdecimal_ty), + }); + } + + return Ok(stringify!($bigdecimal_ty)); + } + )* + } + + #[cfg(not(feature = "bigdecimal"))] + if preferred_crates.numeric == NumericCrate::BigDecimal { + return Err(Error::NumericCrateFeatureNotEnabled); + } + + #[cfg(feature = "rust_decimal")] + if matches!(preferred_crates.numeric, NumericCrate::RustDecimal | NumericCrate::Inferred) { + $( + if <$rust_decimal_ty as sqlx_core::types::Type<$database>>::type_info() == *info { + return Ok($crate::select_input_type!($rust_decimal_ty $(, $rust_decimal_input)?)); + } + )* + + $( + if <$rust_decimal_ty as sqlx_core::types::Type<$database>>::compatible(info) { + return Ok($crate::select_input_type!($rust_decimal_ty $(, $rust_decimal_input)?)); + } + )* + } + + #[cfg(not(feature = "rust_decimal"))] + if preferred_crates.numeric == NumericCrate::RustDecimal { + return Err(Error::NumericCrateFeatureNotEnabled); + } + + Err(Error::NoMappingFound) + } + + fn get_feature_gate($ty_info: &Self::TypeInfo) -> Option<&'static str> { + $get_gate + } + + fn fmt_value_debug(value: &Self::Value) -> $crate::type_checking::FmtValue { + use $crate::value::Value; + + let info = value.type_info(); + + #[cfg(feature = "time")] + { + $( + if <$time_ty as sqlx_core::types::Type<$database>>::compatible(&info) { + return $crate::type_checking::FmtValue::debug::<$time_ty>(value); + } + )* + } + + #[cfg(feature = "chrono")] + { + $( + if <$chrono_ty as sqlx_core::types::Type<$database>>::compatible(&info) { + return $crate::type_checking::FmtValue::debug::<$chrono_ty>(value); + } + )* + } + + #[cfg(feature = "bigdecimal")] + { + $( + if <$bigdecimal_ty as sqlx_core::types::Type<$database>>::compatible(&info) { + return $crate::type_checking::FmtValue::debug::<$bigdecimal_ty>(value); + } + )* + } + + #[cfg(feature = "rust_decimal")] + { + $( + if <$rust_decimal_ty as sqlx_core::types::Type<$database>>::compatible(&info) { + return $crate::type_checking::FmtValue::debug::<$rust_decimal_ty>(value); + } + )* + } + + $( + $(#[$meta])? + if <$ty as sqlx_core::types::Type<$database>>::compatible(&info) { + return $crate::type_checking::FmtValue::debug::<$ty>(value); + } + )* + + $crate::type_checking::FmtValue::unknown(value) + } + } + }; +} diff --git a/vendor/sqlx-core/src/type_info.rs b/vendor/sqlx-core/src/type_info.rs new file mode 100755 index 0000000..812bcf3 --- /dev/null +++ b/vendor/sqlx-core/src/type_info.rs @@ -0,0 +1,26 @@ +use std::fmt::{Debug, Display}; + +/// Provides information about a SQL type for the database driver. +pub trait TypeInfo: Debug + Display + Clone + PartialEq + Send + Sync { + fn is_null(&self) -> bool; + + /// Returns the database system name of the type. Length specifiers should not be included. + /// Common type names are `VARCHAR`, `TEXT`, or `INT`. Type names should be uppercase. They + /// should be a rough approximation of how they are written in SQL in the given database. + fn name(&self) -> &str; + + /// Return `true` if `self` and `other` represent mutually compatible types. + /// + /// Defaults to `self == other`. + fn type_compatible(&self, other: &Self) -> bool + where + Self: Sized, + { + self == other + } + + #[doc(hidden)] + fn is_void(&self) -> bool { + false + } +} diff --git a/vendor/sqlx-core/src/types/bstr.rs b/vendor/sqlx-core/src/types/bstr.rs new file mode 100755 index 0000000..5afae9a --- /dev/null +++ b/vendor/sqlx-core/src/types/bstr.rs @@ -0,0 +1,59 @@ +/// Conversions between `bstr` types and SQL types. +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; + +#[doc(no_inline)] +pub use bstr::{BStr, BString, ByteSlice}; + +impl Type for BString +where + DB: Database, + [u8]: Type, +{ + fn type_info() -> DB::TypeInfo { + <&[u8] as Type>::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + <&[u8] as Type>::compatible(ty) + } +} + +impl<'r, DB> Decode<'r, DB> for BString +where + DB: Database, + Vec: Decode<'r, DB>, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + as Decode>::decode(value).map(BString::from) + } +} + +impl<'q, DB: Database> Encode<'q, DB> for &'q BStr +where + DB: Database, + &'q [u8]: Encode<'q, DB>, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + <&[u8] as Encode>::encode(self.as_bytes(), buf) + } +} + +impl<'q, DB: Database> Encode<'q, DB> for BString +where + DB: Database, + Vec: Encode<'q, DB>, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + as Encode>::encode(self.as_bytes().to_vec(), buf) + } +} diff --git a/vendor/sqlx-core/src/types/json.rs b/vendor/sqlx-core/src/types/json.rs new file mode 100755 index 0000000..6616ce1 --- /dev/null +++ b/vendor/sqlx-core/src/types/json.rs @@ -0,0 +1,263 @@ +use std::ops::{Deref, DerefMut}; + +use serde::{Deserialize, Serialize}; +pub use serde_json::value::RawValue as JsonRawValue; +pub use serde_json::Value as JsonValue; + +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::error::BoxDynError; +use crate::types::Type; + +/// Json for json and jsonb fields +/// +/// Will attempt to cast to type passed in as the generic. +/// +/// ```toml +/// [dependencies] +/// serde_json = { version = "1.0", features = ["raw_value"] } +/// +/// ``` +/// +/// # Example +/// +/// ``` +/// # use serde::Deserialize; +/// #[derive(Deserialize)] +/// struct Book { +/// name: String +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct Author { +/// name: String, +/// books: sqlx::types::Json +/// } +/// ``` +/// +/// Can also be used to turn the json/jsonb into a hashmap +/// ``` +/// use std::collections::HashMap; +/// use serde::Deserialize; +/// +/// #[derive(Deserialize)] +/// struct Book { +/// name: String +/// } +/// #[derive(sqlx::FromRow)] +/// struct Library { +/// id: String, +/// dewey_decimal: sqlx::types::Json> +/// } +/// ``` +/// +/// If the query macros are used, it is necessary to tell the macro to use +/// the `Json` adapter by using the type override syntax +/// ```rust,ignore +/// # async fn example3() -> sqlx::Result<()> { +/// # let mut conn: sqlx::PgConnection = unimplemented!(); +/// #[derive(sqlx::FromRow)] +/// struct Book { +/// title: String, +/// } +/// +/// #[derive(sqlx::FromRow)] +/// struct Author { +/// name: String, +/// books: sqlx::types::Json, +/// } +/// // Note the type override in the query string +/// let authors = sqlx::query_as!( +/// Author, +/// r#" +/// SELECT name, books as "books: Json" +/// FROM authors +/// "# +/// ) +/// .fetch_all(&mut conn) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +#[derive( + Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize, +)] +#[serde(transparent)] +pub struct Json(pub T); + +impl Json { + /// Extract the inner value. + pub fn into_inner(self) -> T { + self.0 + } +} + +impl From for Json { + fn from(value: T) -> Self { + Self(value) + } +} + +impl Deref for Json { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Json { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl AsRef for Json { + fn as_ref(&self) -> &T { + &self.0 + } +} + +impl AsMut for Json { + fn as_mut(&mut self) -> &mut T { + &mut self.0 + } +} + +// UNSTABLE: for driver use only! +#[doc(hidden)] +impl Json { + pub fn encode_to_string(&self) -> Result { + serde_json::to_string(self) + } + + pub fn encode_to(&self, buf: &mut Vec) -> Result<(), serde_json::Error> { + serde_json::to_writer(buf, self) + } +} + +// UNSTABLE: for driver use only! +#[doc(hidden)] +impl<'a, T: 'a> Json +where + T: Deserialize<'a>, +{ + pub fn decode_from_string(s: &'a str) -> Result { + serde_json::from_str(s).map_err(Into::into) + } + + pub fn decode_from_bytes(bytes: &'a [u8]) -> Result { + serde_json::from_slice(bytes).map_err(Into::into) + } +} + +impl Type for JsonValue +where + Json: Type, + DB: Database, +{ + fn type_info() -> DB::TypeInfo { + as Type>::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + as Type>::compatible(ty) + } +} + +impl<'q, DB> Encode<'q, DB> for JsonValue +where + for<'a> Json<&'a Self>: Encode<'q, DB>, + DB: Database, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + as Encode<'q, DB>>::encode(Json(self), buf) + } +} + +impl<'r, DB> Decode<'r, DB> for JsonValue +where + Json: Decode<'r, DB>, + DB: Database, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + as Decode>::decode(value).map(|item| item.0) + } +} + +impl Type for JsonRawValue +where + for<'a> Json<&'a Self>: Type, + DB: Database, +{ + fn type_info() -> DB::TypeInfo { + as Type>::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + as Type>::compatible(ty) + } +} + +impl<'q, DB> Encode<'q, DB> for JsonRawValue +where + for<'a> Json<&'a Self>: Encode<'q, DB>, + DB: Database, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + as Encode<'q, DB>>::encode(Json(self), buf) + } +} + +impl<'q, DB> Encode<'q, DB> for &'q JsonRawValue +where + for<'a> Json<&'a Self>: Encode<'q, DB>, + DB: Database, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + as Encode<'q, DB>>::encode(Json(self), buf) + } +} + +impl<'q, DB> Encode<'q, DB> for Box +where + for<'a> Json<&'a Self>: Encode<'q, DB>, + DB: Database, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer, + ) -> Result { + as Encode<'q, DB>>::encode(Json(self), buf) + } +} + +impl<'r, DB> Decode<'r, DB> for &'r JsonRawValue +where + Json: Decode<'r, DB>, + DB: Database, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + as Decode>::decode(value).map(|item| item.0) + } +} + +impl<'r, DB> Decode<'r, DB> for Box +where + Json: Decode<'r, DB>, + DB: Database, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + as Decode>::decode(value).map(|item| item.0) + } +} diff --git a/vendor/sqlx-core/src/types/mod.rs b/vendor/sqlx-core/src/types/mod.rs new file mode 100755 index 0000000..f42d2e3 --- /dev/null +++ b/vendor/sqlx-core/src/types/mod.rs @@ -0,0 +1,290 @@ +//! Conversions between Rust and SQL types. +//! +//! To see how each SQL type maps to a Rust type, see the corresponding `types` module for each +//! database: +//! +//! * [PostgreSQL](crate::postgres::types) +//! * [MySQL](crate::mysql::types) +//! * [SQLite](crate::sqlite::types) +//! * [MSSQL](crate::mssql::types) +//! +//! Any external types that have had [`Type`] implemented for, are re-exported in this module +//! for convenience as downstream users need to use a compatible version of the external crate +//! to take advantage of the implementation. +//! +//! # Nullable +//! +//! To represent nullable SQL types, `Option` is supported where `T` implements `Type`. +//! An `Option` represents a potentially `NULL` value from SQL. + +use std::{borrow::Cow, rc::Rc, sync::Arc}; + +use crate::database::Database; +use crate::type_info::TypeInfo; + +mod non_zero; + +#[cfg(feature = "bstr")] +#[cfg_attr(docsrs, doc(cfg(feature = "bstr")))] +pub mod bstr; + +#[cfg(feature = "json")] +#[cfg_attr(docsrs, doc(cfg(feature = "json")))] +mod json; + +mod text; + +#[cfg(feature = "uuid")] +#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))] +#[doc(no_inline)] +pub use uuid::{self, Uuid}; + +#[cfg(feature = "chrono")] +#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))] +pub mod chrono { + #[doc(no_inline)] + pub use chrono::{ + DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc, + }; +} + +#[cfg(feature = "bit-vec")] +#[cfg_attr(docsrs, doc(cfg(feature = "bit-vec")))] +#[doc(no_inline)] +pub use bit_vec::BitVec; + +#[cfg(feature = "time")] +#[cfg_attr(docsrs, doc(cfg(feature = "time")))] +pub mod time { + #[doc(no_inline)] + pub use time::{Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; +} + +#[cfg(feature = "bigdecimal")] +#[cfg_attr(docsrs, doc(cfg(feature = "bigdecimal")))] +#[doc(no_inline)] +pub use bigdecimal::BigDecimal; +#[cfg(feature = "rust_decimal")] +#[cfg_attr(docsrs, doc(cfg(feature = "rust_decimal")))] +#[doc(no_inline)] +pub use rust_decimal::Decimal; + +#[cfg(feature = "ipnet")] +#[cfg_attr(docsrs, doc(cfg(feature = "ipnet")))] +pub mod ipnet { + #[doc(no_inline)] + pub use ipnet::{IpNet, Ipv4Net, Ipv6Net}; +} + +#[cfg(feature = "ipnetwork")] +#[cfg_attr(docsrs, doc(cfg(feature = "ipnetwork")))] +pub mod ipnetwork { + #[doc(no_inline)] + pub use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network}; +} + +#[cfg(feature = "mac_address")] +#[cfg_attr(docsrs, doc(cfg(feature = "mac_address")))] +pub mod mac_address { + #[doc(no_inline)] + pub use mac_address::MacAddress; +} + +#[cfg(feature = "json")] +pub use json::{Json, JsonRawValue, JsonValue}; +pub use text::Text; + +#[cfg(feature = "bstr")] +pub use bstr::{BStr, BString}; + +/// Indicates that a SQL type is supported for a database. +/// +/// ## Compile-time verification +/// +/// Type definitions are *not* verified against the database at compile-time. +/// The [`query!()`](macro.query.html) macros have no implicit knowledge of user-defined types. +/// +/// When using custom types in query parameters or output columns with `query!()`, +/// the use of [type overrides](macro.query.html#type-overrides-bind-parameters-postgres-only) is required. +/// +/// ```rust,ignore +/// struct MyUser { id: UserId, name: String } +/// +/// // fetch all properties from user and override the type in Rust for `id` +/// let user = query_as!(MyUser, r#"SELECT users.*, id as "id: UserId" FROM users"#) +/// .fetch_one(&pool).await?; +/// ``` +/// +/// ## Derivable +/// +/// This trait can be derived by SQLx to support Rust-only wrapper types, enumerations, and (for +/// postgres) structured records. Additionally, an implementation of [`Encode`](crate::encode::Encode) and [`Decode`](crate::decode::Decode) is +/// generated. +/// +/// ### Transparent +/// +/// Rust-only domain wrappers around SQL types. The generated implementations directly delegate +/// to the implementation of the inner type. +/// +/// ```rust,ignore +/// #[derive(sqlx::Type)] +/// #[sqlx(transparent)] +/// struct UserId(i64); +/// ``` +/// +/// ##### Note: `PgHasArrayType` +/// If you have the `postgres` feature enabled, this derive also generates a `PgHasArrayType` impl +/// so that you may use it with `Vec` and other types that decode from an array in Postgres: +/// +/// ```rust,ignore +/// let user_ids: Vec = sqlx::query_scalar("select '{ 123, 456 }'::int8[]") +/// .fetch(&mut pg_connection) +/// .await?; +/// ``` +/// +/// However, if you are wrapping a type that does not implement `PgHasArrayType` +/// (e.g. `Vec` itself, because we don't currently support multidimensional arrays), +/// you may receive an error: +/// +/// ```rust,ignore +/// #[derive(sqlx::Type)] // ERROR: `Vec` does not implement `PgHasArrayType` +/// #[sqlx(transparent)] +/// struct UserIds(Vec); +/// ``` +/// +/// To remedy this, add `#[sqlx(no_pg_array)]`, which disables the generation +/// of the `PgHasArrayType` impl: +/// +/// ```rust,ignore +/// #[derive(sqlx::Type)] +/// #[sqlx(transparent, no_pg_array)] +/// struct UserIds(Vec); +/// ``` +/// +/// ##### Attributes +/// +/// * `#[sqlx(type_name = "")]` on struct definition: instead of inferring the SQL +/// type name from the inner field (in the above case, `BIGINT`), explicitly set it to +/// `` instead. May trigger errors or unexpected behavior if the encoding of the +/// given type is different than that of the inferred type (e.g. if you rename the above to +/// `VARCHAR`). Affects Postgres only. +/// * `#[sqlx(rename_all = "")]` on struct definition: See [`derive docs in FromRow`](crate::from_row::FromRow#rename_all) +/// * `#[sqlx(no_pg_array)]`: do not emit a `PgHasArrayType` impl (see above). +/// +/// ### Enumeration +/// +/// Enumerations may be defined in Rust and can match SQL by +/// integer discriminant or variant name. +/// +/// With `#[repr(_)]` the integer representation is used when converting from/to SQL and expects +/// that SQL type (e.g., `INT`). Without, the names of the variants are used instead and +/// expects a textual SQL type (e.g., `VARCHAR`, `TEXT`). +/// +/// ```rust,ignore +/// #[derive(sqlx::Type)] +/// #[repr(i32)] +/// enum Color { Red = 1, Green = 2, Blue = 3 } +/// ``` +/// +/// ```rust,ignore +/// #[derive(sqlx::Type)] +/// #[sqlx(type_name = "color")] // only for PostgreSQL to match a type definition +/// #[sqlx(rename_all = "lowercase")] +/// enum Color { Red, Green, Blue } +/// ``` +/// +/// ### Records +/// +/// User-defined composite types are supported through deriving a `struct`. +/// +/// This is only supported for PostgreSQL. +/// +/// ```rust,ignore +/// #[derive(sqlx::Type)] +/// #[sqlx(type_name = "interface_type")] +/// struct InterfaceType { +/// name: String, +/// supplier_id: i32, +/// price: f64 +/// } +/// ``` +pub trait Type { + /// Returns the canonical SQL type for this Rust type. + /// + /// When binding arguments, this is used to tell the database what is about to be sent; which, + /// the database then uses to guide query plans. This can be overridden by `Encode::produces`. + /// + /// A map of SQL types to Rust types is populated with this and used + /// to determine the type that is returned from the anonymous struct type from `query!`. + fn type_info() -> DB::TypeInfo; + + /// Determines if this Rust type is compatible with the given SQL type. + /// + /// When decoding values from a row, this method is checked to determine if we should continue + /// or raise a runtime type mismatch error. + /// + /// When binding arguments with `query!` or `query_as!`, this method is consulted to determine + /// if the Rust type is acceptable. + /// + /// Defaults to checking [`TypeInfo::type_compatible()`]. + fn compatible(ty: &DB::TypeInfo) -> bool { + Self::type_info().type_compatible(ty) + } +} + +// for references, the underlying SQL type is identical +impl, DB: Database> Type for &'_ T { + fn type_info() -> DB::TypeInfo { + >::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + >::compatible(ty) + } +} + +// for optionals, the underlying SQL type is identical +impl, DB: Database> Type for Option { + fn type_info() -> DB::TypeInfo { + >::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + ty.is_null() || >::compatible(ty) + } +} + +macro_rules! impl_type_for_smartpointer { + ($smart_pointer:ty) => { + impl Type for $smart_pointer + where + T: Type + ?Sized, + { + fn type_info() -> DB::TypeInfo { + >::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + >::compatible(ty) + } + } + }; +} + +impl_type_for_smartpointer!(Arc); +impl_type_for_smartpointer!(Box); +impl_type_for_smartpointer!(Rc); + +impl Type for Cow<'_, T> +where + // `ToOwned` is required here to satisfy `Cow` + T: Type + ToOwned + ?Sized, +{ + fn type_info() -> DB::TypeInfo { + >::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + >::compatible(ty) + } +} diff --git a/vendor/sqlx-core/src/types/non_zero.rs b/vendor/sqlx-core/src/types/non_zero.rs new file mode 100755 index 0000000..4f04768 --- /dev/null +++ b/vendor/sqlx-core/src/types/non_zero.rs @@ -0,0 +1,76 @@ +//! [`Type`], [`Encode`], and [`Decode`] implementations for the various [`NonZero*`][non-zero] +//! types from the standard library. +//! +//! [non-zero]: core::num::NonZero + +use std::num::{ + NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, +}; + +use crate::database::Database; +use crate::decode::Decode; +use crate::encode::{Encode, IsNull}; +use crate::types::Type; + +macro_rules! impl_non_zero { + ($($int:ty => $non_zero:ty),* $(,)?) => { + $(impl Type for $non_zero + where + DB: Database, + $int: Type, + { + fn type_info() -> ::TypeInfo { + <$int as Type>::type_info() + } + + fn compatible(ty: &::TypeInfo) -> bool { + <$int as Type>::compatible(ty) + } + } + + impl<'q, DB> Encode<'q, DB> for $non_zero + where + DB: Database, + $int: Encode<'q, DB>, + { + fn encode_by_ref(&self, buf: &mut ::ArgumentBuffer) -> Result { + <$int as Encode<'q, DB>>::encode_by_ref(&self.get(), buf) + } + + fn encode(self, buf: &mut ::ArgumentBuffer) -> Result + where + Self: Sized, + { + <$int as Encode<'q, DB>>::encode(self.get(), buf) + } + + fn produces(&self) -> Option<::TypeInfo> { + <$int as Encode<'q, DB>>::produces(&self.get()) + } + } + + impl<'r, DB> Decode<'r, DB> for $non_zero + where + DB: Database, + $int: Decode<'r, DB>, + { + fn decode(value: ::ValueRef<'r>) -> Result { + let int = <$int as Decode<'r, DB>>::decode(value)?; + let non_zero = Self::try_from(int)?; + + Ok(non_zero) + } + })* + }; +} + +impl_non_zero! { + i8 => NonZeroI8, + u8 => NonZeroU8, + i16 => NonZeroI16, + u16 => NonZeroU16, + i32 => NonZeroI32, + u32 => NonZeroU32, + i64 => NonZeroI64, + u64 => NonZeroU64, +} diff --git a/vendor/sqlx-core/src/types/text.rs b/vendor/sqlx-core/src/types/text.rs new file mode 100755 index 0000000..941e80c --- /dev/null +++ b/vendor/sqlx-core/src/types/text.rs @@ -0,0 +1,134 @@ +use std::ops::{Deref, DerefMut}; + +/// Map a SQL text value to/from a Rust type using [`Display`] and [`FromStr`]. +/// +/// This can be useful for types that do not have a direct SQL equivalent, or are simply not +/// supported by SQLx for one reason or another. +/// +/// For strongly typed databases like Postgres, this will report the value's type as `TEXT`. +/// Explicit conversion may be necessary on the SQL side depending on the desired type. +/// +/// [`Display`]: std::fmt::Display +/// [`FromStr`]: std::str::FromStr +/// +/// ### Panics +/// +/// You should only use this adapter with `Display` implementations that are infallible, +/// otherwise you may encounter panics when attempting to bind a value. +/// +/// This is because the design of the `Encode` trait assumes encoding is infallible, so there is no +/// way to bubble up the error. +/// +/// Fortunately, most `Display` implementations are infallible by convention anyway +/// (the standard `ToString` trait also assumes this), but you may still want to audit +/// the source code for any types you intend to use with this adapter, just to be safe. +/// +/// ### Example: `SocketAddr` +/// +/// MySQL and SQLite do not have a native SQL equivalent for `SocketAddr`, so if you want to +/// store and retrieve instances of it, it makes sense to map it to `TEXT`: +/// +/// ```rust,no_run +/// # use sqlx::types::{time, uuid}; +/// +/// use std::net::SocketAddr; +/// +/// use sqlx::Connection; +/// use sqlx::mysql::MySqlConnection; +/// use sqlx::types::Text; +/// +/// use uuid::Uuid; +/// use time::OffsetDateTime; +/// +/// #[derive(sqlx::FromRow, Debug)] +/// struct Login { +/// user_id: Uuid, +/// socket_addr: Text, +/// login_at: OffsetDateTime +/// } +/// +/// # async fn example() -> Result<(), Box> { +/// +/// let mut conn: MySqlConnection = MySqlConnection::connect("").await?; +/// +/// let user_id: Uuid = "e9a72cdc-d907-48d6-a488-c64a91fd063c".parse().unwrap(); +/// let socket_addr: SocketAddr = "198.51.100.47:31790".parse().unwrap(); +/// +/// // CREATE TABLE user_login(user_id VARCHAR(36), socket_addr TEXT, login_at TIMESTAMP); +/// sqlx::query("INSERT INTO user_login(user_id, socket_addr, login_at) VALUES (?, ?, NOW())") +/// .bind(user_id) +/// .bind(Text(socket_addr)) +/// .execute(&mut conn) +/// .await?; +/// +/// let logins: Vec = sqlx::query_as("SELECT * FROM user_login") +/// .fetch_all(&mut conn) +/// .await?; +/// +/// println!("Logins for user ID {user_id}: {logins:?}"); +/// +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Text(pub T); + +impl Text { + /// Extract the inner value. + pub fn into_inner(self) -> T { + self.0 + } +} + +impl Deref for Text { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Text { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/* We shouldn't use blanket impls so individual drivers can provide specialized ones. +impl Type for Text +where + String: Type, + DB: Database, +{ + fn type_info() -> DB::TypeInfo { + String::type_info() + } + + fn compatible(ty: &DB::TypeInfo) -> bool { + String::compatible(ty) + } +} + +impl<'q, T, DB> Encode<'q, DB> for Text +where + T: Display, + String: Encode<'q, DB>, + DB: Database, +{ + fn encode_by_ref(&self, buf: &mut ::ArgumentBuffer) -> Result { + self.0.to_string().encode(buf) + } +} + +impl<'r, T, DB> Decode<'r, DB> for Text +where + T: FromStr, + BoxDynError: From<::Err>, + &'r str: Decode<'r, DB>, + DB: Database, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + Ok(Text(<&'r str as Decode<'r, DB>>::decode(value)?.parse()?)) + } +} +*/ diff --git a/vendor/sqlx-core/src/value.rs b/vendor/sqlx-core/src/value.rs new file mode 100755 index 0000000..94e8b7b --- /dev/null +++ b/vendor/sqlx-core/src/value.rs @@ -0,0 +1,113 @@ +use crate::database::Database; +use crate::decode::Decode; +use crate::error::{mismatched_types, Error}; +use crate::type_info::TypeInfo; +use crate::types::Type; +use std::borrow::Cow; + +/// An owned value from the database. +pub trait Value { + type Database: Database; + + /// Get this value as a reference. + fn as_ref(&self) -> ::ValueRef<'_>; + + /// Get the type information for this value. + fn type_info(&self) -> Cow<'_, ::TypeInfo>; + + /// Returns `true` if the SQL value is `NULL`. + fn is_null(&self) -> bool; + + /// Decode this single value into the requested type. + /// + /// # Panics + /// + /// Panics if the value cannot be decoded into the requested type. + /// See [`try_decode`](Self::try_decode) for a non-panicking version. + /// + #[inline] + fn decode<'r, T>(&'r self) -> T + where + T: Decode<'r, Self::Database> + Type, + { + self.try_decode::().unwrap() + } + + /// Decode this single value into the requested type. + /// + /// Unlike [`decode`](Self::decode), this method does not check that the type of this + /// value is compatible with the Rust type and blindly tries to decode the value. + /// + /// # Panics + /// + /// Panics if the value cannot be decoded into the requested type. + /// See [`try_decode_unchecked`](Self::try_decode_unchecked) for a non-panicking version. + /// + #[inline] + fn decode_unchecked<'r, T>(&'r self) -> T + where + T: Decode<'r, Self::Database>, + { + self.try_decode_unchecked::().unwrap() + } + + /// Decode this single value into the requested type. + /// + /// # Errors + /// + /// * [`Decode`] if the value could not be decoded into the requested type. + /// + /// [`Decode`]: Error::Decode + /// + #[inline] + fn try_decode<'r, T>(&'r self) -> Result + where + T: Decode<'r, Self::Database> + Type, + { + if !self.is_null() { + let ty = self.type_info(); + + if !ty.is_null() && !T::compatible(&ty) { + return Err(Error::Decode(mismatched_types::(&ty))); + } + } + + self.try_decode_unchecked() + } + + /// Decode this single value into the requested type. + /// + /// Unlike [`try_decode`](Self::try_decode), this method does not check that the type of this + /// value is compatible with the Rust type and blindly tries to decode the value. + /// + /// # Errors + /// + /// * [`Decode`] if the value could not be decoded into the requested type. + /// + /// [`Decode`]: Error::Decode + /// + #[inline] + fn try_decode_unchecked<'r, T>(&'r self) -> Result + where + T: Decode<'r, Self::Database>, + { + T::decode(self.as_ref()).map_err(Error::Decode) + } +} + +/// A reference to a single value from the database. +pub trait ValueRef<'r>: Sized { + type Database: Database; + + /// Creates an owned value from this value reference. + /// + /// This is just a reference increment in PostgreSQL and MySQL and thus is `O(1)`. In SQLite, + /// this is a copy. + fn to_owned(&self) -> ::Value; + + /// Get the type information for this value. + fn type_info(&self) -> Cow<'_, ::TypeInfo>; + + /// Returns `true` if the SQL value is `NULL`. + fn is_null(&self) -> bool; +}