docs(flare,kiosk,lagoon): compile README Go examples via src= (quick-261118-qsd)
- flare: send region run by TestDocsNotifyReply against a loopback TLS push service; blogSubscriptions and the publish-source region run by TestDocsSubscriptionSource on a Postgres container (skips under -short) - kiosk: write, newest and client regions run by TestDocsWriteManifest (a copy of the literal fixture), ExampleVersionsResponse and TestDocsBlogReleases (httptest registry); the CheckT fence reuses TestPluginManifest - lagoon: new open region run by TestDocsOpenFromApp (DocsDSN added to export_docs_test.go); the model, create-post, on-database, publish and migrations fences reuse the Database pages' targets
This commit is contained in:
@@ -48,7 +48,7 @@ Use cases:
|
||||
|
||||
Open the shared pool once at boot and publish it, so plugins and handlers reuse the same handles:
|
||||
|
||||
```go
|
||||
```go src=modules/lagoon/example_test.go#open
|
||||
sqlDB, gdb, err := lagoon.OpenFromApp(ctx, app)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -58,68 +58,123 @@ if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||
}
|
||||
```
|
||||
|
||||
A model uses the column types and helpers directly:
|
||||
A model uses the column types directly, and a handler validates and mass-assigns input through the helpers:
|
||||
|
||||
```go
|
||||
```go src=modules/lagoon/example_test.go#Post
|
||||
// Post is the acme.blog post model: a plain GORM struct with lagoon column
|
||||
// types.
|
||||
type Post struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Title string `gorm:"column:title"`
|
||||
Tags lagoon.Jsonable[[]string] `gorm:"column:tags"`
|
||||
APIToken lagoon.Encrypted `gorm:"column:api_token"`
|
||||
}
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
Title string `gorm:"column:title" json:"title"`
|
||||
Slug string `gorm:"column:slug" json:"slug"`
|
||||
Views int `gorm:"column:views" json:"views"`
|
||||
Tags lagoon.Jsonable[[]string] `gorm:"column:tags" json:"-"`
|
||||
APIToken lagoon.Encrypted `gorm:"column:api_token" json:"-"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"-"`
|
||||
|
||||
func (Post) Fillable() []string { return []string{"title"} }
|
||||
|
||||
func createPost(ctx context.Context, gdb *gorm.DB, tr *phrasebook.Translator, input map[string]any) (map[string][]string, error) {
|
||||
var post Post
|
||||
rules := map[string]string{"title": "required|max:255|unique:posts"}
|
||||
if errs, err := lagoon.Validate(ctx, gdb, &post, rules, input, tr); err != nil || errs != nil {
|
||||
return errs, err
|
||||
}
|
||||
if err := lagoon.Fill(&post, post.Fillable(), input, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
post.APIToken = lagoon.NewEncrypted("change-me")
|
||||
return nil, gdb.Create(&post).Error
|
||||
Categories []Category `gorm:"many2many:acme_blog_post_categories" json:"-"`
|
||||
}
|
||||
```
|
||||
|
||||
```go src=modules/lagoon/example_test.go#Post.Fillable
|
||||
// Fillable is the Go form of $fillable: the keys mass assignment may set.
|
||||
func (Post) Fillable() []string { return []string{"title", "views"} }
|
||||
```
|
||||
|
||||
```go src=modules/lagoon/example_test.go#create-post
|
||||
rules := map[string]string{
|
||||
"title": "required|max:255|unique:acme_blog_posts",
|
||||
"views": "nullable|integer|min:0",
|
||||
}
|
||||
var post Post
|
||||
errs, err := lagoon.Validate(ctx, db, &post, rules, input, nil)
|
||||
if err != nil || errs != nil {
|
||||
return nil, errs, err
|
||||
}
|
||||
if err := lagoon.Fill(&post, post.Fillable(), input, false); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(&post).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &post, nil, nil
|
||||
```
|
||||
|
||||
A plugin registers its GORM callbacks from Boot through `lagoon.OnDatabase`, so they are installed whenever the database is published, and defers side effects until the write commits. Register the callback before GORM's `gorm:commit_or_rollback_transaction` step: lagoon runs a single-statement write's after-commit work from `lagoon:after_commit` right after that step, so work buffered by a callback GORM sorts later never runs, and `lagoon.AfterCommit` logs a warning for it (see [Callbacks registered at boot](../../docs/database/transactions.md#callbacks-registered-at-boot)):
|
||||
|
||||
```go
|
||||
func (p *Plugin) Boot(app *backpack.App) error {
|
||||
return lagoon.OnDatabase(app, func(_ *sql.DB, gdb *gorm.DB) error {
|
||||
return gdb.Callback().Create().After("gorm:create").Before("gorm:commit_or_rollback_transaction").Register("acme:post_created", func(db *gorm.DB) {
|
||||
if db.Error != nil {
|
||||
return
|
||||
}
|
||||
lagoon.AfterCommit(db.Statement.Context, db, func(ctx context.Context, db *gorm.DB) {
|
||||
// runs only once the insert is committed
|
||||
})
|
||||
```go src=modules/lagoon/example_test.go#on-database
|
||||
return lagoon.OnDatabase(app, func(_ *sql.DB, gdb *gorm.DB) error {
|
||||
return gdb.Callback().Create().After("gorm:create").Before("gorm:commit_or_rollback_transaction").Register("acme:post_created", func(db *gorm.DB) {
|
||||
post, ok := db.Statement.Dest.(*Post)
|
||||
if db.Error != nil || !ok {
|
||||
return
|
||||
}
|
||||
lagoon.AfterCommit(db.Statement.Context, db, func(ctx context.Context, db *gorm.DB) {
|
||||
*log = append(*log, "created "+post.Slug) // runs only once the insert is committed
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
func publish(ctx context.Context, gdb *gorm.DB, post *Post) error {
|
||||
return lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
return tx.Create(post).Error // acme:post_created work waits for this commit
|
||||
```go src=modules/lagoon/example_test.go#publish
|
||||
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
if err := tx.Model(&Post{}).Where("id = ?", id).Update("title", "Published").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, db *gorm.DB) {
|
||||
*log = append(*log, fmt.Sprintf("post %d published", id)) // broadcast, index, send mail...
|
||||
})
|
||||
}
|
||||
if fail {
|
||||
return errors.New("rolled back") // the AfterCommit work never runs
|
||||
}
|
||||
return nil
|
||||
})
|
||||
```
|
||||
|
||||
A plugin ships its schema as an ordered gormigrate set; `migrate` runs it after the framework sets:
|
||||
|
||||
```go
|
||||
func (p *Plugin) Migrations() []*gormigrate.Migration {
|
||||
return []*gormigrate.Migration{{
|
||||
ID: "202601010001_create_posts",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`CREATE TABLE posts (id SERIAL PRIMARY KEY, title TEXT NOT NULL, tags TEXT, api_token TEXT)`).Error
|
||||
```go src=modules/lagoon/example_test.go#BlogPlugin.Migrations
|
||||
// Migrations returns the plugin's schema as an ordered gormigrate set. In a
|
||||
// scaffolded plugin each migration is a file in updates/ and this list is
|
||||
// generated in file name order.
|
||||
func (p *BlogPlugin) Migrations() []*gormigrate.Migration {
|
||||
return []*gormigrate.Migration{
|
||||
{
|
||||
ID: "20260101000100_create_posts",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`CREATE TABLE acme_blog_posts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
slug TEXT NOT NULL,
|
||||
views INTEGER NOT NULL DEFAULT 0,
|
||||
tags TEXT,
|
||||
api_token TEXT,
|
||||
deleted_at TIMESTAMPTZ
|
||||
)`).Error
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`DROP TABLE IF EXISTS acme_blog_posts`).Error
|
||||
},
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`DROP TABLE IF EXISTS posts`).Error
|
||||
{
|
||||
ID: "20260101000200_create_comments_and_categories",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE acme_blog_comments (id SERIAL PRIMARY KEY, post_id INTEGER NOT NULL, body TEXT NOT NULL, deleted_at TIMESTAMPTZ)`,
|
||||
`CREATE TABLE acme_blog_categories (id SERIAL PRIMARY KEY, name TEXT NOT NULL)`,
|
||||
`CREATE TABLE acme_blog_post_categories (post_id INTEGER NOT NULL, category_id INTEGER NOT NULL, sort_order INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (post_id, category_id))`,
|
||||
} {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`DROP TABLE IF EXISTS acme_blog_post_categories, acme_blog_categories, acme_blog_comments`).Error
|
||||
},
|
||||
},
|
||||
}}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user