Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
run: go mod download

- name: Run tests
run: go test -coverprofile=coverage.txt ./pkg/core
run: go test -coverprofile=coverage.txt ./pkg/core ./pkg/util

- name: Upload results to Codecov
uses: codecov/codecov-action@v5
Expand Down
11 changes: 6 additions & 5 deletions docs/content/docs/1-introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ Furthermore, writing basic CRUD operations for every model leads to massive code

## 🧹 Simplifying with Dot Imports
Just like the core Rays framework, it is highly recommended to use Go's dot import feature for the ORM packages:
- `import . "github.com/BeamFoundry/rays-orm/pkg/core"` for core repository types, interfaces, and transaction management (`OrmRepository`, `OrmQueryFunc`, `GormTransactional`).
- `import . "github.com/BeamFoundry/rays-orm/pkg/core"` for core repository types and interfaces (`OrmRepository`, `OrmQueryFunc`, `GormTransactional`).
- `import . "github.com/BeamFoundry/rays-orm/pkg/tx"` for the default `GormTransactionalManager` implementation.
- `import . "github.com/BeamFoundry/rays-orm/pkg/util"` for ready-to-use query helpers (`Paginate`, `WithLimit`, `WithOffset`, `WithPreload`, `WithJoins`, `OrderByAsc`, etc.).
- `import . "github.com/BeamFoundry/rays/pkg/util/stream"` for lazy, Java 8-style stream operations on query results (`Stream[T]`).

Expand All @@ -24,10 +25,10 @@ This allows you to use types, query helpers, and stream primitives directly with
1. **Auto-Generated Repository Methods:** By simply defining a function signature like `findByName func(string) *User`,
`listActiveUsersByStatus func(string) []User`, or `streamAllByStatusOrderByCreatedAtDesc func(string) Stream[User]` on your repository struct,
Rays ORM will automatically generate the underlying GORM query logic and bind it to that field during the container's wiring phase.
2. **ThreadLocal Transactions:** Using `github.com/timandy/routine`, Rays ORM implements true ThreadLocal storage for Go.
When a Service starts a transaction, the `*gorm.DB` transaction object is bound to the current goroutine.
Downstream repositories transparently inherit this transaction without requiring you to pass it via function arguments.
3. **IoC Managed DB:** You define a standard `*gorm.DB` Beam, and the framework's `GormTransactional` handles the rest.
2. **ThreadLocal Transactions:** Using `github.com/timandy/routine` and Rays' central `TransactionManager`, Rays ORM implements true ThreadLocal storage for Go.
When a Service starts a transaction via `TransactionManager`, the `*gorm.DB` transaction object is lazily enlisted and bound to the current goroutine.
Downstream repositories transparently inherit this transaction and propagate errors back to `TransactionManager` without requiring you to pass `*gorm.DB` or `context.Context` via function arguments.
3. **IoC Managed DB:** You define a standard `*gorm.DB` Beam, and the framework's `GormTransactional` and `TransactionManager` handle the rest.
4. **Secure by Default (SQL Injection Prevention):** The auto-generated query builder does not concatenate raw strings.
It automatically translates your method names into **parameterized queries** using `?` placeholders, ensuring that all database
interactions are natively protected against SQL injection attacks without requiring manual sanitization.
246 changes: 206 additions & 40 deletions docs/content/docs/4-transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,48 @@ weight: 4

# ThreadLocal Transactions

A common pain point in Go is passing database transaction objects (`*gorm.DB`) explicitly as arguments to
every repository function.
A common pain point in Go is passing `context.Context` and database transaction objects (`*gorm.DB`) explicitly as arguments to every service and repository function.

Rays ORM utilizes `github.com/timandy/routine` to establish **ThreadLocal** state for your goroutines.
When you start a transaction via the `GormTransactional`, the transaction is stored in the local thread context.
Rays and Rays ORM utilize `github.com/timandy/routine` to establish **ThreadLocal** state for your goroutines:

When your auto-generated repositories execute queries, they transparently check the ThreadLocal context.
If a transaction exists, they use it. If not, they use the global `*gorm.DB`.
- **Services** inject the core `TransactionManager` (`github.com/BeamFoundry/rays/pkg/core`) to start, commit, or roll back transactions—and optionally bind a goroutine-local `context.Context`.
- **Repositories** (`OrmRepository`) inject `GormTransactional` (`GormTransactionalManager` from `github.com/BeamFoundry/rays-orm/pkg/tx`), which is registered as a **Prototype** Beam by default.
- **Lazy Enlistment & Error Propagation**: When a repository executes a query while a transaction is active on `TransactionManager`, `GormTransactional` lazily enlists itself in the current goroutine's transaction and opens a `*gorm.DB` transaction using `TransactionManager.GetContext()`. Any database error encountered by a repository is reported back to `GormTransactional.SetError(err)` and forwarded to `TransactionManager`, which immediately rolls back the active transaction (as well as any other participating `Transactional[T]` providers on that goroutine).

