From c16d80fd94e7f68653bf96938a09e0bb1aa6b25d Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 28 Oct 2024 15:40:24 -0500 Subject: [PATCH] Add Get Fields For Inserted Row as a Drizzle TIL --- README.md | 3 +- drizzle/get-fields-for-inserted-row.md | 56 ++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 drizzle/get-fields-for-inserted-row.md diff --git a/README.md b/README.md index 6e26df5..1194b27 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1487 TILs and counting..._ +_1488 TILs and counting..._ --- @@ -212,6 +212,7 @@ _1487 TILs and counting..._ ### Drizzle - [Create bigint Identity Column For Primary Key](drizzle/create-bigint-identity-column-for-primary-key.md) +- [Get Fields For Inserted Row](drizzle/get-fields-for-inserted-row.md) ### Elixir diff --git a/drizzle/get-fields-for-inserted-row.md b/drizzle/get-fields-for-inserted-row.md new file mode 100644 index 0000000..0f96ba5 --- /dev/null +++ b/drizzle/get-fields-for-inserted-row.md @@ -0,0 +1,56 @@ +# Get Fields For Inserted Row + +With Drizzle, we can insert a row with a set of values like so: + +```typescript +await db + .insert(todoItems) + .values({ + title, + userId, + description, + }) +``` + +The result of this is `QueryResult`. In other words, nothing useful is +coming back to us from the database. + +Sometimes an insert is treated as a fire-and-forget (as long as it succeeds) or +since we know what data we are inserting, we don't need the database to +response. But what about values that are generated or computed by the database +-- such as an id from a sequence, timestamp columns that default to `now()`, or +generated columns. + +To get all the fields of a freshly inserted row, we can tack on [the +`returning()` function](https://orm.drizzle.team/docs/insert#insert-returning) +(which likely adds something like [`returning +*`](https://www.postgresql.org/docs/current/dml-returning.html)) to the insert +query under the hood). + +```typescript +await db + .insert(todoItems) + .values({ + title, + userId, + description, + }) + .returning() +``` + +This will have a return type of `Array` which means that for +each inserted row we'll have all the fields (columns) for that row. + +Alternatively, if we just need the generated ID for the new row(s), we can use +a partial return like so: + +```typescript +await db + .insert(todoItems) + .values({ + title, + userId, + description, + }) + .returning({ id: todoItems.id }) +```