SQLX-MODELS

sqlx-modes is a working progress implementation for a sql migration manangement tool for applications using sqlx.

Basic Tutorial

install the CLI by running the following command: cargo install sqlx-models-cli

now write in src/main.rs: ```rust use sqlx_models::Model;

[derive(Model)]

struct User { #[primarykey] id: i32, #[unique] email: String, password: String, #[default = 0] isadmin: bool, }

[derive(Model)]

struct PostLike { #[foreignkey(User.id)] #[primarykey(postid)] userid: i32, #[foreignkey(Post.id)] postid: i32, }

[derive(Model)]

struct CommentLike { #[foreignkey(User.id)] #[primarykey(comment)] user: i32, #[foreignkey(Comment.id)] comment: i32, #[default = false] isdislike: bool, }

[derive(Model)]

struct Post { #[primarykey] id: i32, #[foreignkey(User.id)] author_: String, #[default = ""] title: String, content: String, }

[derive(Model)]

struct Comment { #[primarykey] id: i32, #[foreignkey(User.id)] author: i32, #[foreign_key(Post.id)] post: i32, } ```

If you now run the following command, your migrations should be automatically created (make sure your code compiles). sqlx generate the output generated should look something like this ```sql -- at user.sql. CREATE TABLE user ( id INTEGER NOT NULL, email TEXT NOT NULL, PASSWORD TEXT NOT NULL, isadmin BOOLEAN NOT NULL DEFAULT 0, CONSTRAINT userprimaryid PRIMARY KEY (id), CONSTRAINT useruniqueemail UNIQUE (email) ); -- at post.sql. CREATE TABLE post ( id INTEGER NOT NULL, author TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', content TEXT NOT NULL, CONSTRAINT postprimaryid PRIMARY KEY (id), CONSTRAINT postforeignauthor_id FOREIGN KEY (author) REFERENCES User(id) );

-- at comment.sql. CREATE TABLE COMMENT ( id INTEGER NOT NULL, author INTEGER NOT NULL, post INTEGER NOT NULL, CONSTRAINT commentprimaryid PRIMARY KEY (id), CONSTRAINT commentforeignauthorid FOREIGN KEY (author) REFERENCES User(id), CONSTRAINT commentforeignpostid FOREIGN KEY (post) REFERENCES Post(id) ); -- at commentlike.sql.

CREATE TABLE commentlike ( user INTEGER NOT NULL, COMMENT INTEGER NOT NULL, isdislike BOOLEAN NOT NULL DEFAULT false, CONSTRAINT commentlikeforeignuserid FOREIGN KEY (user) REFERENCES User(id), CONSTRAINT commentlikeprimaryusercomment PRIMARY KEY (user, COMMENT), CONSTRAINT commentlikeforeigncommentid FOREIGN KEY (COMMENT) REFERENCES COMMENT(id) );

-- at postlike.sql. CREATE TABLE postlike ( userid INTEGER NOT NULL, postid INTEGER NOT NULL, CONSTRAINT postlikeforeignuseridid FOREIGN KEY (userid) REFERENCES User(id), CONSTRAINT postlikeprimaryuseridpostid PRIMARY KEY (userid, postid), CONSTRAINT postlikeforeignpostidid FOREIGN KEY (postid) REFERENCES Post(id) ); ``` If we later modify those structures in our application, we can generate new migrations to update the tables.