Search code examples
mysqlrustrust-dieselrust-rocket

How to write column names with whitespace in diesel model.rs?


I am trying to use Diesel to manage my database to use with Rocket and i got stuck at writing the models.rs for my table:

CREATE TABLE `problemSet` (
  `id` varchar(10) NOT NULL,
  `contestId` int DEFAULT NULL,
  `difficulty` varchar(10) DEFAULT NULL,
  `title` varchar(300) DEFAULT NULL,
  `rating` int DEFAULT NULL,
  `link` varchar(300) DEFAULT NULL,
  `binary search` tinyint(1) DEFAULT '0',
  `chinese remainder theorem` tinyint(1) DEFAULT '0',
  `constructive algorithms` tinyint(1) DEFAULT '0',
  `data structures` tinyint(1) DEFAULT '0',
  `dfs and similar` tinyint(1) DEFAULT '0',
  `divide and conquer` tinyint(1) DEFAULT '0',
  PRIMARY KEY(`id`)
  );

Here, I am confused for how to write the identifiers in struct of models.rs for column_names with whitespaces.

I was referring to official guide of Diesel and RUST.


Solution

  • When defining the schema, you can use the sql_name attribute to specify a name for a column that is different to the name as it will appear in rust code:

    diesel::table! {
        problemSet {
            ...
            #[sql_name = "divide and conquer"]
            divide_and_conquer -> Text,
            ...
        }
    }
    

    See: documentation for the table! macro

    Having said that, my preference would be to keep away from spaces in column names.