0

When using GraphQL mutations to create records, it expects the full object in return, e.g.:

mutation {
  createPost(title: "Good morning") {
    id
    title
  }
}

How do I reliably get MySQL to return the newly inserted item? I'm currently doing this:

INSERT INTO posts(title) VALUES('Good morning');
SELECT * FROM posts WHERE id = LAST_INSERT_ID();

But I'm not sure if this is the best way. What if another user happens to perform an INSERT immediately after my own? Would LAST_INSERT_ID() refer to their primary key ID instead of mine?

ffxsam
  • 26,428
  • 32
  • 94
  • 144
  • It's a valid concern, but I don't think it's really specific to GraphQL. You would, after all, wonder the same thing if you were building a REST API as well. The answer to your question can be found here: https://stackoverflow.com/a/17112962/6024220 – Daniel Rearden Feb 09 '19 at 18:45
  • This is the only way possible in MySQL `LAST_INSERT_ID()` is session based so it's safe to use it like that.. PostgreSQL has a even better feature `INSERT INTO ... RETURNING *` it can directly return the output, i wished MySQL also supported this syntax. – Raymond Nijland Feb 09 '19 at 18:46

1 Answers1

0

That's the way we did it at my last job, and never had any problems. The docs say it is per connection, so you don't need to worry about another connection changing it.

One thing to be careful of is inserting multiple rows with one INSERT statement. In this case LAST_INSERT_ID() will return the first inserted ID.

Kelly Joyner
  • 143
  • 6