## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# template/db

> Package db keeps templates in a table of a PostgreSQL, MySQL or SQLite database, reached through a gas.DatabaseProvider such as gas/database's Service, with the table created by migrations that a gas.MigrationManager, such as gas/migrate's Service, applies.

The Markdown of https://gasmod.dev/reference/template/db/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
import "github.com/gasmod/gas/template/db"
```

Package db keeps templates in a table of a PostgreSQL, MySQL or SQLite
database, reached through a gas.DatabaseProvider such as gas/database's
Service, with the table created by migrations that a
gas.MigrationManager, such as gas/migrate's Service, applies.

[Store](#Store) implements gas.TemplateProvider with the contract of the
template package, and gas.Service. It is the store for templates edited
while the app runs, by trusted administrators only, as the template
package's Security section describes.

## Usage

In an app, register the constructor. It takes the database, the logger
and the migration manager from the container:

```go
gas.WithSingletonService[gas.TemplateProvider](db.NewStore(db.WithNamespace("emails")))
```

By hand:

```go
store, err := db.NewStore()(database, logger, migrations)
if err != nil {
	return err
}
if err := store.Init(ctx); err != nil {
	return err
}
defer store.Close(ctx)
if err := migrations.RunPendingContext(ctx); err != nil {
	return err
}

