write handles the database writing of tuple and attribute collections for a given tenant. It returns an EncodedSnapToken upon successful write or an error if the write fails.
( ctx context.Context, tenantID string, tupleCollection *database.TupleCollection, attributeCollection *database.AttributeCollection, )
| 165 | // write handles the database writing of tuple and attribute collections for a given tenant. |
| 166 | // It returns an EncodedSnapToken upon successful write or an error if the write fails. |
| 167 | func (w *DataWriter) write( |
| 168 | ctx context.Context, |
| 169 | tenantID string, |
| 170 | tupleCollection *database.TupleCollection, |
| 171 | attributeCollection *database.AttributeCollection, |
| 172 | ) (token token.EncodedSnapToken, err error) { |
| 173 | var tx pgx.Tx |
| 174 | tx, err = w.database.WritePool.BeginTx(ctx, w.txOptions) |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | // Defer rollback |
| 179 | defer func() { |
| 180 | _ = tx.Rollback(ctx) |
| 181 | }() |
| 182 | // Get transaction ID and snapshot |
| 183 | var xid db.XID8 |
| 184 | var snapshotValue string |
| 185 | err = tx.QueryRow(ctx, utils.TransactionTemplate, tenantID).Scan(&xid, &snapshotValue) |
| 186 | if err != nil { |
| 187 | return nil, err |
| 188 | } |
| 189 | |
| 190 | slog.DebugContext(ctx, "retrieved transaction", slog.Any("xid", xid), "for tenant", slog.Any("tenant_id", tenantID)) |
| 191 | |
| 192 | slog.DebugContext(ctx, "processing tuples and executing insert query") |
| 193 | |
| 194 | batch := &pgx.Batch{} |
| 195 | |
| 196 | if len(tupleCollection.GetTuples()) > 0 { |
| 197 | err = w.batchInsertRelationships(batch, xid, tenantID, tupleCollection) |
| 198 | if err != nil { |
| 199 | return nil, err |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | if len(attributeCollection.GetAttributes()) > 0 { |
| 204 | err = w.batchUpdateAttributes(batch, xid, tenantID, buildDeleteClausesForAttributes(attributeCollection)) |
| 205 | if err != nil { |
| 206 | return nil, err |
| 207 | } |
| 208 | err = w.batchInsertAttributes(batch, xid, tenantID, attributeCollection) |
| 209 | if err != nil { |
| 210 | return nil, err |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | batchResult := tx.SendBatch(ctx, batch) |
| 215 | for i := 0; i < batch.Len(); i++ { |
| 216 | _, err = batchResult.Exec() |
| 217 | if err != nil { |
| 218 | err = batchResult.Close() |
| 219 | if err != nil { |
| 220 | return nil, err |
| 221 | } |
| 222 | return nil, err |
| 223 | } |
| 224 | } |
no test coverage detected