sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

how to convert mysql bit(1)/tinyint(1) to rust type bool?

Open LayneYy opened this issue 6 years ago • 10 comments

In mysql(Version 8.0.22),bit(1) or tinyint(1) represents a bool value.But query_as!() macro transforms bit(1) as u8 and tinyint(1) as i8.

#[derive(Debug)]
pub struct WxUserInfo {
    pub info_id: i64,
    pub open_id: String,
    pub has_subscript: bool,
    pub sub_time: NaiveDateTime,
}
pub async fn by_id(conn: &mut MySqlConnection, info_id: i64) -> sqlx::Result<WxUserInfo> {
    query_as!(
        WxUserInfo,
        "select *from wx_user_info where info_id = ?",
        info_id
        )
        .fetch_one(conn)
        .await
    // Ok(adapter.into())
}


error[E0308]: mismatched types
  --> service/src/model/entity/wx.rs:34:9
   |
34 | /         query_as!(
35 | |         WxUserInfo,
36 | |         "select *from wx_user_info where info_id = ?",
37 | |         info_id
38 | |         )
   | |_________^ expected `bool`, found `u8`
CREATE TABLE `wx_user_info` (
  `info_id` bigint NOT NULL ,
  `open_id` varchar(32) NOT NULL,
  `has_subscript` bit(1) NOT NULL ,
  `sub_time` datetime NOT NULL ,
  PRIMARY KEY (`info_id`),
  UNIQUE KEY `wx_user_info_info_id_uindex` (`info_id`),
  UNIQUE KEY `wx_user_info_open_id_uindex` (`open_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

LayneYy avatar Dec 04 '20 12:12 LayneYy

I ran into this myself. I'm not sure about bit(1), but for tinyint(1) It looks like this crate can convert it to a rust bool, but by default wants to use an i8. You can coerce it to a bool by altering your query like this (if has_subscript was a tinyint(1):

SELECT
  info_id,
  open_id,
  has_subscript as `has_subscript: _`, -- or `has_subscript: bool`
  sub_time
FROM wx_user_info where info_id = ?

There are details on the docs for query!: https://docs.rs/sqlx/0.4.1/sqlx/macro.query.html#force-a-differentcustom-type

For bit(1) you might have implement Decode for a custom type

SHDavies avatar Dec 17 '20 18:12 SHDavies

The workaround of : https://docs.rs/sqlx/0.4.1/sqlx/macro.query.html#force-a-differentcustom-type results in lota boilerplate code when u have only have 1 bool column and more than 20 non bool columns as you have to type name of each column instead of select * from tablename

LightSith avatar Dec 18 '20 07:12 LightSith

If possible, I think it would make sense if you could instruct sqlx to use a custom type when defining a struct deriving FromRow (maybe using a field attribute?).

Allowing that would mean you wouldn't need to duplicate the type override in every single query returning that struct, and you also wouldn't need to enumerate every column in queries fetching all columns (mentioned by the previous comment).

tobbez avatar May 05 '21 10:05 tobbez

I'm also facing this issue.

Cightline avatar May 08 '21 20:05 Cightline

Just ran into this problem and I have to say - it's really frustrating. The "accepted" workaround becomes a big problem when you start to have a lot of bool fields:

use serde::{Deserialize, Serialize};
use sqlx::{query_as, MySqlPool};

#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct DbAccessRole {
    id: u8,
    name: String,
    title: String,

    // General
    can_log_in: bool,
    can_queue_for_matchmaking: bool,

    // User Moderation
    can_view_users: bool,
    can_manage_users: bool,
    can_ban_users: bool,

    // Match Outcome Disputes
    can_view_disputes: bool,
    can_assist_disputes: bool,
    can_resolve_disputes: bool,

    // System Administration
    can_view_system: bool,
    can_modify_system: bool,
}

impl DbAccessRole {
    pub async fn all(db: &MySqlPool) -> sqlx::Result<Vec<DbAccessRole>> {
        query_as!(DbAccessRole, "SELECT * FROM `access_role`",)
            .fetch_all(db)
            .await
    }

    pub async fn by_name(db: &MySqlPool, name: &String) -> sqlx::Result<Option<DbAccessRole>> {
        query_as!(
            DbAccessRole,
            "SELECT * FROM `access_role` WHERE `name` = ?",
            name
        )
        .fetch_optional(db)
        .await
    }
}

Each one of these bool fields is mapped as a tinyint(1) in the MySQL database schema, and I get compile errors for query_as!(...):

error[E0277]: the trait bound `bool: From<i8>` is not satisfied
  --> src\db\access_role.rs:31:9
   |
31 |         query_as!(DbAccessRole, "SELECT * FROM `access_role`",)
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `From<i8>` is not implemented for `bool`
   |
   = help: the trait `From<subtle::Choice>` is implemented for `bool`
   = note: required for `i8` to implement `Into<bool>`

Ideally, sqlx should know that the MySQL engine converts all bit, bool, and boolean types to tinyint and provide a seamless conversion if the type is specified as bool in the Rust code.

If the sqlx team doesn't want to break the explicit type safety, then there should be a field attribute to override/specify the database type that it should type-check against and convert from:

pub(crate) struct DbAccessRole {
    id: u8,
    name: String,

    #[sqlx(type = u8)]
    can_log_in: bool,
}

BTOdell avatar Oct 30 '23 04:10 BTOdell

I'm also facing this issue.

avahe-kellenberger avatar Oct 31 '23 09:10 avahe-kellenberger

According to the docs, Rust bool should be convertible with MySQL tinyint(1): https://docs.rs/sqlx-mysql/0.7.2/sqlx_mysql/types/index.html#types

BTOdell avatar Oct 31 '23 22:10 BTOdell

I've already added an explanation to the docs for how the mapping actually works, it's just not released yet:

https://github.com/launchbadge/sqlx/blob/e1ac3881734293cb33674a8b0b1d983132b9c2b1/sqlx-mysql/src/types/mod.rs#L21-L36

TL;DR: you have to explicitly ask for the conversion on decode, because there's no way for SQLx to know that tinyint(1) is actually supposed to be a boolean and not an i8.

abonander avatar Oct 31 '23 22:10 abonander

Is that an acceptable solution for the library given that it excludes support for the SELECT * syntax? It's cumbersome to have to duplicate the entire list of columns during decode.

Off the top of your head, would it be a significant amount of work to allow a field attribute to specify the type override in the struct definition like I suggested?

BTOdell avatar Nov 01 '23 16:11 BTOdell

In case it helps anyone, I just use a quick wrapper. Using this as the destination type or struct field allows you to select directly.

/// Simple wrapper type that provides SQL conversions to a u8
///
/// See <https://github.com/launchbadge/sqlx/issues/877>
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct SqlBool(pub bool);

impl From<i8> for SqlBool {
    fn from(value: i8) -> Self {
        match value {
            0 => Self(false),
            1 => Self(true),
            _ => panic!("invalid boolean value {value}"),
        }
    }
}

Not as nice as an inbuilt solution, but I can't see how that would work

tgross35 avatar Jan 26 '24 11:01 tgross35