Skip to content

Commit

Permalink
Merge pull request #2010 from KeenS/try_from
Browse files Browse the repository at this point in the history
ungate try_from because it has been stabilized
  • Loading branch information
weiznich authored Apr 16, 2019
2 parents 2c574bb + e4bdb2e commit 167e704
Show file tree
Hide file tree
Showing 37 changed files with 159 additions and 89 deletions.
8 changes: 4 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ matrix:
allow_failures:
- rust: nightly
include:
- rust: nightly-2018-11-27
- rust: nightly-2019-02-26
name: "Compile tests"
script:
- (cd diesel_compile_tests && cargo +$TRAVIS_RUST_VERSION test)
- rust: 1.31.1
- rust: 1.34.0
name: "Rustfmt && Clippy"
script:
- rustup component add rustfmt clippy
Expand All @@ -59,8 +59,8 @@ matrix:
- SQLITE_DATABASE_URL=/tmp/test.db
script:
- (cd diesel_cli && cargo +$TRAVIS_RUST_VERSION test --no-default-features --features "sqlite-bundled")
- rust: 1.31.1
name: "Minimal supported rust version == 1.31.1"
- rust: 1.34.0
name: "Minimal supported rust version == 1.34.0"
script:
- cargo +$TRAVIS_RUST_VERSION check --all

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ for Rust libraries in [RFC #1105](https://github.com/rust-lang/rfcs/blob/master/
`&DB::RawValue` or `&<DB as Backend>::RawValue>`) should use
[`backend::RawValue<DB>`][raw-value-2-0-0] instead. Implementors of `Backend`
should check the relevant section of [the migration guide][2-0-migration].
* The minimal officially supported rustc version is now 1.34.0

[backend-2-0-0]: http://docs.diesel.rs/diesel/backend/trait.Backend.html
[raw-value-2-0-0]: http://docs.diesel.rs/diesel/backend/type.RawValue.html
Expand Down
8 changes: 4 additions & 4 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ jobs:
- template: _build/install-rust.yml
parameters:
platform: Linux
rust_version: nightly-2018-11-27
rust_version: nightly-2019-02-26
- bash: |
sudo apt-get update &&
sudo apt-get -y install libsqlite3-dev libpq-dev libmysqlclient-dev
Expand All @@ -195,7 +195,7 @@ jobs:
- template: _build/install-rust.yml
parameters:
platform: Linux
rust_version: 1.31.1
rust_version: 1.34.0
- bash: |
sudo apt-get update &&
sudo apt-get -y install libsqlite3-dev libpq-dev libmysqlclient-dev
Expand Down Expand Up @@ -239,11 +239,11 @@ jobs:
- template: _build/install-rust.yml
parameters:
platform: Linux
rust_version: 1.31.1
rust_version: 1.34.0
- bash: |
sudo apt-get update &&
sudo apt-get -y install libsqlite3-dev libpq-dev libmysqlclient-dev
displayName: Install build dependencies
- bash: |
cargo check --all
displayName: Check building with rust 1.31.1
displayName: Check building with rust 1.34.0
2 changes: 1 addition & 1 deletion diesel/src/connection/statement_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub struct StatementCache<DB: Backend, Statement> {
pub cache: RefCell<HashMap<StatementCacheKey<DB>, Statement>>,
}

#[allow(clippy::len_without_is_empty, clippy::new_without_default_derive)]
#[allow(clippy::len_without_is_empty, clippy::new_without_default)]
impl<DB, Statement> StatementCache<DB, Statement>
where
DB: Backend,
Expand Down
2 changes: 1 addition & 1 deletion diesel/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
//! You can come ask for help at
//! [gitter.im/diesel-rs/diesel](https://gitter.im/diesel-rs/diesel)

#![cfg_attr(feature = "unstable", feature(specialization, try_from))]
#![cfg_attr(feature = "unstable", feature(specialization))]
// Built-in Lints
#![deny(
warnings,
Expand Down
2 changes: 1 addition & 1 deletion diesel/src/mysql/connection/url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl ConnectionOptions {
return Err(connection_url_error());
}