## Using the `GormTransactional` Closure
---

## Using the `TransactionManager` Closure

Inject the `GormTransactional` into your business logic services to orchestrate complex database operations safely.
The `Transactional` closure accepts a `context.Context` (which is passed to GORM's `WithContext`) and manages commits
and rollbacks automatically based on the returned error.
Inject `TransactionManager` into your business logic services to orchestrate database operations safely. The `Transactional` closure manages `Start()`, `Commit()`, `Rollback()`, panic recovery, and `End()` automatically:

```go
package services

import (
"context"
"gorm.io/gorm"
. "github.com/BeamFoundry/rays-orm/pkg/core"
. "github.com/BeamFoundry/rays/pkg/core"
. "github.com/BeamFoundry/rays/pkg/lang"
)

type UserService struct {
Service

txManager GormTransactional `@:"Inject"`
userRepo *UserRepository `@:"Inject"`
auditRepo *AuditRepository`@:"Inject"`
txManager TransactionManager `@:"Inject"`
userRepo *UserRepository `@:"Inject"`
auditRepo *AuditRepository `@:"Inject"`
}

func (s *UserService) CreateUserWithAudit(ctx context.Context, name string) Error {

// Execute a block of code within a ThreadLocal transaction
return s.txManager.Transactional(ctx, func(_ *gorm.DB) Error {

func (s *UserService) CreateUserWithAudit(name string) Error {
// Execute a block of code within a coordinated ThreadLocal transaction
return s.txManager.Transactional(func() Error {
newUser := &User{Name: name}

// 1. This save natively participates in the active transaction
// 1. Lazily enlists GormTransactional and participates in the active transaction
_, err := s.userRepo.Save(newUser)
if err != nil {
return err // Triggers rollback
}

// 2. This custom query also participates in the transaction
// 2. Reuses the active ThreadLocal *gorm.DB transaction
auditLog := &Audit{Action: "USER_CREATED", TargetID: newUser.ID}
_, err = s.auditRepo.Save(auditLog)
if err != nil {
Expand All @@ -64,51 +58,223 @@ func (s *UserService) CreateUserWithAudit(ctx context.Context, name string) Erro
}
```

### Binding a `context.Context`

If you need to attach a request context, timeout, or cancellation signal to the current goroutine's queries and transactions, call `SetContext(ctx)` and `defer ClearContext()` on `TransactionManager`:

```go
func (s *UserService) CreateUserWithContext(ctx context.Context, name string) Error {
s.txManager.SetContext(ctx)
defer s.txManager.ClearContext()

return s.txManager.Transactional(func() Error {
_, err := s.userRepo.Save(&User{Name: name})
return err
})
}
```

---

## Manual Transaction Management

If you prefer or require granular control over the transaction lifecycle, you can manually start, commit,
and rollback transactions.
If you require granular imperative control over the transaction lifecycle, you can manually call `Start()`, `Commit()`, `Rollback()`, and `End()` on `TransactionManager`.

When using this approach, you **must** call `defer this.transactionManager.End()` immediately after starting
the transaction to ensure the ThreadLocal state is properly cleaned up, even in the event of a panic.
When using this approach, always call `defer this.transactionManager.End()` immediately after `Start()` to ensure the ThreadLocal state is cleaned up (and automatically rolled back if `Commit()` was not reached):

```go
package services

import (
"context"
"errors"
. "github.com/BeamFoundry/rays-orm/pkg/core"

. "github.com/BeamFoundry/rays/pkg/core"
)

type UserServiceImpl struct {
Service
transactionManager GormTransactional `@:"Inject"`
userRepository *UserRepository `@:"Inject"`
transactionManager TransactionManager `@:"Inject"`
userRepository *UserRepository `@:"Inject"`
}

func (this *UserServiceImpl) AddUser(ctx context.Context, username string) (*User, error) {
// Start the transaction and bind it to the current thread
tx := this.transactionManager.Start(ctx)
func (this *UserServiceImpl) AddUser(username string) (*User, error) {
// Start the transaction on the current goroutine
if err := this.transactionManager.Start(); err != nil {
return nil, err
}

// ALWAYS defer End() to clean up the ThreadLocal storage
// ALWAYS defer End() to clean up ThreadLocal storage
defer this.transactionManager.End()

if _, ok := this.userRepository.FindByUsername(username).Get(); ok {
tx.Rollback()
return nil, errors.New("User already exists")
_ = this.transactionManager.Rollback()
return nil, errors.New("user already exists")
}

user := &User{ Name: username }
user := &User{Name: username}

u, err := this.userRepository.Save(user)
if err != nil {
tx.Rollback()
_ = this.transactionManager.Rollback()
return nil, err
}

tx.Commit()
if err := this.transactionManager.Commit(); err != nil {
return nil, err
}
return u, nil
}
```

---

## Multi-Database Routing: Type Splitting & Context Splitting

Because `GormTransactional` is a **Prototype** Beam and `GormTransactionalManager` tracks active goroutine transactions per `*gorm.DB` driver instance:

- Repositories that resolve to the **same** `*gorm.DB` driver on a goroutine automatically share the same active SQL transaction.
- Repositories that resolve to **different** `*gorm.DB` drivers on a goroutine each enlist their own `*gorm.DB` transaction in `TransactionManager`, providing **best-effort** multi-database commit and rollback coordination (rather than an atomic distributed transaction).

When a Prototype `GormTransactional` injects a Prototype `*gorm.DB` (a `Configuration` method accepting `ctx context.Context`), Rays automatically populates `ctx` with:
- `PrototypeContextProxyType`: The `reflect.Type` of the repository (e.g. `*UserRepository`).
- `PrototypeContextProxyInstance`: The repository instance (which implements `OrmEntityTypeProvider` via `OrmRepository[T, ID]`).
- All runtime context values set on `TransactionManager.SetContext(ctx)`.

Rays ORM provides two helper functions in `github.com/BeamFoundry/rays-orm/pkg/core` to inspect the target repository or entity from `ctx`:

| Helper Function | Return Value | Description |
| :--- | :--- | :--- |
| `OrmEntityTypeFromContext(ctx)` | `reflect.Type` | Returns the `reflect.Type` of entity `T` (e.g. `reflect.TypeFor[Animal]()`). |
| `OrmRepositoryTypeFromContext(ctx)` | `reflect.Type` | Returns the `reflect.Type` of the repository pointer (e.g. `reflect.TypeFor[*AnimalRepository]()`). |

---

### 1. Type Splitting (by Entity Type `T` or Repository Type)

To route different entities or repositories to separate `*gorm.DB` connections without modifying your repository structs, define a Prototype `DB(ctx context.Context) *gorm.DB` method in a `Configuration` Beam:

```go
package config

import (
"context"
"reflect"

"gorm.io/gorm"

. "github.com/BeamFoundry/rays-orm/pkg/core"
. "github.com/BeamFoundry/rays/pkg/core"
)

type MultiDBConfig struct {
Configuration
primaryDB *gorm.DB
auditDB *gorm.DB
}

// Accepting context.Context makes *gorm.DB a Prototype Beam evaluated per repository
func (this *MultiDBConfig) DB(ctx context.Context) *gorm.DB {
// Option A: Route by OrmRepository Entity Type T
if OrmEntityTypeFromContext(ctx) == reflect.TypeFor[AuditLog]() {
return this.auditDB
}

// Option B: Route by Repository Type, Name, or Package Path
if repoType := OrmRepositoryTypeFromContext(ctx); repoType != nil {
if repoType == reflect.TypeFor[*AuditRepository]() {
return this.auditDB
}
}

return this.primaryDB
}
```

When a service runs `this.txManager.Transactional(...)` and calls both `userRepo` (`primaryDB`) and `auditRepo` (`auditDB`), both databases lazily enlist in `TransactionManager` for **best-effort** coordination: if an error occurs before commit, all enlisted databases are rolled back together; at completion, each enlisted database is committed sequentially.

> **Important:** Multi-database coordination is **not** an atomic two-phase commit (2PC). If one database commits and a subsequent database's commit fails, the already-committed changes remain durable while the failing and remaining uncommitted databases are rolled back. Application-level recovery or compensation is required to handle partial commit failures.

---

### 2. Context Splitting (Multi-Tenancy & Dynamic Routing)

When a Controller or Middleware binds runtime parameters (such as a tenant ID or shard key) to `TransactionManager.SetContext(ctx)`, a repository can dynamically resolve its `GormTransactional` from the active `context.Context` by:

1. Injecting `Foundry[GormTransactional]` into the repository struct.
2. Implementing the `GormTransactionalResolver` interface (`GormTransactional(ctx context.Context) GormTransactional`).

`OrmRepository` automatically invokes `GormTransactional(ctx)` with `TransactionManager.GetContext()` and caches the resolved `GormTransactional` for that context on the current goroutine:

```go
package repositories

import (
"context"

"gorm.io/gorm"

. "github.com/BeamFoundry/rays-orm/pkg/core"
. "github.com/BeamFoundry/rays/pkg/core"
. "github.com/BeamFoundry/rays/pkg/lang"
)

type TenantKeyType string

const TenantKey TenantKeyType = "tenant"

// 1. Repository implements GormTransactionalResolver using an injected Foundry
type UserRepository struct {
OrmRepository[User, uint]
foundry Foundry[GormTransactional] `@:"Inject"`
findByName func(string) *User
}

var _ GormTransactionalResolver = &UserRepository{}

func (this *UserRepository) GormTransactional(ctx context.Context) GormTransactional {
if ctx.Value(TenantKey) == nil {
return nil // Intentional default route: falls back to the default injected GormTransactional
}
// Stop the operation and propagate any Forge routing failure rather than falling back to defaultDB
return RaiseVal(this.foundry.Forge(ctx))
}

func (this *UserRepository) FindByName(name string) *User {
return this.findByName(name)
}

// 2. Configuration selects the *gorm.DB based on the runtime context.Context
type TenantDBConfig struct {
Configuration
defaultDB *gorm.DB
tenantADB *gorm.DB
tenantBDB *gorm.DB
}

func (this *TenantDBConfig) DB(ctx context.Context) (*gorm.DB, Error) {
switch ctx.Value(TenantKey) {
case nil:
return this.defaultDB, nil
case "tenant-a":
return this.tenantADB, nil
case "tenant-b":
return this.tenantBDB, nil
default:
return nil, NewError("UnknownTenantError", "unrecognized tenant in context")
}
}
```

In your Controller or Service, simply bind the tenant context to `TransactionManager`:

```go
ctx := context.WithValue(req.Context(), TenantKey, "tenant-a")
this.txManager.SetContext(ctx)
defer this.txManager.ClearContext()

err := this.txManager.Transactional(func() Error {
// Automatically forged and executed against tenantADB
_, err := this.userRepo.Save(&User{Name: "Alice"})
return err
})
```
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/BeamFoundry/rays-orm
go 1.27

require (
github.com/BeamFoundry/rays v0.4.0
github.com/BeamFoundry/rays v0.5.0-rc1
github.com/onsi/ginkgo/v2 v2.34.0
github.com/onsi/gomega v1.44.0
github.com/orandin/slog-gorm v1.4.0
Expand All @@ -27,9 +27,9 @@ require (
github.com/leodido/go-urn v1.5.0 // indirect
github.com/mattn/go-sqlite3 v1.14.24 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/crypto v0.59.0 // indirect
golang.org/x/mod v0.42.0 // indirect
golang.org/x/net v0.61.0 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/term v0.48.0 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ github.com/BeamFoundry/rays v0.3.0 h1:cNAkHcIRfBbHEj9ZhJl0VOw5cft8jdA+y8R5h1/qGU
github.com/BeamFoundry/rays v0.3.0/go.mod h1:5wiQwphroNUY4tWjLrKjoV4B/pHb4ldh8XUFSFnzvQo=
github.com/BeamFoundry/rays v0.4.0 h1:7YGO8TMw6jJU1ssIlQd4Nk8QNRQ0WoJSJs0DvZ8IThc=
github.com/BeamFoundry/rays v0.4.0/go.mod h1:t7DZl4+V9yYsWRFHeWlgGDdvMafJjIWHBN0rhkwDnhI=
github.com/BeamFoundry/rays v0.5.0-rc1 h1:fkdbDFPcJBJ9h4+otX5NRbYmsM99ZejkTgEjskLQpFo=
github.com/BeamFoundry/rays v0.5.0-rc1/go.mod h1:TVthNFJp7AcpbfVqyZ1yELaf///Dy3HVrz2l9nHyctU=
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand Down Expand Up @@ -83,10 +85,14 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
Expand Down
Loading
Loading