Search code examples
mysqlrustrdbmsddlrust-diesel

Declarative schema definition with Diesel


I want to write table schemas declarative way like

However, As far I know, Diesel requires hand-written migration DDL like below.

-- up.sql
CREATE TABLE members (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL
);

-- down.sql
DROP TABLE members;

It is complex a little bit because it is stateful.

Is a declarative way to write schemas provided by Diesel? Or do a good external tool exist?

I found Prisma can generate DDL equivalent to up.sql from declarative schema written in its own syntax. But I couldn't find a way to generate down.sql https://www.prisma.io/docs/concepts/components/prisma-migrate


Solution

  • If I understand correctly, you're looking for a way to keep your rust entities and db schema in sync, without having to write any SQL (which is basically what a regular orm like EFCore or GORM would provide).

    If that's what you need, I'm afraid diesel won't do what you're looking for. There is this library which looks nice https://github.com/rust-db/barrel, and it provides a way for you to write your migrations in Rust instead of SQL, a bit like EFCore.

    diesel also provides the embed_migrations! macro, which you can use in order to automatically run migrations without using the cli.

    However, while all these tools will sort of help you out in automating your db migrations, you're still going to have to write them manually.