|
| 1 | +package sqldb_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/smarty/sqldb/v3" |
| 8 | +) |
| 9 | + |
| 10 | +// Business Event: |
| 11 | +type FooEstablished struct { |
| 12 | + Timestamp time.Time |
| 13 | + FooID uint64 |
| 14 | +} |
| 15 | + |
| 16 | +// Storage Operation: |
| 17 | +type LoadFooName struct { |
| 18 | + FooID uint64 |
| 19 | + Result struct { |
| 20 | + FooID uint64 |
| 21 | + FooName string |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +type Mapper struct { |
| 26 | + db sqldb.DBTx |
| 27 | +} |
| 28 | + |
| 29 | +func (this Mapper) fooEstablished(ctx context.Context, operation FooEstablished) (uint64, error) { |
| 30 | + return sqldb.ExecuteStatements(ctx, this.db, ` |
| 31 | + INSERT |
| 32 | + INTO Foos |
| 33 | + ( foo_id, created, foo_name ) |
| 34 | + VALUES ( ?, ?, '' ) |
| 35 | + ON DUPLICATE KEY |
| 36 | + UPDATE created = created;`, |
| 37 | + operation.FooID, operation.Timestamp, |
| 38 | + ) |
| 39 | +} |
| 40 | +func (this Mapper) fooEstablished_Prepared(ctx context.Context, operation FooEstablished) (uint64, error) { |
| 41 | + statement, err := this.db.PrepareContext(ctx, ` |
| 42 | + INSERT |
| 43 | + INTO Foos |
| 44 | + ( foo_id, created, foo_name ) |
| 45 | + VALUES ( ?, ?, '' ) |
| 46 | + ON DUPLICATE KEY |
| 47 | + UPDATE created = created;`, |
| 48 | + ) |
| 49 | + if err != nil { |
| 50 | + return 0, err |
| 51 | + } |
| 52 | + return sqldb.RowsAffected(statement.ExecContext(ctx, operation.FooID, operation.Timestamp)) |
| 53 | +} |
| 54 | + |
| 55 | +func (this Mapper) loadFooName(ctx context.Context, operation *LoadFooName) error { |
| 56 | + rows, err := this.db.QueryContext(ctx, ` |
| 57 | + SELECT foo_id, foo_name |
| 58 | + FROM Foos |
| 59 | + WHERE foo_id = ?;`, |
| 60 | + operation.FooID, |
| 61 | + ) |
| 62 | + return sqldb.BindAll(rows, err, func(source sqldb.Scanner) error { |
| 63 | + return source.Scan(&operation.Result.FooID, &operation.Result.FooName) |
| 64 | + }) |
| 65 | +} |
| 66 | +func (this Mapper) loadFooName_Prepared(ctx context.Context, operation *LoadFooName) error { |
| 67 | + statement, err := this.db.PrepareContext(ctx, ` |
| 68 | + SELECT foo_id, foo_name |
| 69 | + FROM Foos |
| 70 | + WHERE foo_id = ?;`, |
| 71 | + ) |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + rows, err := statement.QueryContext(ctx, operation.FooID) |
| 76 | + return sqldb.BindAll(rows, err, func(source sqldb.Scanner) error { |
| 77 | + return source.Scan(&operation.Result.FooID, &operation.Result.FooName) |
| 78 | + }) |
| 79 | +} |
0 commit comments