if url.path_segments().map(|x| x.count()).unwrap_or(0) > 1 {
if url.path_segments().map(Iterator::count).unwrap_or(0) > 1 {
return Err(connection_url_error());
}

Expand Down
2 changes: 1 addition & 1 deletion diesel/src/mysql/types/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub mod bigdecimal {
fn to_sql<W: Write>(&self, out: &mut Output<W, Mysql>) -> serialize::Result {
write!(out, "{}", *self)
.map(|_| IsNull::No)
.map_err(|e| e.into())
.map_err(Into::into)
}
}

Expand Down
2 changes: 0 additions & 2 deletions diesel/src/pg/connection/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,6 @@ impl NamedCursor {
where
T: QueryableByName<Pg>,
{
use result::Error::DeserializationError;

(0..self.db_result.num_rows())
.map(|i| {
let row = PgNamedRow::new(&self, i);
Expand Down
4 changes: 2 additions & 2 deletions diesel/src/pg/types/integers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ use sql_types;
impl FromSql<sql_types::Oid, Pg> for u32 {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
let mut bytes = not_none!(bytes);
bytes.read_u32::<NetworkEndian>().map_err(|e| e.into())
bytes.read_u32::<NetworkEndian>().map_err(Into::into)
}
}

impl ToSql<sql_types::Oid, Pg> for u32 {
fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
out.write_u32::<NetworkEndian>(*self)
.map(|_| IsNull::No)
.map_err(|e| e.into())
.map_err(Into::into)
}
}

Expand Down
70 changes: 33 additions & 37 deletions diesel/src/pg/types/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ mod bigdecimal {
use serialize::{self, Output, ToSql};
use sql_types::Numeric;

#[cfg(feature = "unstable")]
use std::convert::{TryFrom, TryInto};
#[cfg(feature = "unstable")]
use std::error::Error;

/// Iterator over the digits of a big uint in base 10k.
Expand All @@ -40,44 +38,40 @@ mod bigdecimal {
}
}

fn pg_decimal_to_bigdecimal(numeric: &PgNumeric) -> deserialize::Result<BigDecimal> {
let (sign, weight, scale, digits) = match *numeric {
PgNumeric::Positive {
weight,
scale,
ref digits,
} => (Sign::Plus, weight, scale, digits),
PgNumeric::Negative {
weight,
scale,
ref digits,
} => (Sign::Minus, weight, scale, digits),
PgNumeric::NaN => return Err(Box::from("NaN is not (yet) supported in BigDecimal")),
};

let mut result = BigUint::default();
let count = digits.len() as i64;
for digit in digits {
result *= BigUint::from(10_000u64);
result += BigUint::from(*digit as u64);
}
// First digit got factor 10_000^(digits.len() - 1), but should get 10_000^weight
let correction_exp = 4 * (i64::from(weight) - count + 1);
let result = BigDecimal::new(BigInt::from_biguint(sign, result), -correction_exp)
.with_scale(i64::from(scale));
Ok(result)
}

#[cfg(feature = "unstable")]
impl<'a> TryFrom<&'a PgNumeric> for BigDecimal {
type Error = Box<Error + Send + Sync>;

fn try_from(numeric: &'a PgNumeric) -> deserialize::Result<Self> {
pg_decimal_to_bigdecimal(numeric)
let (sign, weight, scale, digits) = match *numeric {
PgNumeric::Positive {
weight,
scale,
ref digits,
} => (Sign::Plus, weight, scale, digits),
PgNumeric::Negative {
weight,
scale,
ref digits,
} => (Sign::Minus, weight, scale, digits),
PgNumeric::NaN => {
return Err(Box::from("NaN is not (yet) supported in BigDecimal"))
}
};

let mut result = BigUint::default();
let count = digits.len() as i64;
for digit in digits {
result *= BigUint::from(10_000u64);
result += BigUint::from(*digit as u64);
}
// First digit got factor 10_000^(digits.len() - 1), but should get 10_000^weight
let correction_exp = 4 * (i64::from(weight) - count + 1);
let result = BigDecimal::new(BigInt::from_biguint(sign, result), -correction_exp)
.with_scale(i64::from(scale));
Ok(result)
}
}

#[cfg(feature = "unstable")]
impl TryFrom<PgNumeric> for BigDecimal {
type Error = Box<Error + Send + Sync>;

Expand All @@ -88,7 +82,11 @@ mod bigdecimal {

impl<'a> From<&'a BigDecimal> for PgNumeric {
// NOTE(clippy): No `std::ops::MulAssign` impl for `BigInt`
#[allow(clippy::assign_op_pattern)]
// NOTE(clippy): Clippy suggests to replace the `.take_while(|i| i.is_zero())`
// with `.take_while(Zero::is_zero)`, but that's a false positive.
// The closure gets an `&&i16` due to autoderef `<i16 as Zero>::is_zero(&self) -> bool`
// is called. There is no impl for `&i16` that would work with this closure.
#[allow(clippy::assign_op_pattern, clippy::redundant_closure)]
fn from(decimal: &'a BigDecimal) -> Self {
let (mut integer, scale) = decimal.as_bigint_and_exponent();
let scale = scale as u16;
Expand Down Expand Up @@ -156,9 +154,7 @@ mod bigdecimal {

impl FromSql<Numeric, Pg> for BigDecimal {
fn from_sql(numeric: Option<&[u8]>) -> deserialize::Result<Self> {
// FIXME: Use the TryFrom impl when try_from is stable
let numeric = PgNumeric::from_sql(numeric)?;
pg_decimal_to_bigdecimal(&numeric)
PgNumeric::from_sql(numeric)?.try_into()
}
}

Expand Down
2 changes: 1 addition & 1 deletion diesel/src/pg/types/uuid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct UuidProxy(uuid::Uuid);
impl FromSql<Uuid, Pg> for uuid::Uuid {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
let bytes = not_none!(bytes);
uuid::Uuid::from_bytes(bytes).map_err(|e| e.into())
uuid::Uuid::from_bytes(bytes).map_err(Into::into)
}
}

Expand Down
2 changes: 1 addition & 1 deletion diesel/src/pg/types/uuid_v0_7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct UuidProxy(uuid::Uuid);
impl FromSql<Uuid, Pg> for uuid::Uuid {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
let bytes = not_none!(bytes);
uuid::Uuid::from_slice(bytes).map_err(|e| e.into())
uuid::Uuid::from_slice(bytes).map_err(Into::into)
}
}

Expand Down
2 changes: 1 addition & 1 deletion diesel/src/query_builder/bind_collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub struct RawBytesBindCollector<DB: Backend + TypeMetadata> {
pub binds: Vec<Option<Vec<u8>>>,
}

#[allow(clippy::new_without_default_derive)]
#[allow(clippy::new_without_default)]
impl<DB: Backend + TypeMetadata> RawBytesBindCollector<DB> {
/// Construct an empty `RawBytesBindCollector`
pub fn new() -> Self {
Expand Down
2 changes: 1 addition & 1 deletion diesel/src/query_builder/update_statement/changeset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl<T: AsChangeset> AsChangeset for Option<T> {
type Changeset = Option<T::Changeset>;

fn as_changeset(self) -> Self::Changeset {
self.map(|v| v.as_changeset())
self.map(AsChangeset::as_changeset)
}
}

Expand Down
1 change: 0 additions & 1 deletion diesel/src/query_builder/where_clause.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@ where

fn and(self, predicate: Predicate) -> Self::Output {
use self::BoxedWhereClause::Where;
use expression::operators::And;

match self {
Where(where_clause) => Where(Box::new(And::new(where_clause, predicate))),
Expand Down
5 changes: 1 addition & 4 deletions diesel_cli/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,9 @@ fn drop_database(database_url: &str) -> DatabaseResult<()> {
}
#[cfg(feature = "sqlite")]
Backend::Sqlite => {
use std::fs;
use std::path::Path;

if Path::new(database_url).exists() {
println!("Dropping database: {}", database_url);
fs::remove_file(&database_url)?;
std::fs::remove_file(&database_url)?;
}
}
#[cfg(feature = "mysql")]
Expand Down
6 changes: 3 additions & 3 deletions diesel_cli/src/database_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ impl Error for DatabaseError {
}
IoError(ref error) => error
.source()
.map(|e| e.description())
.map(Error::description)
.unwrap_or_else(|| error.description()),
QueryError(ref error) => error
.source()
.map(|e| e.description())
.map(Error::description)
.unwrap_or_else(|| error.description()),
ConnectionError(ref error) => error
.source()
.map(|e| e.description())
.map(Error::description)
.unwrap_or_else(|| error.description()),
}
}
Expand Down
2 changes: 1 addition & 1 deletion diesel_cli/src/infer_schema_internals/foreign_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub fn remove_unsafe_foreign_keys_for_codegen(

let duplicates = foreign_keys
.iter()
.map(|fk| fk.ordered_tables())
.map(ForeignKeyConstraint::ordered_tables)
.filter(|tables| {
let dup_count = foreign_keys
.iter()
Expand Down
1 change: 0 additions & 1 deletion diesel_cli/tests/support/project_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ impl Project {
}

pub fn create_migration_in_directory(&self, directory: &str, name: &str, up: &str, down: &str) {
use std::io::Write;
let migration_path = self.directory.path().join(directory).join(name);
fs::create_dir(&migration_path)
.expect("Migrations folder must exist to create a migration");
Expand Down
2 changes: 1 addition & 1 deletion diesel_compile_tests/rust-toolchain
Original file line number Diff line number Diff line change
@@ -1 +1 @@
nightly-2018-11-27
nightly-2019-02-26
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ fn main() {
//~| ERROR E0277
//~| ERROR E0277
//~| ERROR E0277
//~| ERROR E0277
select(array((1f64, 3f64))).get_result::<Vec<f64>>(&connection);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ fn main() {
//~| ERROR E0277
//~| ERROR E0277
//~| ERROR E0277
//~| ERROR E0277

select(array((1, 3f64))).get_result::<Vec<f64>>(&connection).unwrap();
//~^ ERROR E0277
Expand All @@ -26,4 +27,5 @@ fn main() {
//~| ERROR E0277
//~| ERROR E0277
//~| ERROR E0277
//~| ERROR E0277
}
4 changes: 2 additions & 2 deletions diesel_compile_tests/tests/compile_tests.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
#![cfg(not(windows))]
extern crate compiletest_rs as compiletest;

use std::path::PathBuf;
use std::env::var;
use std::path::PathBuf;

fn run_mode(mode: &'static str) {
let mut config = compiletest::Config::default();

let cfg_mode = mode.parse().expect("Invalid mode");

if let Ok(name) = var::<&str>("TESTNAME") {
let s : String = name.to_owned();
let s: String = name.to_owned();
config.filter = Some(s)
}
config.mode = cfg_mode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,23 @@ error: `column_name` must be in the form `column_name = "value"`
14 | #[column_name]
| ^^^^^^^^^^^

error: aborting due to previous error
error[E0412]: cannot find type `column_name` in module `users`
--> $DIR/as_changeset_bad_column_name_syntax.rs:14:7
|
14 | #[column_name]
| ^^^^^^^^^^^ not found in `users`

error[E0425]: cannot find value `column_name` in module `users`
--> $DIR/as_changeset_bad_column_name_syntax.rs:14:7
|
14 | #[column_name]
| ^^^^^^^^^^^ not found in `users`

error[E0601]: `main` function not found in crate `as_changeset_bad_column_name_syntax`
|
= note: consider adding a `main` function to `$DIR/as_changeset_bad_column_name_syntax.rs`

error: aborting due to 4 previous errors

Some errors occurred: E0412, E0425, E0601.
For more information about an error, try `rustc --explain E0412`.
Loading

0 comments on commit 167e704

Please sign in to comment.