jeremydaly / data-api-client

A "DocumentClient" for the Amazon Aurora Serverless Data API
MIT License
439 stars 61 forks source link

Get insertID of multiple queries of a transaction #60

Open mg98 opened 3 years ago

mg98 commented 3 years ago

Is there a way to retrieve r.InsertID of multiple queries inside a following query? The following code will demonstrate my use case:

db.transaction()
        .query(insertContactSQL, formData.sender)
        .query(insertContactSQL, formData.receiver)
        .query(insertContactSQL, formData.customer)
        .query(insertOrderSQL, {
            senderID: INSERT_ID_OF_FIRST_QUERY,
            receiverID: INSERT_ID_OF_SECOND_QUERY,
            customerID: INSERT_ID_OF_THIRD_QUERY,
        });
marracuene commented 3 years ago

I haven't done this with InsertID, but I have done it using the SQL RETURNING syntax which PostgreSQL offers. Not sure if MySQL does.

For instance if insertContactSQL were something like the below, assuming that my_table has an autogenerated id column,

"INSERT INTO my_table (name, phone_number) VALUES (:name, :phone) RETURNING id"

...then you should be able to do this...

db.transaction()
        .query(insertContactSQL, formData.sender)
        .query(insertContactSQL, formData.receiver)
        .query(insertContactSQL, formData.customer)
        .query((prevResult:any) => 
          {
              return [insertOrderSQL, {
                 senderID: prevResult.records[0].id,
                 receiverID: prevResult.records[1].id,
                 customerID: prevResult.records[2].id,
                 } ];
          });