Tenant-safe ordered lists in Laravel Go
Why this recipe and where it comes from
At the time of writing, the Package Port catalog listed spatie/eloquent-sortable as needing a Go port. A catalog listing is not proof no implementation exists; check get-recipe's current port catalog before recommending a rewrite. This recipe addresses a bounded missing behavior: app-owned append, ordered reads, and atomic full-list reorder.
Read Spatie's MIT-licensed 5.0.1 source at caf2596e5df0260d0e2863e89b750611eef2fc59, especially src/SortableTrait.php, configuration, event, interface, and tests. Retain MIT notices for adapted source. Target baseline: Laravel Go 56c7fd3691dc4ccb636119308d6fcf919e308518, module go.laravel.com. This guidance has not been run in your app; verify it with the trial checklist below.
Source behavior and selected contract
The trait optionally assigns max(order_column) + 1 on creation, orders by the configured column, and assigns consecutive ranks in supplied ID order. setNewOrder() drops the soft-delete global scope for those updates, can suppress timestamp changes, and dispatches a sorted event. Its loop is not a complete transactional, tenant-authorized reorder endpoint.
Inventory the app's actual list scope, primary key, order column, deleted-row handling, relative move/swap calls, and event listeners. Declare a full-list contract: inputs are exactly a permutation of the authorized current members. Exclude partial reorders/cross-list moves unless separately designed. Preserve only the used behavior; document deliberate strengthening of isolation and authorization.
Go implementation
- Keep the existing position data. Read with
OrderBy("position").OrderBy("id")on an authorized list-scoped query, using fixed identifiers. Index list membership plus position as appropriate; do not migrate production schema just to follow this prose. - Put all membership/order mutations behind the same list action. Begin with
db.Transaction(requestContext, func(ctx context.Context) error { ... }). At the pinned revision,db/tx.gobinds the transaction to the callback'sctx. Every query and write inside must use thatctx, not the original request context orcontext.Background(). - Inside the callback, lock the tenant-authorized parent row with
LockForUpdate()before reading children. It serializes even an empty list on PostgreSQL/MySQL. Recheck mutable authorization after locking. Append, delete, restore, transfer, and reorder must all use the same lock protocol. SQLite needs an explicit compatible write-serialization strategy and separate tests. - Bound payload length and validate distinct positive IDs. Read membership under the parent lock, then compare sets and cardinalities. Reject foreign tenant/list IDs, duplicates, omitted members, and unknown/deleted IDs under the chosen deletion policy before writing any rank.
- Assign one-based ranks in input order, with both ID and parent predicates on every update; check affected rows. An immediate unique
(list_id, position)index can make swaps fail: stage all involved ranks into a checked disjoint range first, or use an explicitly reviewed deferrable design. Check integer overflow and existing constraints; do not drop uniqueness to hide an error. - For append, calculate max plus one under the same lock. Preserve timestamp policy explicitly. Return any error from the callback so it rolls back. Do not start goroutines that outlive the transaction; notify listeners only after commit.
Transaction shape only—the application-specific membership checks and writes belong inside this callback:
err := db.Transaction(r, func(ctx context.Context) error {
// Lock the authorized parent using ctx.
// Read and validate the complete member set using ctx.
// Stage unique ranks if needed; write the new order using ctx.
return nil
})
r must be the app's request/job context, not a bare background context lacking a connection. Import context and go.laravel.com/db. The sketch is not a runnable reorder implementation by itself.
Trial checklist
Seed list A [11, 24, 39] and list B [50]. Reorder A to [39, 11, 24]; assert exact ranks and output IDs, B unchanged.
- Duplicate, omitted, foreign-list/tenant, and oversized inputs leave the database and event stream unchanged.
- Inject failure after the first update. A fresh-connection read must see the original order, catching use of the wrong transaction context.
- Run independent-connection concurrent reorders and append-versus-reorder; accept only complete serial outcomes.
go test -racealone does not test database isolation. - Cover empty-list append, soft-delete/restore rules, legacy tied ranks, immediate unique-index swaps, overflow boundaries, and post-commit events.
Run gofmt, go vet ./..., go test ./..., go test -race ./..., and the production-driver concurrency integration tests. Record Go/framework versions, transaction-context usage, and decisive test output with the change.