RecordTransaction records a new transaction in the database. It logs the transaction details using OpenTelemetry tracing. Parameters: - ctx: Context for managing the request and tracing. - txn: The transaction object containing details to be recorded. Returns: - The recorded transaction if successfu
(ctx context.Context, txn *model.Transaction)
| 47 | // Returns: |
| 48 | // - The recorded transaction if successful, or an error if the recording fails. |
| 49 | func (d Datasource) RecordTransaction(ctx context.Context, txn *model.Transaction) (*model.Transaction, error) { |
| 50 | // Start a new tracing span for the database operation |
| 51 | ctx, span := otel.Tracer("transaction.database").Start(ctx, "RecordTransaction") |
| 52 | defer span.End() |
| 53 | |
| 54 | // Marshal transaction metadata into JSON format |
| 55 | metaDataJSON, err := json.Marshal(txn.MetaData) |
| 56 | if err != nil { |
| 57 | span.RecordError(err) // Record the error in the tracing span |
| 58 | return nil, apierror.NewAPIError(apierror.ErrInternalServer, "Failed to marshal metadata", err) |
| 59 | } |
| 60 | |
| 61 | // Execute the SQL insert statement to record the transaction |
| 62 | _, err = d.Conn.ExecContext(ctx, |
| 63 | `INSERT INTO ledgerforge.transactions(transaction_id, parent_transaction, source, reference, amount, precise_amount, precision, rate, currency, destination, description, status, created_at, meta_data, scheduled_for, hash, effective_date) |
| 64 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)`, |
| 65 | txn.TransactionID, txn.ParentTransaction, txn.Source, txn.Reference, txn.AmountString, txn.PreciseAmount.String(), txn.Precision, txn.Rate, txn.Currency, txn.Destination, txn.Description, txn.Status, txn.CreatedAt, metaDataJSON, txn.ScheduledFor, txn.Hash, txn.EffectiveDate, |
| 66 | ) |
| 67 | // Handle errors that may occur during the execution of the query |
| 68 | if err != nil { |
| 69 | span.RecordError(err) |
| 70 | return nil, apierror.NewAPIError(apierror.ErrInternalServer, "Failed to record transaction", err) |
| 71 | } |
| 72 | |
| 73 | // Log the successful transaction recording as an event in the tracing span |
| 74 | span.AddEvent("Transaction recorded", trace.WithAttributes( |
| 75 | attribute.String("transaction.id", txn.TransactionID), |
| 76 | attribute.String("transaction.reference", txn.Reference), |
| 77 | )) |
| 78 | |
| 79 | return txn, nil |
| 80 | } |
| 81 | |
| 82 | // recordTransactionInTx inserts a transaction record within an existing database transaction. |
| 83 | // This is a helper function used by RecordTransactionWithBalances for atomic operations. |