err = store.Register(ctx, "welcome.html", []byte("<p>Hi {{.Name}}</p>"))
```

After this the table `__gas_templates` exists and holds one row,
namespace `default`, name `welcome.html`.

## Table

Every Store keeps its templates in [TableName](#TableName), `__gas_templates`, one
row per template:

- `namespace`, `name` and `content`, unique on namespace and name;
- `id`, `created_at` and `updated_at`, which the store writes but
never reads.

A Store reads and writes only the rows of its namespace,
[DefaultNamespace](#DefaultNamespace) unless [WithNamespace](#WithNamespace) gives another. So several
stores share the table, each with its own set of templates.

A namespace is valid UTF-8 without a NUL byte, of 1 to 255 characters.
For any other, the constructor returns an error wrapping
[ErrInvalidNamespace](#ErrInvalidNamespace), which gives the reason and never the namespace.

A name is at most 255 characters too, on every dialect. A longer one is
refused with template.ErrInvalidName before any statement runs. MySQL's
columns hold no more, and on PostgreSQL a row of the unique index on
namespace and name must fit in 2704 bytes, which 255 characters of four
bytes each, of both, do.

## Statements

Each method runs these statements:

- Get selects the row of the name, with its content only when that is
within the store's maximum size, [WithMaxSize](#WithMaxSize). So a larger row is
template.ErrTooLarge without the database sending it.
- List selects the names of the namespace. It sorts them in Go, in
byte order, whatever the database's collation. It leaves out a row
whose name the store would refuse, such as one another store of the
namespace wrote with other extensions.
- Register inserts the row or replaces its content, in one statement.
- RegisterFS does the same for each file in one transaction, which a
failure rolls back, so it registers all or none.
- [Store.Exists](#Store.Exists) reports whether a row is there.
- [Store.Delete](#Store.Delete) deletes the row, or returns an error wrapping
template.ErrTemplateNotFound when there is none.

## Dialects

Init picks the SQL from the provider's Driver: `postgres`, `mysql` or
`sqlite`, the names gas/database reports. Any other is
[ErrUnsupportedDriver](#ErrUnsupportedDriver), which lists the supported names and not the one
given. So is gas/database before its own Init, which reports an empty
driver.

MySQL must be 8.0.19 or later, for the `AS new` alias the upsert uses
and the utf8mb4\_0900\_bin collation. MariaDB has neither and is not
supported.

Names are exact on every dialect:

- PostgreSQL: TEXT names and BYTEA content, compared byte for byte.
- SQLite: TEXT names and BLOB content, compared byte for byte by the
BINARY collation.
- MySQL: `namespace` and `name` are VARCHAR(255) of utf8mb4 with the
utf8mb4\_0900\_bin collation, which compares code points and pads
nothing. So `Home.html` and `home.html`, and `café.html` and
`cafe.html`, are different names. Content is LONGBLOB, which holds
any bytes as given, without MEDIUMBLOB's 16 MiB cap. A single
Register is limited by the server's max\_allowed\_packet, 64 MiB by
default on MySQL 8.4.

Content is otherwise limited only by the store's maximum size, 16 MiB
by default, and the largest value the database stores.

## Migrations

Init registers two migrations with the migration manager, owned by the
store under [ServiceName](#ServiceName). They are the same for every dialect, but each
in its own SQL. Every store registers the same two, so several stores on
one manager register them once.

The manager applies them when it runs. Until then Register and the
other methods fail with [ErrQuery](#ErrQuery) and the driver's code for a missing
table. Seed templates once the migrations ran, such as in a ready
function of the app.

The two migrations:

- `20260322235959`, `create templates table`: creates the table, with
an index on `namespace`. On MySQL it creates `name` and `namespace`
with the database's default collation and `content` as MEDIUMBLOB.
Its SQL is unchanged from earlier releases, so that a database where
it was applied keeps its row.
- `20261031120000`, `exact template names`: drops the index on
`namespace`, which the unique key on namespace and name already
serves, on every dialect. On MySQL it also changes `namespace` and
`name` to the utf8mb4\_0900\_bin collation and `content` to LONGBLOB,
in one ALTER TABLE that keeps every row, as under MySQL migrations.

## MySQL migrations

A table of an earlier release cannot hold two names that the new
collation tells apart and the old one did not, so the unique key holds
through the change to utf8mb4\_0900\_bin.

On MySQL both directions of `20261031120000` first add
STRICT\_ALL\_TABLES to the session's sql\_mode, whatever the server's
sql\_mode. So a value that does not fit fails the ALTER TABLE, which then
changes nothing, instead of being cut short or replaced by `?` with a
warning. gas/migrate runs a migration on a connection of its own and
closes it after, so the setting ends with it.

Reverting `20261031120000` restores the index, and on MySQL the
database's default collation and MEDIUMBLOB. On MySQL the revert fails,
and leaves the migration dirty, when:

- two names of a namespace differ only in case or accents, which the
default collation takes as one;
- a name or namespace holds a character the database's default
character set cannot, such as `日本.html` in a latin1 database;
- a template's content is over 16 MiB, which MEDIUMBLOB cannot hold.

The table is then left as it was. Delete such rows before reverting.

## Lifecycle

[NewStore](#NewStore)'s constructor checks its dependencies and options, and
touches no database.

Init picks the dialect, takes the provider's DB, and registers the
migrations; it runs no statement. It returns [ErrNilDatabase](#ErrNilDatabase) when the
provider's DB is nil, and changes nothing on failure. Init logs `store
initialized` at info level, with `dialect` and `namespace`.

Close makes the store closed and closes nothing, since the database is
the provider's. Init may run again after it, and takes the provider's
DB afresh, so restarting the database means restarting the store too.

Out of the usual order:

- Before the first successful Init, every method but Init and Close
returns template.ErrNotInitialized.
- After Close, until Init runs again, they return template.ErrClosed.
- Init on an open store returns template.ErrAlreadyInitialized.

## Several stores

The gas container builds one service per registered type. So a second
Store, in another namespace, needs a type of its own, such as one
registered as gas.TemplateProvider and the other as \*db.Store.

The gas worker tracks services by instance and closes both at shutdown.
But every Store is named ServiceName, and no option gives it another
name, so its CloseService and RestartService refuse either with
gas.ErrDuplicateServiceName.

## Concurrency

A Store is safe for concurrent use. A read-write lock guards its state.
It is held for reading only while a method takes the handle, never
while a statement runs.

Statements run on the provider's \*sql.DB pool. Two Registers of one
name at once leave one of the two contents.

## Errors

The sentinels this package adds, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrNilDatabase](#ErrNilDatabase), [ErrNilLogger](#ErrNilLogger), [ErrNilMigrations](#ErrNilMigrations): the
constructor was given a nil dependency, or Init got a nil DB.
- [ErrInvalidNamespace](#ErrInvalidNamespace): WithNamespace was given a namespace the store
refuses.
- [ErrUnsupportedDriver](#ErrUnsupportedDriver): the provider reports a driver the store has
no SQL for.
- [ErrQuery](#ErrQuery): a statement failed. It never wraps the driver's error.

The methods return errors wrapping the template package's sentinels
too:

- ErrInvalidName, ErrTemplateNotFound, ErrTooLarge;
- ErrInvalidExtension, ErrInvalidMaxSize;
- ErrNilFS, ErrRead and the context's error, from RegisterFS;
- ErrNotInitialized, ErrAlreadyInitialized and ErrClosed.

A driver's error text can hold the database's user, the client's
address and the database's name, as MySQL's 1142, `SELECT command
denied to user`, and 1146, `Table 'app.__gas_templates' doesn't
exist`, do. So an ErrQuery error names the operation and the template,
and then gives no driver text:

- When the provider has a method `SafeError(error) error`, as
gas/database's Service has, the driver's error passes through it
first, and a connection-level failure, which it replaces with its
own fixed text, keeps that text and what it wraps, such as
gas/database's ErrConnect.
- A context that ended, or database/sql's ErrConnDone or ErrTxDone,
is kept, wrapped.
- Any other error gives only its code: `mysql error` and MySQL's
error number, `postgres error` and PostgreSQL's SQLSTATE, `sqlite
error` and SQLite's result code, or `driver error` for an error of
another driver. The code is enough to look the failure up, and the
database's own log holds the rest.

The errors of this package, as returned, with SQLite's codes:

```go
template: database is nil
template: logger is nil
template: migration manager is nil
template: invalid namespace: empty
template: invalid namespace: not valid UTF-8
template: invalid namespace: holds a NUL byte
template: invalid namespace: longer than 255 characters
template: unsupported driver: supported are postgres, mysql and sqlite
template: invalid name: longer than 255 characters
template: query failed: get "welcome.html": sqlite error 1
template: query failed: get "welcome.html": context canceled
template: query failed: list: sqlite error 1
template: query failed: register "welcome.html": sqlite error 1
template: query failed: exists "welcome.html": sqlite error 1
template: query failed: delete "welcome.html": sqlite error 1
```


## API reference

### Constants

<a id="DefaultNamespace"></a>

```go
const DefaultNamespace = "default"
```

DefaultNamespace is the namespace of a store not given another.

<a id="ServiceName"></a>

```go
const ServiceName = "gas/template/db"
```

ServiceName is the name of the store, returned by Store.Name and
recorded as the owner of its migrations.

<a id="TableName"></a>

```go
const TableName = "__gas_templates"
```

TableName is the table the templates are kept in, as described in the
package documentation.

### Variables

<a id="ErrNilDatabase"></a><a id="ErrNilLogger"></a><a id="ErrNilMigrations"></a><a id="ErrInvalidNamespace"></a><a id="ErrUnsupportedDriver"></a><a id="ErrQuery"></a>

```go
var (
	// ErrNilDatabase indicates that the constructor was given a nil
	// gas.DatabaseProvider, or that its DB returned nil in Init.
	ErrNilDatabase = errors.New(template.ErrorPrefix + "database is nil")
	// ErrNilLogger indicates that the constructor was given a nil logger.
	ErrNilLogger = errors.New(template.ErrorPrefix + "logger is nil")
	// ErrNilMigrations indicates that the constructor was given a nil
	// gas.MigrationManager.
	ErrNilMigrations = errors.New(template.ErrorPrefix + "migration manager is nil")
	// ErrInvalidNamespace indicates that WithNamespace was given a
	// namespace the store does not accept.
	ErrInvalidNamespace = errors.New(template.ErrorPrefix + "invalid namespace")
	// ErrUnsupportedDriver indicates that the database reports a driver
	// the store has no SQL for.
	ErrUnsupportedDriver = errors.New(template.ErrorPrefix + "unsupported driver")
	// ErrQuery indicates that a statement on the table failed. It never
	// wraps the driver's error, as described in the package
	// documentation.
	ErrQuery = errors.New(template.ErrorPrefix + "query failed")
)
```

<a id="NewStore"></a>

#### func NewStore

```go
func NewStore(
	opts ...Option,
) func(gas.DatabaseProvider, gas.Logger, gas.MigrationManager) (*Store, error)
```

NewStore returns the constructor of a Store with opts applied, in the
shape the gas container expects. The constructor returns ErrNilDatabase,
ErrNilLogger or ErrNilMigrations for a nil dependency, and an error
wrapping ErrInvalidNamespace, template.ErrInvalidExtension or
template.ErrInvalidMaxSize for a bad option.

<a id="Option"></a>

### type Option

```go
type Option func(*Store)
```

Option configures a Store.

<a id="WithExtensions"></a>

#### func WithExtensions

```go
func WithExtensions(exts ...string) Option
```

WithExtensions sets the extensions a template name must end in. The
constructor checks them, as described in the template package
documentation.

Default: template.DefaultExtension.

<a id="WithMaxSize"></a>

#### func WithMaxSize

```go
func WithMaxSize(n int64) Option
```

WithMaxSize sets the most bytes a template may hold. The constructor
checks it with template.CheckMaxSize.

Default: template.DefaultMaxSize.

<a id="WithNamespace"></a>

#### func WithNamespace

```go
func WithNamespace(namespace string) Option
```

WithNamespace sets the namespace the store's rows are scoped to. The
constructor checks it, as described in the package documentation.

Default: DefaultNamespace.

<a id="Store"></a>

### type Store

```go
type Store struct {
	// contains filtered or unexported fields
}
```

Store keeps templates in a table of a database, as described in the
package documentation. It implements gas.Service and is safe for
concurrent use.

<a id="Store.Close"></a>

#### func (*Store) Close

```go
func (s *Store) Close(context.Context) error
```

Close makes every later call but Init return an error wrapping
template.ErrClosed. It closes nothing: the database belongs to its
provider. Close on a store that is not open returns nil.

<a id="Store.Delete"></a>

#### func (*Store) Delete

```go
func (s *Store) Delete(ctx context.Context, name string) error
```

Delete removes the template name. Its errors are as Get's: one wrapping
template.ErrTemplateNotFound when there is none.

<a id="Store.Exists"></a>

#### func (*Store) Exists

```go
func (s *Store) Exists(ctx context.Context, name string) (bool, error)
```

Exists reports whether the template name is stored. Its errors are as
Get's, without template.ErrTemplateNotFound.

<a id="Store.Get"></a>

#### func (*Store) Get

```go
func (s *Store) Get(ctx context.Context, name string) ([]byte, error)
```

Get returns the content of the template name, as described in the
package documentation. Its errors wrap template.ErrInvalidName,
template.ErrTemplateNotFound, template.ErrTooLarge, ErrQuery,
template.ErrNotInitialized or template.ErrClosed. Content over the
store's maximum size is not sent by the database.

<a id="Store.Init"></a>

#### func (*Store) Init

```go
func (s *Store) Init(context.Context) error
```

Init picks the dialect from the provider's driver, takes the provider's
DB and registers the table's migrations, as described in the package
documentation. On an open store it returns
template.ErrAlreadyInitialized and changes nothing. A failed Init leaves
the store as it was.

<a id="Store.List"></a>

#### func (*Store) List

```go
func (s *Store) List(ctx context.Context) (names []string, err error)
```

List returns the names of the namespace's templates in byte order, as
described in the package documentation. A row whose name the store
would refuse is left out.

<a id="Store.Name"></a>

#### func (*Store) Name

```go
func (*Store) Name() string
```

Name returns ServiceName.

<a id="Store.Register"></a>

#### func (*Store) Register

```go
func (s *Store) Register(ctx context.Context, name string, content []byte) error
```

Register stores a copy of content as the template name, replacing one
of that name. Nil content is stored as empty, and content over the
store's maximum size is an error wrapping template.ErrTooLarge. Its
errors are as Get's, without template.ErrTemplateNotFound.

<a id="Store.RegisterFS"></a>

#### func (*Store) RegisterFS

```go
func (s *Store) RegisterFS(ctx context.Context, fsys fs.FS) error
```

RegisterFS reads the files of fsys with one of the store's extensions
and stores them in one transaction, all or none, as described in the
template package documentation.
