Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly insert ActiveModel::default() #97

Closed
billy1624 opened this issue Aug 20, 2021 · 3 comments
Closed

Correctly insert ActiveModel::default() #97

billy1624 opened this issue Aug 20, 2021 · 3 comments

Comments

@billy1624
Copy link
Member

let cake = cake::ActiveModel { ..Default::default() };
Cake::insert(cake).exec(db).await?;

This returns a database error:

Query Error: error returned from database: syntax error at or near ")"

Because the generated query is:

INSERT INTO "cakes" () VALUES () RETURNING "id" AS "last_insert_id"

@acidic9 thanks for reporting this!

@tyt2y3
Copy link
Member

tyt2y3 commented Aug 21, 2021

@acidic9
What is the desired behavior in this case? NOOP (do nothing)?

@tqwewe
Copy link
Contributor

tqwewe commented Aug 21, 2021

A small fix would be to simple check that all fields in the active model are unset, and in that case panic!(...).

Optimally, it would be best that this code doesn't even compile.
Maybe by making an insert require fields which are not null and do not have a default value. For example a username.

This is why through my experience with using SeaOMR, it seems like it may be worth investigating having a separate struct for inserts.

This is why it may be also worth investigating generating a schema.rs file which contains the database complete schema with columns, column types, nullablility. This schema can then be used for macros to lookup and prevent queries which will not even compile.

@tqwewe
Copy link
Contributor

tqwewe commented Sep 4, 2021

Following up on this, I just thought that there may be cases where someone might actually want this. For example, if every column in the table has a default value.

In which case the query should execute, but should not contain the parenthesis () I believe.
Eg:

INSERT INTO "cakes" RETURNING "id" AS "last_insert_id"

If I'm not wrong, this is a valid SQL query.

But in the case of an update, perhaps it can be a NOOP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants