repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tools/dbutils/json.go | tools/dbutils/json.go | package dbutils
import (
"fmt"
"strings"
)
// JSONEach returns JSON_EACH SQLite string expression with
// some normalizations for non-json columns.
func JSONEach(column string) string {
// note: we are not using the new and shorter "if(x,y)" syntax for
// compatibility with custom drivers that use older SQLite version
return fmt.Sprintf(
`json_each(CASE WHEN iif(json_valid([[%s]]), json_type([[%s]])='array', FALSE) THEN [[%s]] ELSE json_array([[%s]]) END)`,
column, column, column, column,
)
}
// JSONArrayLength returns JSON_ARRAY_LENGTH SQLite string expression
// with some normalizations for non-json columns.
//
// It works with both json and non-json column values.
//
// Returns 0 for empty string or NULL column values.
func JSONArrayLength(column string) string {
// note: we are not using the new and shorter "if(x,y)" syntax for
// compatibility with custom drivers that use older SQLite version
return fmt.Sprintf(
`json_array_length(CASE WHEN iif(json_valid([[%s]]), json_type([[%s]])='array', FALSE) THEN [[%s]] ELSE (CASE WHEN [[%s]] = '' OR [[%s]] IS NULL THEN json_array() ELSE json_array([[%s]]) END) END)`,
column, column, column, column, column, column,
)
}
// JSONExtract returns a JSON_EXTRACT SQLite string expression with
// some normalizations for non-json columns.
func JSONExtract(column string, path string) string {
// prefix the path with dot if it is not starting with array notation
if path != "" && !strings.HasPrefix(path, "[") {
path = "." + path
}
return fmt.Sprintf(
// note: the extra object wrapping is needed to workaround the cases where a json_extract is used with non-json columns.
"(CASE WHEN json_valid([[%s]]) THEN JSON_EXTRACT([[%s]], '$%s') ELSE JSON_EXTRACT(json_object('pb', [[%s]]), '$.pb%s') END)",
column,
column,
path,
column,
path,
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tools/dbutils/index.go | tools/dbutils/index.go | package dbutils
import (
"regexp"
"strings"
"github.com/pocketbase/pocketbase/tools/tokenizer"
)
var (
indexRegex = regexp.MustCompile(`(?im)create\s+(unique\s+)?\s*index\s*(if\s+not\s+exists\s+)?(\S*)\s+on\s+(\S*)\s*\(([\s\S]*)\)(?:\s*where\s+([\s\S]*))?`)
indexColumnRegex = regexp.MustCompile(`(?im)^([\s\S]+?)(?:\s+collate\s+([\w]+))?(?:\s+(asc|desc))?$`)
)
// IndexColumn represents a single parsed SQL index column.
type IndexColumn struct {
Name string `json:"name"` // identifier or expression
Collate string `json:"collate"`
Sort string `json:"sort"`
}
// Index represents a single parsed SQL CREATE INDEX expression.
type Index struct {
SchemaName string `json:"schemaName"`
IndexName string `json:"indexName"`
TableName string `json:"tableName"`
Where string `json:"where"`
Columns []IndexColumn `json:"columns"`
Unique bool `json:"unique"`
Optional bool `json:"optional"`
}
// IsValid checks if the current Index contains the minimum required fields to be considered valid.
func (idx Index) IsValid() bool {
return idx.IndexName != "" && idx.TableName != "" && len(idx.Columns) > 0
}
// Build returns a "CREATE INDEX" SQL string from the current index parts.
//
// Returns empty string if idx.IsValid() is false.
func (idx Index) Build() string {
if !idx.IsValid() {
return ""
}
var str strings.Builder
str.WriteString("CREATE ")
if idx.Unique {
str.WriteString("UNIQUE ")
}
str.WriteString("INDEX ")
if idx.Optional {
str.WriteString("IF NOT EXISTS ")
}
if idx.SchemaName != "" {
str.WriteString("`")
str.WriteString(idx.SchemaName)
str.WriteString("`.")
}
str.WriteString("`")
str.WriteString(idx.IndexName)
str.WriteString("` ")
str.WriteString("ON `")
str.WriteString(idx.TableName)
str.WriteString("` (")
if len(idx.Columns) > 1 {
str.WriteString("\n ")
}
var hasCol bool
for _, col := range idx.Columns {
trimmedColName := strings.TrimSpace(col.Name)
if trimmedColName == "" {
continue
}
if hasCol {
str.WriteString(",\n ")
}
if strings.Contains(col.Name, "(") || strings.Contains(col.Name, " ") {
// most likely an expression
str.WriteString(trimmedColName)
} else {
// regular identifier
str.WriteString("`")
str.WriteString(trimmedColName)
str.WriteString("`")
}
if col.Collate != "" {
str.WriteString(" COLLATE ")
str.WriteString(col.Collate)
}
if col.Sort != "" {
str.WriteString(" ")
str.WriteString(strings.ToUpper(col.Sort))
}
hasCol = true
}
if hasCol && len(idx.Columns) > 1 {
str.WriteString("\n")
}
str.WriteString(")")
if idx.Where != "" {
str.WriteString(" WHERE ")
str.WriteString(idx.Where)
}
return str.String()
}
// ParseIndex parses the provided "CREATE INDEX" SQL string into Index struct.
func ParseIndex(createIndexExpr string) Index {
result := Index{}
matches := indexRegex.FindStringSubmatch(createIndexExpr)
if len(matches) != 7 {
return result
}
trimChars := "`\"'[]\r\n\t\f\v "
// Unique
// ---
result.Unique = strings.TrimSpace(matches[1]) != ""
// Optional (aka. "IF NOT EXISTS")
// ---
result.Optional = strings.TrimSpace(matches[2]) != ""
// SchemaName and IndexName
// ---
nameTk := tokenizer.NewFromString(matches[3])
nameTk.Separators('.')
nameParts, _ := nameTk.ScanAll()
if len(nameParts) == 2 {
result.SchemaName = strings.Trim(nameParts[0], trimChars)
result.IndexName = strings.Trim(nameParts[1], trimChars)
} else {
result.IndexName = strings.Trim(nameParts[0], trimChars)
}
// TableName
// ---
result.TableName = strings.Trim(matches[4], trimChars)
// Columns
// ---
columnsTk := tokenizer.NewFromString(matches[5])
columnsTk.Separators(',')
rawColumns, _ := columnsTk.ScanAll()
result.Columns = make([]IndexColumn, 0, len(rawColumns))
for _, col := range rawColumns {
colMatches := indexColumnRegex.FindStringSubmatch(col)
if len(colMatches) != 4 {
continue
}
trimmedName := strings.Trim(colMatches[1], trimChars)
if trimmedName == "" {
continue
}
result.Columns = append(result.Columns, IndexColumn{
Name: trimmedName,
Collate: strings.TrimSpace(colMatches[2]),
Sort: strings.ToUpper(colMatches[3]),
})
}
// WHERE expression
// ---
result.Where = strings.TrimSpace(matches[6])
return result
}
// FindSingleColumnUniqueIndex returns the first matching single column unique index.
func FindSingleColumnUniqueIndex(indexes []string, column string) (Index, bool) {
var index Index
for _, idx := range indexes {
index := ParseIndex(idx)
if index.Unique && len(index.Columns) == 1 && strings.EqualFold(index.Columns[0].Name, column) {
return index, true
}
}
return index, false
}
// Deprecated: Use `_, ok := FindSingleColumnUniqueIndex(indexes, column)` instead.
//
// HasColumnUniqueIndex loosely checks whether the specified column has
// a single column unique index (WHERE statements are ignored).
func HasSingleColumnUniqueIndex(column string, indexes []string) bool {
_, ok := FindSingleColumnUniqueIndex(indexes, column)
return ok
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tools/dbutils/json_test.go | tools/dbutils/json_test.go | package dbutils_test
import (
"testing"
"github.com/pocketbase/pocketbase/tools/dbutils"
)
func TestJSONEach(t *testing.T) {
result := dbutils.JSONEach("a.b")
expected := "json_each(CASE WHEN iif(json_valid([[a.b]]), json_type([[a.b]])='array', FALSE) THEN [[a.b]] ELSE json_array([[a.b]]) END)"
if result != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, result)
}
}
func TestJSONArrayLength(t *testing.T) {
result := dbutils.JSONArrayLength("a.b")
expected := "json_array_length(CASE WHEN iif(json_valid([[a.b]]), json_type([[a.b]])='array', FALSE) THEN [[a.b]] ELSE (CASE WHEN [[a.b]] = '' OR [[a.b]] IS NULL THEN json_array() ELSE json_array([[a.b]]) END) END)"
if result != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, result)
}
}
func TestJSONExtract(t *testing.T) {
scenarios := []struct {
name string
column string
path string
expected string
}{
{
"empty path",
"a.b",
"",
"(CASE WHEN json_valid([[a.b]]) THEN JSON_EXTRACT([[a.b]], '$') ELSE JSON_EXTRACT(json_object('pb', [[a.b]]), '$.pb') END)",
},
{
"starting with array index",
"a.b",
"[1].a[2]",
"(CASE WHEN json_valid([[a.b]]) THEN JSON_EXTRACT([[a.b]], '$[1].a[2]') ELSE JSON_EXTRACT(json_object('pb', [[a.b]]), '$.pb[1].a[2]') END)",
},
{
"starting with key",
"a.b",
"a.b[2].c",
"(CASE WHEN json_valid([[a.b]]) THEN JSON_EXTRACT([[a.b]], '$.a.b[2].c') ELSE JSON_EXTRACT(json_object('pb', [[a.b]]), '$.pb.a.b[2].c') END)",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := dbutils.JSONExtract(s.column, s.path)
if result != s.expected {
t.Fatalf("Expected\n%v\ngot\n%v", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tools/dbutils/index_test.go | tools/dbutils/index_test.go | package dbutils_test
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/pocketbase/pocketbase/tools/dbutils"
)
func TestParseIndex(t *testing.T) {
scenarios := []struct {
index string
expected dbutils.Index
}{
// invalid
{
`invalid`,
dbutils.Index{},
},
// simple (multiple spaces between the table and columns list)
{
`create index indexname on tablename (col1)`,
dbutils.Index{
IndexName: "indexname",
TableName: "tablename",
Columns: []dbutils.IndexColumn{
{Name: "col1"},
},
},
},
// simple (no space between the table and the columns list)
{
`create index indexname on tablename(col1)`,
dbutils.Index{
IndexName: "indexname",
TableName: "tablename",
Columns: []dbutils.IndexColumn{
{Name: "col1"},
},
},
},
// all fields
{
`CREATE UNIQUE INDEX IF NOT EXISTS "schemaname".[indexname] on 'tablename' (
col0,
` + "`" + `col1` + "`" + `,
json_extract("col2", "$.a") asc,
"col3" collate NOCASE,
"col4" collate RTRIM desc
) where test = 1`,
dbutils.Index{
Unique: true,
Optional: true,
SchemaName: "schemaname",
IndexName: "indexname",
TableName: "tablename",
Columns: []dbutils.IndexColumn{
{Name: "col0"},
{Name: "col1"},
{Name: `json_extract("col2", "$.a")`, Sort: "ASC"},
{Name: `col3`, Collate: "NOCASE"},
{Name: `col4`, Collate: "RTRIM", Sort: "DESC"},
},
Where: "test = 1",
},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("scenario_%d", i), func(t *testing.T) {
result := dbutils.ParseIndex(s.index)
resultRaw, err := json.Marshal(result)
if err != nil {
t.Fatalf("Faild to marshalize parse result: %v", err)
}
expectedRaw, err := json.Marshal(s.expected)
if err != nil {
t.Fatalf("Failed to marshalize expected index: %v", err)
}
if !bytes.Equal(resultRaw, expectedRaw) {
t.Errorf("Expected \n%s \ngot \n%s", expectedRaw, resultRaw)
}
})
}
}
func TestIndexIsValid(t *testing.T) {
scenarios := []struct {
name string
index dbutils.Index
expected bool
}{
{
"empty",
dbutils.Index{},
false,
},
{
"no index name",
dbutils.Index{
TableName: "table",
Columns: []dbutils.IndexColumn{{Name: "col"}},
},
false,
},
{
"no table name",
dbutils.Index{
IndexName: "index",
Columns: []dbutils.IndexColumn{{Name: "col"}},
},
false,
},
{
"no columns",
dbutils.Index{
IndexName: "index",
TableName: "table",
},
false,
},
{
"min valid",
dbutils.Index{
IndexName: "index",
TableName: "table",
Columns: []dbutils.IndexColumn{{Name: "col"}},
},
true,
},
{
"all fields",
dbutils.Index{
Optional: true,
Unique: true,
SchemaName: "schema",
IndexName: "index",
TableName: "table",
Columns: []dbutils.IndexColumn{{Name: "col"}},
Where: "test = 1 OR test = 2",
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.index.IsValid()
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestIndexBuild(t *testing.T) {
scenarios := []struct {
name string
index dbutils.Index
expected string
}{
{
"empty",
dbutils.Index{},
"",
},
{
"no index name",
dbutils.Index{
TableName: "table",
Columns: []dbutils.IndexColumn{{Name: "col"}},
},
"",
},
{
"no table name",
dbutils.Index{
IndexName: "index",
Columns: []dbutils.IndexColumn{{Name: "col"}},
},
"",
},
{
"no columns",
dbutils.Index{
IndexName: "index",
TableName: "table",
},
"",
},
{
"min valid",
dbutils.Index{
IndexName: "index",
TableName: "table",
Columns: []dbutils.IndexColumn{{Name: "col"}},
},
"CREATE INDEX `index` ON `table` (`col`)",
},
{
"all fields",
dbutils.Index{
Optional: true,
Unique: true,
SchemaName: "schema",
IndexName: "index",
TableName: "table",
Columns: []dbutils.IndexColumn{
{Name: "col1", Collate: "NOCASE", Sort: "asc"},
{Name: "col2", Sort: "desc"},
{Name: `json_extract("col3", "$.a")`, Collate: "NOCASE"},
},
Where: "test = 1 OR test = 2",
},
"CREATE UNIQUE INDEX IF NOT EXISTS `schema`.`index` ON `table` (\n `col1` COLLATE NOCASE ASC,\n `col2` DESC,\n " + `json_extract("col3", "$.a")` + " COLLATE NOCASE\n) WHERE test = 1 OR test = 2",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.index.Build()
if result != s.expected {
t.Fatalf("Expected \n%v \ngot \n%v", s.expected, result)
}
})
}
}
func TestHasSingleColumnUniqueIndex(t *testing.T) {
scenarios := []struct {
name string
column string
indexes []string
expected bool
}{
{
"empty indexes",
"test",
nil,
false,
},
{
"empty column",
"",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`)",
},
false,
},
{
"mismatched column",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test2`)",
},
false,
},
{
"non unique index",
"test",
[]string{
"CREATE INDEX `index1` ON `example` (`test`)",
},
false,
},
{
"matching columnd and unique index",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`)",
},
true,
},
{
"multiple columns",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`, `test2`)",
},
false,
},
{
"multiple indexes",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`, `test2`)",
"CREATE UNIQUE INDEX `index2` ON `example` (`test`)",
},
true,
},
{
"partial unique index",
"test",
[]string{
"CREATE UNIQUE INDEX `index` ON `example` (`test`) where test != ''",
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := dbutils.HasSingleColumnUniqueIndex(s.column, s.indexes)
if result != s.expected {
t.Fatalf("Expected %v got %v", s.expected, result)
}
})
}
}
func TestFindSingleColumnUniqueIndex(t *testing.T) {
scenarios := []struct {
name string
column string
indexes []string
expected bool
}{
{
"empty indexes",
"test",
nil,
false,
},
{
"empty column",
"",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`)",
},
false,
},
{
"mismatched column",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test2`)",
},
false,
},
{
"non unique index",
"test",
[]string{
"CREATE INDEX `index1` ON `example` (`test`)",
},
false,
},
{
"matching columnd and unique index",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`)",
},
true,
},
{
"multiple columns",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`, `test2`)",
},
false,
},
{
"multiple indexes",
"test",
[]string{
"CREATE UNIQUE INDEX `index1` ON `example` (`test`, `test2`)",
"CREATE UNIQUE INDEX `index2` ON `example` (`test`)",
},
true,
},
{
"partial unique index",
"test",
[]string{
"CREATE UNIQUE INDEX `index` ON `example` (`test`) where test != ''",
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
index, exists := dbutils.FindSingleColumnUniqueIndex(s.indexes, s.column)
if exists != s.expected {
t.Fatalf("Expected exists %v got %v", s.expected, exists)
}
if !exists && len(index.Columns) > 0 {
t.Fatal("Expected index.Columns to be empty")
}
if exists && !strings.EqualFold(index.Columns[0].Name, s.column) {
t.Fatalf("Expected to find column %q in %v", s.column, index)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tests/request.go | tests/request.go | package tests
import (
"bytes"
"io"
"mime/multipart"
"os"
)
// MockMultipartData creates a mocked multipart/form-data payload.
//
// Example
//
// data, mp, err := tests.MockMultipartData(
// map[string]string{"title": "new"},
// "file1",
// "file2",
// ...
// )
func MockMultipartData(data map[string]string, fileFields ...string) (*bytes.Buffer, *multipart.Writer, error) {
body := new(bytes.Buffer)
mp := multipart.NewWriter(body)
defer mp.Close()
// write data fields
for k, v := range data {
mp.WriteField(k, v)
}
// write file fields
for _, fileField := range fileFields {
// create a test temporary file
err := func() error {
tmpFile, err := os.CreateTemp(os.TempDir(), "tmpfile-*.txt")
if err != nil {
return err
}
if _, err := tmpFile.Write([]byte("test")); err != nil {
return err
}
tmpFile.Seek(0, 0)
defer tmpFile.Close()
defer os.Remove(tmpFile.Name())
// stub uploaded file
w, err := mp.CreateFormFile(fileField, tmpFile.Name())
if err != nil {
return err
}
if _, err := io.Copy(w, tmpFile); err != nil {
return err
}
return nil
}()
if err != nil {
return nil, nil, err
}
}
return body, mp, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tests/api.go | tests/api.go | package tests
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"maps"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
)
// ApiScenario defines a single api request test case/scenario.
type ApiScenario struct {
// Name is the test name.
Name string
// Method is the HTTP method of the test request to use.
Method string
// URL is the url/path of the endpoint you want to test.
URL string
// Body specifies the body to send with the request.
//
// For example:
//
// strings.NewReader(`{"title":"abc"}`)
Body io.Reader
// Headers specifies the headers to send with the request (e.g. "Authorization": "abc")
Headers map[string]string
// Delay adds a delay before checking the expectations usually
// to ensure that all fired non-awaited go routines have finished
Delay time.Duration
// Timeout specifies how long to wait before cancelling the request context.
//
// A zero or negative value means that there will be no timeout.
Timeout time.Duration
// DisableTestAppCleanup disables the builtin TestApp cleanup at
// the end of the ApiScenario execution.
//
// This option works only when explicit TestAppFactory is specified
// and means that the developer is responsible to do the necessary
// after test cleanup on their own (e.g. by manually calling testApp.Cleanup()).
DisableTestAppCleanup bool
// expectations
// ---------------------------------------------------------------
// ExpectedStatus specifies the expected response HTTP status code.
ExpectedStatus int
// List of keywords that MUST exist in the response body.
//
// Either ExpectedContent or NotExpectedContent must be set if the response body is non-empty.
// Leave both fields empty if you want to ensure that the response didn't have any body (e.g. 204).
ExpectedContent []string
// List of keywords that MUST NOT exist in the response body.
//
// Either ExpectedContent or NotExpectedContent must be set if the response body is non-empty.
// Leave both fields empty if you want to ensure that the response didn't have any body (e.g. 204).
NotExpectedContent []string
// List of hook events to check whether they were fired or not.
//
// You can use the wildcard "*" event key if you want to ensure
// that no other hook events except those listed have been fired.
//
// For example:
//
// map[string]int{ "*": 0 } // no hook events were fired
// map[string]int{ "*": 0, "EventA": 2 } // no hook events, except EventA were fired
// map[string]int{ "EventA": 2, "EventB": 0 } // ensures that EventA was fired exactly 2 times and EventB exactly 0 times.
ExpectedEvents map[string]int
// test hooks
// ---------------------------------------------------------------
TestAppFactory func(t testing.TB) *TestApp
BeforeTestFunc func(t testing.TB, app *TestApp, e *core.ServeEvent)
AfterTestFunc func(t testing.TB, app *TestApp, res *http.Response)
}
// Test executes the test scenario.
//
// Example:
//
// func TestListExample(t *testing.T) {
// scenario := tests.ApiScenario{
// Name: "list example collection",
// Method: http.MethodGet,
// URL: "/api/collections/example/records",
// ExpectedStatus: 200,
// ExpectedContent: []string{
// `"totalItems":3`,
// `"id":"0yxhwia2amd8gec"`,
// `"id":"achvryl401bhse3"`,
// `"id":"llvuca81nly1qls"`,
// },
// ExpectedEvents: map[string]int{
// "OnRecordsListRequest": 1,
// "OnRecordEnrich": 3,
// },
// }
//
// scenario.Test(t)
// }
func (scenario *ApiScenario) Test(t *testing.T) {
t.Run(scenario.normalizedName(), func(t *testing.T) {
scenario.test(t)
})
}
// Benchmark benchmarks the test scenario.
//
// Example:
//
// func BenchmarkListExample(b *testing.B) {
// scenario := tests.ApiScenario{
// Name: "list example collection",
// Method: http.MethodGet,
// URL: "/api/collections/example/records",
// ExpectedStatus: 200,
// ExpectedContent: []string{
// `"totalItems":3`,
// `"id":"0yxhwia2amd8gec"`,
// `"id":"achvryl401bhse3"`,
// `"id":"llvuca81nly1qls"`,
// },
// ExpectedEvents: map[string]int{
// "OnRecordsListRequest": 1,
// "OnRecordEnrich": 3,
// },
// }
//
// scenario.Benchmark(b)
// }
func (scenario *ApiScenario) Benchmark(b *testing.B) {
b.Run(scenario.normalizedName(), func(b *testing.B) {
for i := 0; i < b.N; i++ {
scenario.test(b)
}
})
}
func (scenario *ApiScenario) normalizedName() string {
var name = scenario.Name
if name == "" {
name = fmt.Sprintf("%s:%s", scenario.Method, scenario.URL)
}
return name
}
func (scenario *ApiScenario) test(t testing.TB) {
var testApp *TestApp
if scenario.TestAppFactory != nil {
testApp = scenario.TestAppFactory(t)
if testApp == nil {
t.Fatal("TestAppFactory must return a non-nill app instance")
}
} else {
var testAppErr error
testApp, testAppErr = NewTestApp()
if testAppErr != nil {
t.Fatalf("Failed to initialize the test app instance: %v", testAppErr)
}
}
// https://github.com/pocketbase/pocketbase/discussions/7267
if scenario.TestAppFactory == nil || !scenario.DisableTestAppCleanup {
defer testApp.Cleanup()
}
baseRouter, err := apis.NewRouter(testApp)
if err != nil {
t.Fatal(err)
}
// manually trigger the serve event to ensure that custom app routes and middlewares are registered
serveEvent := new(core.ServeEvent)
serveEvent.App = testApp
serveEvent.Router = baseRouter
serveErr := testApp.OnServe().Trigger(serveEvent, func(e *core.ServeEvent) error {
if scenario.BeforeTestFunc != nil {
scenario.BeforeTestFunc(t, testApp, e)
}
// reset the event counters in case a hook was triggered from a before func (eg. db save)
testApp.ResetEventCalls()
// add middleware to timeout long-running requests (eg. keep-alive routes)
e.Router.Bind(&hook.Handler[*core.RequestEvent]{
Func: func(re *core.RequestEvent) error {
slowTimer := time.AfterFunc(3*time.Second, func() {
t.Logf("[WARN] Long running test %q", scenario.Name)
})
defer slowTimer.Stop()
if scenario.Timeout > 0 {
ctx, cancelFunc := context.WithTimeout(re.Request.Context(), scenario.Timeout)
defer cancelFunc()
re.Request = re.Request.Clone(ctx)
}
return re.Next()
},
Priority: -9999,
})
recorder := httptest.NewRecorder()
req := httptest.NewRequest(scenario.Method, scenario.URL, scenario.Body)
// set default header
req.Header.Set("content-type", "application/json")
// set scenario headers
for k, v := range scenario.Headers {
req.Header.Set(k, v)
}
// execute request
mux, err := e.Router.BuildMux()
if err != nil {
t.Fatalf("Failed to build router mux: %v", err)
}
mux.ServeHTTP(recorder, req)
res := recorder.Result()
if res.StatusCode != scenario.ExpectedStatus {
t.Errorf("Expected status code %d, got %d", scenario.ExpectedStatus, res.StatusCode)
}
if scenario.Delay > 0 {
time.Sleep(scenario.Delay)
}
if len(scenario.ExpectedContent) == 0 && len(scenario.NotExpectedContent) == 0 {
if len(recorder.Body.Bytes()) != 0 {
t.Errorf("Expected empty body, got \n%v", recorder.Body.String())
}
} else {
// normalize json response format
buffer := new(bytes.Buffer)
err := json.Compact(buffer, recorder.Body.Bytes())
var normalizedBody string
if err != nil {
// not a json...
normalizedBody = recorder.Body.String()
} else {
normalizedBody = buffer.String()
}
for _, item := range scenario.ExpectedContent {
if !strings.Contains(normalizedBody, item) {
t.Errorf("Cannot find %v in response body \n%v", item, normalizedBody)
break
}
}
for _, item := range scenario.NotExpectedContent {
if strings.Contains(normalizedBody, item) {
t.Errorf("Didn't expect %v in response body \n%v", item, normalizedBody)
break
}
}
}
remainingEvents := maps.Clone(testApp.EventCalls)
var noOtherEventsShouldRemain bool
for event, expectedNum := range scenario.ExpectedEvents {
if event == "*" && expectedNum <= 0 {
noOtherEventsShouldRemain = true
continue
}
actualNum := remainingEvents[event]
if actualNum != expectedNum {
t.Errorf("Expected event %s to be called %d, got %d", event, expectedNum, actualNum)
}
delete(remainingEvents, event)
}
if noOtherEventsShouldRemain && len(remainingEvents) > 0 {
t.Errorf("Missing expected remaining events:\n%#v\nAll triggered app events are:\n%#v", remainingEvents, testApp.EventCalls)
}
if scenario.AfterTestFunc != nil {
scenario.AfterTestFunc(t, testApp, res)
}
return nil
})
if serveErr != nil {
t.Fatalf("Failed to trigger app serve hook: %v", serveErr)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tests/validation_errors.go | tests/validation_errors.go | package tests
import (
"errors"
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
// TestValidationErrors checks whether the provided rawErrors are
// instance of [validation.Errors] and contains the expectedErrors keys.
func TestValidationErrors(t *testing.T, rawErrors error, expectedErrors []string) {
var errs validation.Errors
if rawErrors != nil && !errors.As(rawErrors, &errs) {
t.Fatalf("Failed to parse errors, expected to find validation.Errors, got %T\n%v", rawErrors, rawErrors)
}
if len(errs) != len(expectedErrors) {
keys := make([]string, 0, len(errs))
for k := range errs {
keys = append(keys, k)
}
t.Fatalf("Expected error keys \n%v\ngot\n%v\n%v", expectedErrors, keys, errs)
}
for _, k := range expectedErrors {
if _, ok := errs[k]; !ok {
t.Fatalf("Missing expected error key %q in %v", k, errs)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tests/mailer.go | tests/mailer.go | package tests
import (
"slices"
"sync"
"github.com/pocketbase/pocketbase/tools/mailer"
)
var _ mailer.Mailer = (*TestMailer)(nil)
// TestMailer is a mock [mailer.Mailer] implementation.
type TestMailer struct {
mux sync.Mutex
messages []*mailer.Message
}
// Send implements [mailer.Mailer] interface.
func (tm *TestMailer) Send(m *mailer.Message) error {
tm.mux.Lock()
defer tm.mux.Unlock()
tm.messages = append(tm.messages, m)
return nil
}
// Reset clears any previously test collected data.
func (tm *TestMailer) Reset() {
tm.mux.Lock()
defer tm.mux.Unlock()
tm.messages = nil
}
// TotalSend returns the total number of sent messages.
func (tm *TestMailer) TotalSend() int {
tm.mux.Lock()
defer tm.mux.Unlock()
return len(tm.messages)
}
// Messages returns a shallow copy of all of the collected test messages.
func (tm *TestMailer) Messages() []*mailer.Message {
tm.mux.Lock()
defer tm.mux.Unlock()
return slices.Clone(tm.messages)
}
// FirstMessage returns a shallow copy of the first sent message.
//
// Returns an empty mailer.Message struct if there are no sent messages.
func (tm *TestMailer) FirstMessage() mailer.Message {
tm.mux.Lock()
defer tm.mux.Unlock()
var m mailer.Message
if len(tm.messages) > 0 {
return *tm.messages[0]
}
return m
}
// LastMessage returns a shallow copy of the last sent message.
//
// Returns an empty mailer.Message struct if there are no sent messages.
func (tm *TestMailer) LastMessage() mailer.Message {
tm.mux.Lock()
defer tm.mux.Unlock()
var m mailer.Message
if len(tm.messages) > 0 {
return *tm.messages[len(tm.messages)-1]
}
return m
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tests/dynamic_stubs.go | tests/dynamic_stubs.go | package tests
import (
"strconv"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/types"
)
func StubOTPRecords(app core.App) error {
superuser2, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
return err
}
superuser2.SetRaw("stubId", "superuser2")
superuser3, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test3@example.com")
if err != nil {
return err
}
superuser3.SetRaw("stubId", "superuser3")
user1, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
return err
}
user1.SetRaw("stubId", "user1")
now := types.NowDateTime()
old := types.NowDateTime().Add(-1 * time.Hour)
stubs := map[*core.Record][]types.DateTime{
superuser2: {now, now.Add(-1 * time.Millisecond), old, now.Add(-2 * time.Millisecond), old.Add(-1 * time.Millisecond)},
superuser3: {now.Add(-3 * time.Millisecond), now.Add(-2 * time.Minute)},
user1: {old},
}
for record, idDates := range stubs {
for i, date := range idDates {
otp := core.NewOTP(app)
otp.Id = record.GetString("stubId") + "_" + strconv.Itoa(i)
otp.SetRecordRef(record.Id)
otp.SetCollectionRef(record.Collection().Id)
otp.SetPassword("test123")
otp.SetRaw("created", date)
if err := app.SaveNoValidate(otp); err != nil {
return err
}
}
}
return nil
}
func StubMFARecords(app core.App) error {
superuser2, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
return err
}
superuser2.SetRaw("stubId", "superuser2")
superuser3, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test3@example.com")
if err != nil {
return err
}
superuser3.SetRaw("stubId", "superuser3")
user1, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
return err
}
user1.SetRaw("stubId", "user1")
now := types.NowDateTime()
old := types.NowDateTime().Add(-1 * time.Hour)
type mfaData struct {
method string
date types.DateTime
}
stubs := map[*core.Record][]mfaData{
superuser2: {
{core.MFAMethodOTP, now},
{core.MFAMethodOTP, old},
{core.MFAMethodPassword, now.Add(-2 * time.Minute)},
{core.MFAMethodPassword, now.Add(-1 * time.Millisecond)},
{core.MFAMethodOAuth2, old.Add(-1 * time.Millisecond)},
},
superuser3: {
{core.MFAMethodOAuth2, now.Add(-3 * time.Millisecond)},
{core.MFAMethodPassword, now.Add(-3 * time.Minute)},
},
user1: {
{core.MFAMethodOAuth2, old},
},
}
for record, idDates := range stubs {
for i, data := range idDates {
otp := core.NewMFA(app)
otp.Id = record.GetString("stubId") + "_" + strconv.Itoa(i)
otp.SetRecordRef(record.Id)
otp.SetCollectionRef(record.Collection().Id)
otp.SetMethod(data.method)
otp.SetRaw("created", data.date)
if err := app.SaveNoValidate(otp); err != nil {
return err
}
}
}
return nil
}
func StubLogsData(app *TestApp) error {
_, err := app.AuxDB().NewQuery(`
delete from {{_logs}};
insert into {{_logs}} (
[[id]],
[[level]],
[[message]],
[[data]],
[[created]],
[[updated]]
)
values
(
"873f2133-9f38-44fb-bf82-c8f53b310d91",
0,
"test_message1",
'{"status":200}',
"2022-05-01 10:00:00.123Z",
"2022-05-01 10:00:00.123Z"
),
(
"f2133873-44fb-9f38-bf82-c918f53b310d",
8,
"test_message2",
'{"status":400}',
"2022-05-02 10:00:00.123Z",
"2022-05-02 10:00:00.123Z"
);
`).Execute()
return err
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/tests/app.go | tests/app.go | // Package tests provides common helpers and mocks used in PocketBase application tests.
package tests
import (
"io"
"os"
"path"
"path/filepath"
"runtime"
"sync"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
_ "github.com/pocketbase/pocketbase/migrations"
)
// TestApp is a wrapper app instance used for testing.
type TestApp struct {
*core.BaseApp
mux sync.Mutex
// EventCalls defines a map to inspect which app events
// (and how many times) were triggered.
EventCalls map[string]int
TestMailer *TestMailer
}
// Cleanup resets the test application state and removes the test
// app's dataDir from the filesystem.
//
// After this call, the app instance shouldn't be used anymore.
func (t *TestApp) Cleanup() {
event := new(core.TerminateEvent)
event.App = t
t.OnTerminate().Trigger(event, func(e *core.TerminateEvent) error {
t.TestMailer.Reset()
t.ResetEventCalls()
t.ResetBootstrapState()
return e.Next()
})
if t.DataDir() != "" {
os.RemoveAll(t.DataDir())
}
}
// ResetEventCalls resets the EventCalls counter.
func (t *TestApp) ResetEventCalls() {
t.mux.Lock()
defer t.mux.Unlock()
t.EventCalls = make(map[string]int)
}
func (t *TestApp) registerEventCall(name string) {
t.mux.Lock()
defer t.mux.Unlock()
if t.EventCalls == nil {
t.EventCalls = make(map[string]int)
}
t.EventCalls[name]++
}
// NewTestApp creates and initializes a test application instance.
//
// It is the caller's responsibility to call app.Cleanup() when the app is no longer needed.
func NewTestApp(optTestDataDir ...string) (*TestApp, error) {
var testDataDir string
if len(optTestDataDir) > 0 {
testDataDir = optTestDataDir[0]
}
return NewTestAppWithConfig(core.BaseAppConfig{
DataDir: testDataDir,
EncryptionEnv: "pb_test_env",
})
}
// NewTestAppWithConfig creates and initializes a test application instance
// from the provided config.
//
// If config.DataDir is not set it fallbacks to the default internal test data directory.
//
// config.DataDir is cloned for each new test application instance.
//
// It is the caller's responsibility to call app.Cleanup() when the app is no longer needed.
func NewTestAppWithConfig(config core.BaseAppConfig) (*TestApp, error) {
if config.DataDir == "" {
// fallback to the default test data directory
_, currentFile, _, _ := runtime.Caller(0)
config.DataDir = filepath.Join(path.Dir(currentFile), "data")
}
tempDir, err := TempDirClone(config.DataDir)
if err != nil {
return nil, err
}
// replace with the clone
config.DataDir = tempDir
app := core.NewBaseApp(config)
// load data dir and db connections
if err := app.Bootstrap(); err != nil {
return nil, err
}
// ensure that the Dao and DB configurations are properly loaded
if _, err := app.DB().NewQuery("Select 1").Execute(); err != nil {
return nil, err
}
if _, err := app.AuxDB().NewQuery("Select 1").Execute(); err != nil {
return nil, err
}
// apply any missing migrations
if err := app.RunAllMigrations(); err != nil {
return nil, err
}
// force disable request logs because the logs db call execute in a separate
// go routine and it is possible to panic due to earlier api test completion.
app.Settings().Logs.MaxDays = 0
t := &TestApp{
BaseApp: app,
EventCalls: make(map[string]int),
TestMailer: &TestMailer{},
}
t.OnBootstrap().Bind(&hook.Handler[*core.BootstrapEvent]{
Func: func(e *core.BootstrapEvent) error {
t.registerEventCall("OnBootstrap")
return e.Next()
},
Priority: -99999,
})
t.OnServe().Bind(&hook.Handler[*core.ServeEvent]{
Func: func(e *core.ServeEvent) error {
t.registerEventCall("OnServe")
e.InstallerFunc = nil // https://github.com/pocketbase/pocketbase/discussions/7202
return e.Next()
},
Priority: -99999,
})
t.OnTerminate().Bind(&hook.Handler[*core.TerminateEvent]{
Func: func(e *core.TerminateEvent) error {
t.registerEventCall("OnTerminate")
return e.Next()
},
Priority: -99999,
})
t.OnBackupCreate().Bind(&hook.Handler[*core.BackupEvent]{
Func: func(e *core.BackupEvent) error {
t.registerEventCall("OnBackupCreate")
return e.Next()
},
Priority: -99999,
})
t.OnBackupRestore().Bind(&hook.Handler[*core.BackupEvent]{
Func: func(e *core.BackupEvent) error {
t.registerEventCall("OnBackupRestore")
return e.Next()
},
Priority: -99999,
})
t.OnModelCreate().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelCreate")
return e.Next()
},
Priority: -99999,
})
t.OnModelCreateExecute().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelCreateExecute")
return e.Next()
},
Priority: -99999,
})
t.OnModelAfterCreateSuccess().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelAfterCreateSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnModelAfterCreateError().Bind(&hook.Handler[*core.ModelErrorEvent]{
Func: func(e *core.ModelErrorEvent) error {
t.registerEventCall("OnModelAfterCreateError")
return e.Next()
},
Priority: -99999,
})
t.OnModelUpdate().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelUpdate")
return e.Next()
},
Priority: -99999,
})
t.OnModelUpdateExecute().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelUpdateExecute")
return e.Next()
},
Priority: -99999,
})
t.OnModelAfterUpdateSuccess().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelAfterUpdateSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnModelAfterUpdateError().Bind(&hook.Handler[*core.ModelErrorEvent]{
Func: func(e *core.ModelErrorEvent) error {
t.registerEventCall("OnModelAfterUpdateError")
return e.Next()
},
Priority: -99999,
})
t.OnModelValidate().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelValidate")
return e.Next()
},
Priority: -99999,
})
t.OnModelDelete().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelDelete")
return e.Next()
},
Priority: -99999,
})
t.OnModelDeleteExecute().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelDeleteExecute")
return e.Next()
},
Priority: -99999,
})
t.OnModelAfterDeleteSuccess().Bind(&hook.Handler[*core.ModelEvent]{
Func: func(e *core.ModelEvent) error {
t.registerEventCall("OnModelAfterDeleteSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnModelAfterDeleteError().Bind(&hook.Handler[*core.ModelErrorEvent]{
Func: func(e *core.ModelErrorEvent) error {
t.registerEventCall("OnModelAfterDeleteError")
return e.Next()
},
Priority: -99999,
})
t.OnRecordEnrich().Bind(&hook.Handler[*core.RecordEnrichEvent]{
Func: func(e *core.RecordEnrichEvent) error {
t.registerEventCall("OnRecordEnrich")
return e.Next()
},
Priority: -99999,
})
t.OnRecordValidate().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordValidate")
return e.Next()
},
Priority: -99999,
})
t.OnRecordCreate().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordCreate")
return e.Next()
},
Priority: -99999,
})
t.OnRecordCreateExecute().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordCreateExecute")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAfterCreateSuccess().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordAfterCreateSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAfterCreateError().Bind(&hook.Handler[*core.RecordErrorEvent]{
Func: func(e *core.RecordErrorEvent) error {
t.registerEventCall("OnRecordAfterCreateError")
return e.Next()
},
Priority: -99999,
})
t.OnRecordUpdate().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordUpdate")
return e.Next()
},
Priority: -99999,
})
t.OnRecordUpdateExecute().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordUpdateExecute")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAfterUpdateSuccess().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordAfterUpdateSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAfterUpdateError().Bind(&hook.Handler[*core.RecordErrorEvent]{
Func: func(e *core.RecordErrorEvent) error {
t.registerEventCall("OnRecordAfterUpdateError")
return e.Next()
},
Priority: -99999,
})
t.OnRecordDelete().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordDelete")
return e.Next()
},
Priority: -99999,
})
t.OnRecordDeleteExecute().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordDeleteExecute")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAfterDeleteSuccess().Bind(&hook.Handler[*core.RecordEvent]{
Func: func(e *core.RecordEvent) error {
t.registerEventCall("OnRecordAfterDeleteSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAfterDeleteError().Bind(&hook.Handler[*core.RecordErrorEvent]{
Func: func(e *core.RecordErrorEvent) error {
t.registerEventCall("OnRecordAfterDeleteError")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionValidate().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionValidate")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionCreate().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionCreate")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionCreateExecute().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionCreateExecute")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionAfterCreateSuccess().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionAfterCreateSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionAfterCreateError().Bind(&hook.Handler[*core.CollectionErrorEvent]{
Func: func(e *core.CollectionErrorEvent) error {
t.registerEventCall("OnCollectionAfterCreateError")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionUpdate().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionUpdate")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionUpdateExecute().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionUpdateExecute")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionAfterUpdateSuccess().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionAfterUpdateSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionAfterUpdateError().Bind(&hook.Handler[*core.CollectionErrorEvent]{
Func: func(e *core.CollectionErrorEvent) error {
t.registerEventCall("OnCollectionAfterUpdateError")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionDelete().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionDelete")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionDeleteExecute().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionDeleteExecute")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionAfterDeleteSuccess().Bind(&hook.Handler[*core.CollectionEvent]{
Func: func(e *core.CollectionEvent) error {
t.registerEventCall("OnCollectionAfterDeleteSuccess")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionAfterDeleteError().Bind(&hook.Handler[*core.CollectionErrorEvent]{
Func: func(e *core.CollectionErrorEvent) error {
t.registerEventCall("OnCollectionAfterDeleteError")
return e.Next()
},
Priority: -99999,
})
t.OnMailerSend().Bind(&hook.Handler[*core.MailerEvent]{
Func: func(e *core.MailerEvent) error {
if t.TestMailer == nil {
t.TestMailer = &TestMailer{}
}
e.Mailer = t.TestMailer
t.registerEventCall("OnMailerSend")
return e.Next()
},
Priority: -99999,
})
t.OnMailerRecordAuthAlertSend().Bind(&hook.Handler[*core.MailerRecordEvent]{
Func: func(e *core.MailerRecordEvent) error {
t.registerEventCall("OnMailerRecordAuthAlertSend")
return e.Next()
},
Priority: -99999,
})
t.OnMailerRecordPasswordResetSend().Bind(&hook.Handler[*core.MailerRecordEvent]{
Func: func(e *core.MailerRecordEvent) error {
t.registerEventCall("OnMailerRecordPasswordResetSend")
return e.Next()
},
Priority: -99999,
})
t.OnMailerRecordVerificationSend().Bind(&hook.Handler[*core.MailerRecordEvent]{
Func: func(e *core.MailerRecordEvent) error {
t.registerEventCall("OnMailerRecordVerificationSend")
return e.Next()
},
Priority: -99999,
})
t.OnMailerRecordEmailChangeSend().Bind(&hook.Handler[*core.MailerRecordEvent]{
Func: func(e *core.MailerRecordEvent) error {
t.registerEventCall("OnMailerRecordEmailChangeSend")
return e.Next()
},
Priority: -99999,
})
t.OnMailerRecordOTPSend().Bind(&hook.Handler[*core.MailerRecordEvent]{
Func: func(e *core.MailerRecordEvent) error {
t.registerEventCall("OnMailerRecordOTPSend")
return e.Next()
},
Priority: -99999,
})
t.OnRealtimeConnectRequest().Bind(&hook.Handler[*core.RealtimeConnectRequestEvent]{
Func: func(e *core.RealtimeConnectRequestEvent) error {
t.registerEventCall("OnRealtimeConnectRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRealtimeMessageSend().Bind(&hook.Handler[*core.RealtimeMessageEvent]{
Func: func(e *core.RealtimeMessageEvent) error {
t.registerEventCall("OnRealtimeMessageSend")
return e.Next()
},
Priority: -99999,
})
t.OnRealtimeSubscribeRequest().Bind(&hook.Handler[*core.RealtimeSubscribeRequestEvent]{
Func: func(e *core.RealtimeSubscribeRequestEvent) error {
t.registerEventCall("OnRealtimeSubscribeRequest")
return e.Next()
},
Priority: -99999,
})
t.OnSettingsListRequest().Bind(&hook.Handler[*core.SettingsListRequestEvent]{
Func: func(e *core.SettingsListRequestEvent) error {
t.registerEventCall("OnSettingsListRequest")
return e.Next()
},
Priority: -99999,
})
t.OnSettingsUpdateRequest().Bind(&hook.Handler[*core.SettingsUpdateRequestEvent]{
Func: func(e *core.SettingsUpdateRequestEvent) error {
t.registerEventCall("OnSettingsUpdateRequest")
return e.Next()
},
Priority: -99999,
})
t.OnSettingsReload().Bind(&hook.Handler[*core.SettingsReloadEvent]{
Func: func(e *core.SettingsReloadEvent) error {
t.registerEventCall("OnSettingsReload")
return e.Next()
},
Priority: -99999,
})
t.OnFileDownloadRequest().Bind(&hook.Handler[*core.FileDownloadRequestEvent]{
Func: func(e *core.FileDownloadRequestEvent) error {
t.registerEventCall("OnFileDownloadRequest")
return e.Next()
},
Priority: -99999,
})
t.OnFileTokenRequest().Bind(&hook.Handler[*core.FileTokenRequestEvent]{
Func: func(e *core.FileTokenRequestEvent) error {
t.registerEventCall("OnFileTokenRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAuthRequest().Bind(&hook.Handler[*core.RecordAuthRequestEvent]{
Func: func(e *core.RecordAuthRequestEvent) error {
t.registerEventCall("OnRecordAuthRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAuthWithPasswordRequest().Bind(&hook.Handler[*core.RecordAuthWithPasswordRequestEvent]{
Func: func(e *core.RecordAuthWithPasswordRequestEvent) error {
t.registerEventCall("OnRecordAuthWithPasswordRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAuthWithOAuth2Request().Bind(&hook.Handler[*core.RecordAuthWithOAuth2RequestEvent]{
Func: func(e *core.RecordAuthWithOAuth2RequestEvent) error {
t.registerEventCall("OnRecordAuthWithOAuth2Request")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAuthRefreshRequest().Bind(&hook.Handler[*core.RecordAuthRefreshRequestEvent]{
Func: func(e *core.RecordAuthRefreshRequestEvent) error {
t.registerEventCall("OnRecordAuthRefreshRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordRequestPasswordResetRequest().Bind(&hook.Handler[*core.RecordRequestPasswordResetRequestEvent]{
Func: func(e *core.RecordRequestPasswordResetRequestEvent) error {
t.registerEventCall("OnRecordRequestPasswordResetRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordConfirmPasswordResetRequest().Bind(&hook.Handler[*core.RecordConfirmPasswordResetRequestEvent]{
Func: func(e *core.RecordConfirmPasswordResetRequestEvent) error {
t.registerEventCall("OnRecordConfirmPasswordResetRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordRequestVerificationRequest().Bind(&hook.Handler[*core.RecordRequestVerificationRequestEvent]{
Func: func(e *core.RecordRequestVerificationRequestEvent) error {
t.registerEventCall("OnRecordRequestVerificationRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordConfirmVerificationRequest().Bind(&hook.Handler[*core.RecordConfirmVerificationRequestEvent]{
Func: func(e *core.RecordConfirmVerificationRequestEvent) error {
t.registerEventCall("OnRecordConfirmVerificationRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordRequestEmailChangeRequest().Bind(&hook.Handler[*core.RecordRequestEmailChangeRequestEvent]{
Func: func(e *core.RecordRequestEmailChangeRequestEvent) error {
t.registerEventCall("OnRecordRequestEmailChangeRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordConfirmEmailChangeRequest().Bind(&hook.Handler[*core.RecordConfirmEmailChangeRequestEvent]{
Func: func(e *core.RecordConfirmEmailChangeRequestEvent) error {
t.registerEventCall("OnRecordConfirmEmailChangeRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordRequestOTPRequest().Bind(&hook.Handler[*core.RecordCreateOTPRequestEvent]{
Func: func(e *core.RecordCreateOTPRequestEvent) error {
t.registerEventCall("OnRecordRequestOTPRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordAuthWithOTPRequest().Bind(&hook.Handler[*core.RecordAuthWithOTPRequestEvent]{
Func: func(e *core.RecordAuthWithOTPRequestEvent) error {
t.registerEventCall("OnRecordAuthWithOTPRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordsListRequest().Bind(&hook.Handler[*core.RecordsListRequestEvent]{
Func: func(e *core.RecordsListRequestEvent) error {
t.registerEventCall("OnRecordsListRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordViewRequest().Bind(&hook.Handler[*core.RecordRequestEvent]{
Func: func(e *core.RecordRequestEvent) error {
t.registerEventCall("OnRecordViewRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordCreateRequest().Bind(&hook.Handler[*core.RecordRequestEvent]{
Func: func(e *core.RecordRequestEvent) error {
t.registerEventCall("OnRecordCreateRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordUpdateRequest().Bind(&hook.Handler[*core.RecordRequestEvent]{
Func: func(e *core.RecordRequestEvent) error {
t.registerEventCall("OnRecordUpdateRequest")
return e.Next()
},
Priority: -99999,
})
t.OnRecordDeleteRequest().Bind(&hook.Handler[*core.RecordRequestEvent]{
Func: func(e *core.RecordRequestEvent) error {
t.registerEventCall("OnRecordDeleteRequest")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionsListRequest().Bind(&hook.Handler[*core.CollectionsListRequestEvent]{
Func: func(e *core.CollectionsListRequestEvent) error {
t.registerEventCall("OnCollectionsListRequest")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionViewRequest().Bind(&hook.Handler[*core.CollectionRequestEvent]{
Func: func(e *core.CollectionRequestEvent) error {
t.registerEventCall("OnCollectionViewRequest")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionCreateRequest().Bind(&hook.Handler[*core.CollectionRequestEvent]{
Func: func(e *core.CollectionRequestEvent) error {
t.registerEventCall("OnCollectionCreateRequest")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionUpdateRequest().Bind(&hook.Handler[*core.CollectionRequestEvent]{
Func: func(e *core.CollectionRequestEvent) error {
t.registerEventCall("OnCollectionUpdateRequest")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionDeleteRequest().Bind(&hook.Handler[*core.CollectionRequestEvent]{
Func: func(e *core.CollectionRequestEvent) error {
t.registerEventCall("OnCollectionDeleteRequest")
return e.Next()
},
Priority: -99999,
})
t.OnCollectionsImportRequest().Bind(&hook.Handler[*core.CollectionsImportRequestEvent]{
Func: func(e *core.CollectionsImportRequestEvent) error {
t.registerEventCall("OnCollectionsImportRequest")
return e.Next()
},
Priority: -99999,
})
t.OnBatchRequest().Bind(&hook.Handler[*core.BatchRequestEvent]{
Func: func(e *core.BatchRequestEvent) error {
t.registerEventCall("OnBatchRequest")
return e.Next()
},
Priority: -99999,
})
return t, nil
}
// TempDirClone creates a new temporary directory copy from the
// provided directory path.
//
// It is the caller's responsibility to call `os.RemoveAll(tempDir)`
// when the directory is no longer needed!
func TempDirClone(dirToClone string) (string, error) {
tempDir, err := os.MkdirTemp("", "pb_test_*")
if err != nil {
return "", err
}
// copy everything from testDataDir to tempDir
if err := copyDir(dirToClone, tempDir); err != nil {
return "", err
}
return tempDir, nil
}
// -------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------
func copyDir(src string, dest string) error {
if err := os.MkdirAll(dest, os.ModePerm); err != nil {
return err
}
sourceDir, err := os.Open(src)
if err != nil {
return err
}
defer sourceDir.Close()
items, err := sourceDir.Readdir(-1)
if err != nil {
return err
}
for _, item := range items {
fullSrcPath := filepath.Join(src, item.Name())
fullDestPath := filepath.Join(dest, item.Name())
var copyErr error
if item.IsDir() {
copyErr = copyDir(fullSrcPath, fullDestPath)
} else {
copyErr = copyFile(fullSrcPath, fullDestPath)
}
if copyErr != nil {
return copyErr
}
}
return nil
}
func copyFile(src string, dest string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
destFile, err := os.Create(dest)
if err != nil {
return err
}
defer destFile.Close()
if _, err := io.Copy(destFile, srcFile); err != nil {
return err
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/test_email_send.go | forms/test_email_send.go | package forms
import (
"errors"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/types"
)
const (
TestTemplateVerification = "verification"
TestTemplatePasswordReset = "password-reset"
TestTemplateEmailChange = "email-change"
TestTemplateOTP = "otp"
TestTemplateAuthAlert = "login-alert"
)
// TestEmailSend is a email template test request form.
type TestEmailSend struct {
app core.App
Email string `form:"email" json:"email"`
Template string `form:"template" json:"template"`
Collection string `form:"collection" json:"collection"` // optional, fallbacks to _superusers
}
// NewTestEmailSend creates and initializes new TestEmailSend form.
func NewTestEmailSend(app core.App) *TestEmailSend {
return &TestEmailSend{app: app}
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *TestEmailSend) Validate() error {
return validation.ValidateStruct(form,
validation.Field(
&form.Collection,
validation.Length(1, 255),
validation.By(form.checkAuthCollection),
),
validation.Field(
&form.Email,
validation.Required,
validation.Length(1, 255),
is.EmailFormat,
),
validation.Field(
&form.Template,
validation.Required,
validation.In(
TestTemplateVerification,
TestTemplatePasswordReset,
TestTemplateEmailChange,
TestTemplateOTP,
TestTemplateAuthAlert,
),
),
)
}
func (form *TestEmailSend) checkAuthCollection(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
c, _ := form.app.FindCollectionByNameOrId(v)
if c == nil || !c.IsAuth() {
return validation.NewError("validation_invalid_auth_collection", "Must be a valid auth collection id or name.")
}
return nil
}
// Submit validates and sends a test email to the form.Email address.
func (form *TestEmailSend) Submit() error {
if err := form.Validate(); err != nil {
return err
}
collectionIdOrName := form.Collection
if collectionIdOrName == "" {
collectionIdOrName = core.CollectionNameSuperusers
}
collection, err := form.app.FindCollectionByNameOrId(collectionIdOrName)
if err != nil {
return err
}
record := core.NewRecord(collection)
for _, field := range collection.Fields {
if field.GetHidden() {
continue
}
record.Set(field.GetName(), "__pb_test_"+field.GetName()+"__")
}
record.RefreshTokenKey()
record.SetEmail(form.Email)
switch form.Template {
case TestTemplateVerification:
return mails.SendRecordVerification(form.app, record)
case TestTemplatePasswordReset:
return mails.SendRecordPasswordReset(form.app, record)
case TestTemplateEmailChange:
return mails.SendRecordChangeEmail(form.app, record, form.Email)
case TestTemplateOTP:
return mails.SendRecordOTP(form.app, record, "_PB_TEST_OTP_ID_", "123456")
case TestTemplateAuthAlert:
testEvent := types.NowDateTime().String() + " - TEST_IP TEST_USER_AGENT"
return mails.SendRecordAuthAlert(form.app, record, testEvent)
default:
return errors.New("unknown template " + form.Template)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/test_email_send_test.go | forms/test_email_send_test.go | package forms_test
import (
"fmt"
"strings"
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tests"
)
func TestEmailSendValidateAndSubmit(t *testing.T) {
t.Parallel()
scenarios := []struct {
template string
email string
collection string
expectedErrors []string
}{
{"", "", "", []string{"template", "email"}},
{"invalid", "test@example.com", "", []string{"template"}},
{forms.TestTemplateVerification, "invalid", "", []string{"email"}},
{forms.TestTemplateVerification, "test@example.com", "invalid", []string{"collection"}},
{forms.TestTemplateVerification, "test@example.com", "demo1", []string{"collection"}},
{forms.TestTemplateVerification, "test@example.com", "users", nil},
{forms.TestTemplatePasswordReset, "test@example.com", "", nil},
{forms.TestTemplateEmailChange, "test@example.com", "", nil},
{forms.TestTemplateOTP, "test@example.com", "", nil},
{forms.TestTemplateAuthAlert, "test@example.com", "", nil},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.template), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
form := forms.NewTestEmailSend(app)
form.Email = s.email
form.Template = s.template
form.Collection = s.collection
result := form.Submit()
// parse errors
errs, ok := result.(validation.Errors)
if !ok && result != nil {
t.Fatalf("Failed to parse errors %v", result)
}
// check errors
if len(errs) > len(s.expectedErrors) {
t.Fatalf("Expected error keys %v, got %v", s.expectedErrors, errs)
}
for _, k := range s.expectedErrors {
if _, ok := errs[k]; !ok {
t.Fatalf("Missing expected error key %q in %v", k, errs)
}
}
expectedEmails := 1
if len(s.expectedErrors) > 0 {
expectedEmails = 0
}
if app.TestMailer.TotalSend() != expectedEmails {
t.Fatalf("Expected %d email(s) to be sent, got %d", expectedEmails, app.TestMailer.TotalSend())
}
if len(s.expectedErrors) > 0 {
return
}
var expectedContent string
switch s.template {
case forms.TestTemplatePasswordReset:
expectedContent = "Reset password"
case forms.TestTemplateEmailChange:
expectedContent = "Confirm new email"
case forms.TestTemplateVerification:
expectedContent = "Verify"
case forms.TestTemplateOTP:
expectedContent = "one-time password"
case forms.TestTemplateAuthAlert:
expectedContent = "from a new location"
default:
expectedContent = "__UNKNOWN_TEMPLATE__"
}
if !strings.Contains(app.TestMailer.LastMessage().HTML, expectedContent) {
t.Errorf("Expected the email to contains %q, got\n%v", expectedContent, app.TestMailer.LastMessage().HTML)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/record_upsert.go | forms/record_upsert.go | package forms
import (
"context"
"errors"
"fmt"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
const (
accessLevelDefault = iota
accessLevelManager
accessLevelSuperuser
)
type RecordUpsert struct {
ctx context.Context
app core.App
record *core.Record
accessLevel int
// extra password fields
disablePasswordValidations bool
password string
passwordConfirm string
oldPassword string
}
// NewRecordUpsert creates a new [RecordUpsert] form from the provided [core.App] and [core.Record] instances
// (for create you could pass a pointer to an empty Record - core.NewRecord(collection)).
func NewRecordUpsert(app core.App, record *core.Record) *RecordUpsert {
form := &RecordUpsert{
ctx: context.Background(),
app: app,
record: record,
}
return form
}
// SetContext assigns ctx as context of the current form.
func (form *RecordUpsert) SetContext(ctx context.Context) {
form.ctx = ctx
}
// SetApp replaces the current form app instance.
//
// This could be used for example if you want to change at later stage
// before submission to change from regular -> transactional app instance.
func (form *RecordUpsert) SetApp(app core.App) {
form.app = app
}
// SetRecord replaces the current form record instance.
func (form *RecordUpsert) SetRecord(record *core.Record) {
form.record = record
}
// ResetAccess resets the form access level to the accessLevelDefault.
func (form *RecordUpsert) ResetAccess() {
form.accessLevel = accessLevelDefault
}
// GrantManagerAccess updates the form access level to "manager" allowing
// directly changing some system record fields (often used with auth collection records).
func (form *RecordUpsert) GrantManagerAccess() {
form.accessLevel = accessLevelManager
}
// GrantSuperuserAccess updates the form access level to "superuser" allowing
// directly changing all system record fields, including those marked as "Hidden".
func (form *RecordUpsert) GrantSuperuserAccess() {
form.accessLevel = accessLevelSuperuser
}
// HasManageAccess reports whether the form has "manager" or "superuser" level access.
func (form *RecordUpsert) HasManageAccess() bool {
return form.accessLevel == accessLevelManager || form.accessLevel == accessLevelSuperuser
}
// Load loads the provided data into the form and the related record.
func (form *RecordUpsert) Load(data map[string]any) {
excludeFields := []string{core.FieldNameExpand}
isAuth := form.record.Collection().IsAuth()
// load the special auth form fields
if isAuth {
if v, ok := data["password"]; ok {
form.password = cast.ToString(v)
}
if v, ok := data["passwordConfirm"]; ok {
form.passwordConfirm = cast.ToString(v)
}
if v, ok := data["oldPassword"]; ok {
form.oldPassword = cast.ToString(v)
}
excludeFields = append(excludeFields, "passwordConfirm", "oldPassword") // skip non-schema password fields
}
for k, v := range data {
if slices.Contains(excludeFields, k) {
continue
}
// set only known collection fields
field := form.record.SetIfFieldExists(k, v)
// restore original value if hidden field (with exception of the auth "password")
//
// note: this is an extra measure against loading hidden fields
// but usually is not used by the default route handlers since
// they filter additionally the data before calling Load
if form.accessLevel != accessLevelSuperuser && field != nil && field.GetHidden() && (!isAuth || field.GetName() != core.FieldNamePassword) {
form.record.SetRaw(field.GetName(), form.record.Original().GetRaw(field.GetName()))
}
}
}
func (form *RecordUpsert) validateFormFields() error {
isAuth := form.record.Collection().IsAuth()
if !isAuth {
return nil
}
form.syncPasswordFields()
isNew := form.record.IsNew()
original := form.record.Original()
validateData := map[string]any{
"email": form.record.Email(),
"verified": form.record.Verified(),
"password": form.password,
"passwordConfirm": form.passwordConfirm,
"oldPassword": form.oldPassword,
}
return validation.Validate(validateData,
validation.Map(
validation.Key(
"email",
// don't allow direct email updates if the form doesn't have manage access permissions
// (aka. allow only admin or authorized auth models to directly update the field)
validation.When(
!isNew && !form.HasManageAccess(),
validation.By(validators.Equal(original.Email())),
),
),
validation.Key(
"verified",
// don't allow changing verified if the form doesn't have manage access permissions
// (aka. allow only admin or authorized auth models to directly change the field)
validation.When(
!form.HasManageAccess(),
validation.By(validators.Equal(original.Verified())),
),
),
validation.Key(
"password",
validation.When(
!form.disablePasswordValidations && (isNew || form.passwordConfirm != "" || form.oldPassword != ""),
validation.Required,
),
),
validation.Key(
"passwordConfirm",
validation.When(
!form.disablePasswordValidations && (isNew || form.password != "" || form.oldPassword != ""),
validation.Required,
),
validation.When(!form.disablePasswordValidations, validation.By(validators.Equal(form.password))),
),
validation.Key(
"oldPassword",
// require old password only on update when:
// - form.HasManageAccess() is not satisfied
// - changing the existing password
validation.When(
!form.disablePasswordValidations && !isNew && !form.HasManageAccess() && (form.password != "" || form.passwordConfirm != ""),
validation.Required,
validation.By(form.checkOldPassword),
),
),
),
)
}
func (form *RecordUpsert) checkOldPassword(value any) error {
v, ok := value.(string)
if !ok {
return validators.ErrUnsupportedValueType
}
if !form.record.Original().ValidatePassword(v) {
return validation.NewError("validation_invalid_old_password", "Missing or invalid old password.")
}
return nil
}
// Deprecated: It was previously used as part of the record create action but it is not needed anymore and will be removed in the future.
//
// DrySubmit performs a temp form submit within a transaction and reverts it at the end.
// For actual record persistence, check the [RecordUpsert.Submit()] method.
//
// This method doesn't perform validations, handle file uploads/deletes or trigger app save events!
func (form *RecordUpsert) DrySubmit(callback func(txApp core.App, drySavedRecord *core.Record) error) error {
isNew := form.record.IsNew()
clone := form.record.Clone()
// set an id if it doesn't have already
// (the value doesn't matter; it is used only during the manual delete/update rollback)
if clone.IsNew() && clone.Id == "" {
clone.Id = "_temp_" + security.PseudorandomString(15)
}
app := form.app.UnsafeWithoutHooks()
isTransactional := app.IsTransactional()
if !isTransactional {
return app.RunInTransaction(func(txApp core.App) error {
tx, ok := txApp.DB().(*dbx.Tx)
if !ok {
return errors.New("failed to get transaction db")
}
defer tx.Rollback()
if err := txApp.SaveNoValidateWithContext(form.ctx, clone); err != nil {
return validators.NormalizeUniqueIndexError(err, clone.Collection().Name, clone.Collection().Fields.FieldNames())
}
if callback != nil {
return callback(txApp, clone)
}
return nil
})
}
// already in a transaction
// (manual rollback to avoid starting another transaction)
// ---------------------------------------------------------------
err := app.SaveNoValidateWithContext(form.ctx, clone)
if err != nil {
return validators.NormalizeUniqueIndexError(err, clone.Collection().Name, clone.Collection().Fields.FieldNames())
}
manualRollback := func() error {
if isNew {
err = app.DeleteWithContext(form.ctx, clone)
if err != nil {
return fmt.Errorf("failed to rollback dry submit created record: %w", err)
}
} else {
clone.Load(clone.Original().FieldsData())
err = app.SaveNoValidateWithContext(form.ctx, clone)
if err != nil {
return fmt.Errorf("failed to rollback dry submit updated record: %w", err)
}
}
return nil
}
if callback != nil {
return errors.Join(callback(app, clone), manualRollback())
}
return manualRollback()
}
// Submit validates the form specific validations and attempts to save the form record.
func (form *RecordUpsert) Submit() error {
err := form.validateFormFields()
if err != nil {
return err
}
// run record validations and persist in db
return form.app.SaveWithContext(form.ctx, form.record)
}
// syncPasswordFields syncs the form's auth password fields with their
// corresponding record field values.
//
// This could be useful in case the password fields were programmatically set
// directly by modifying the related record model.
func (form *RecordUpsert) syncPasswordFields() {
if !form.record.Collection().IsAuth() {
return // not an auth collection
}
form.disablePasswordValidations = false
rawPassword := form.record.GetRaw(core.FieldNamePassword)
if v, ok := rawPassword.(*core.PasswordFieldValue); ok && v != nil {
if
// programmatically set custom plain password value
(v.Plain != "" && v.Plain != form.password) ||
// random generated password for new record
(v.Plain == "" && v.Hash != "" && form.record.IsNew()) {
form.disablePasswordValidations = true
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/test_s3_filesystem.go | forms/test_s3_filesystem.go | package forms
import (
"errors"
"fmt"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/security"
)
const (
s3FilesystemStorage = "storage"
s3FilesystemBackups = "backups"
)
// TestS3Filesystem defines a S3 filesystem connection test.
type TestS3Filesystem struct {
app core.App
// The name of the filesystem - storage or backups
Filesystem string `form:"filesystem" json:"filesystem"`
}
// NewTestS3Filesystem creates and initializes new TestS3Filesystem form.
func NewTestS3Filesystem(app core.App) *TestS3Filesystem {
return &TestS3Filesystem{app: app}
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *TestS3Filesystem) Validate() error {
return validation.ValidateStruct(form,
validation.Field(
&form.Filesystem,
validation.Required,
validation.In(s3FilesystemStorage, s3FilesystemBackups),
),
)
}
// Submit validates and performs a S3 filesystem connection test.
func (form *TestS3Filesystem) Submit() error {
if err := form.Validate(); err != nil {
return err
}
var s3Config core.S3Config
if form.Filesystem == s3FilesystemBackups {
s3Config = form.app.Settings().Backups.S3
} else {
s3Config = form.app.Settings().S3
}
if !s3Config.Enabled {
return errors.New("S3 storage filesystem is not enabled")
}
fsys, err := filesystem.NewS3(
s3Config.Bucket,
s3Config.Region,
s3Config.Endpoint,
s3Config.AccessKey,
s3Config.Secret,
s3Config.ForcePathStyle,
)
if err != nil {
return fmt.Errorf("failed to initialize the S3 filesystem: %w", err)
}
defer fsys.Close()
testPrefix := "pb_settings_test_" + security.PseudorandomString(5)
testFileKey := testPrefix + "/test.txt"
// try to upload a test file
if err := fsys.Upload([]byte("test"), testFileKey); err != nil {
return fmt.Errorf("failed to upload a test file: %w", err)
}
// test prefix deletion (ensures that both bucket list and delete works)
if errs := fsys.DeletePrefix(testPrefix); len(errs) > 0 {
return fmt.Errorf("failed to delete a test file: %w", errs[0])
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/test_s3_filesystem_test.go | forms/test_s3_filesystem_test.go | package forms_test
import (
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tests"
)
func TestS3FilesystemValidate(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
filesystem string
expectedErrors []string
}{
{
"empty filesystem",
"",
[]string{"filesystem"},
},
{
"invalid filesystem",
"something",
[]string{"filesystem"},
},
{
"backups filesystem",
"backups",
[]string{},
},
{
"storage filesystem",
"storage",
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
form := forms.NewTestS3Filesystem(app)
form.Filesystem = s.filesystem
result := form.Validate()
// parse errors
errs, ok := result.(validation.Errors)
if !ok && result != nil {
t.Fatalf("Failed to parse errors %v", result)
}
// check errors
if len(errs) > len(s.expectedErrors) {
t.Fatalf("Expected error keys %v, got %v", s.expectedErrors, errs)
}
for _, k := range s.expectedErrors {
if _, ok := errs[k]; !ok {
t.Fatalf("Missing expected error key %q in %v", k, errs)
}
}
})
}
}
func TestS3FilesystemSubmitFailure(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
// check if validate was called
{
form := forms.NewTestS3Filesystem(app)
form.Filesystem = ""
result := form.Submit()
if result == nil {
t.Fatal("Expected error, got nil")
}
if _, ok := result.(validation.Errors); !ok {
t.Fatalf("Expected validation.Error, got %v", result)
}
}
// check with valid storage and disabled s3
{
form := forms.NewTestS3Filesystem(app)
form.Filesystem = "storage"
result := form.Submit()
if result == nil {
t.Fatal("Expected error, got nil")
}
if _, ok := result.(validation.Error); ok {
t.Fatalf("Didn't expect validation.Error, got %v", result)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/apple_client_secret_create_test.go | forms/apple_client_secret_create_test.go | package forms_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/json"
"encoding/pem"
"testing"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tests"
)
func TestAppleClientSecretCreateValidateAndSubmit(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
encodedKey, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatal(err)
}
privatePem := pem.EncodeToMemory(
&pem.Block{
Type: "PRIVATE KEY",
Bytes: encodedKey,
},
)
scenarios := []struct {
name string
formData map[string]any
expectError bool
}{
{
"empty data",
map[string]any{},
true,
},
{
"invalid data",
map[string]any{
"clientId": "",
"teamId": "123456789",
"keyId": "123456789",
"privateKey": "-----BEGIN PRIVATE KEY----- invalid -----END PRIVATE KEY-----",
"duration": -1,
},
true,
},
{
"valid data",
map[string]any{
"clientId": "123",
"teamId": "1234567890",
"keyId": "1234567891",
"privateKey": string(privatePem),
"duration": 1,
},
false,
},
}
for _, s := range scenarios {
form := forms.NewAppleClientSecretCreate(app)
rawData, marshalErr := json.Marshal(s.formData)
if marshalErr != nil {
t.Errorf("[%s] Failed to marshalize the scenario data: %v", s.name, marshalErr)
continue
}
// load data
loadErr := json.Unmarshal(rawData, form)
if loadErr != nil {
t.Errorf("[%s] Failed to load form data: %v", s.name, loadErr)
continue
}
secret, err := form.Submit()
hasErr := err != nil
if hasErr != s.expectError {
t.Errorf("[%s] Expected hasErr %v, got %v (%v)", s.name, s.expectError, hasErr, err)
}
if hasErr {
continue
}
if secret == "" {
t.Errorf("[%s] Expected non-empty secret", s.name)
}
claims := jwt.MapClaims{}
token, _, err := jwt.NewParser().ParseUnverified(secret, claims)
if err != nil {
t.Errorf("[%s] Failed to parse token: %v", s.name, err)
}
if alg := token.Header["alg"]; alg != "ES256" {
t.Errorf("[%s] Expected %q alg header, got %q", s.name, "ES256", alg)
}
if kid := token.Header["kid"]; kid != form.KeyId {
t.Errorf("[%s] Expected %q kid header, got %q", s.name, form.KeyId, kid)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/record_upsert_test.go | forms/record_upsert_test.go | package forms_test
import (
"bytes"
"encoding/json"
"errors"
"maps"
"os"
"path/filepath"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/filesystem"
)
func TestRecordUpsertLoad(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1Col, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
usersCol, err := testApp.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
data map[string]any
record *core.Record
managerAccessLevel bool
superuserAccessLevel bool
expected []string
notExpected []string
}{
{
name: "base collection record",
data: map[string]any{
"text": "test_text",
"custom": "123", // should be ignored
"number": "456", // should be normalized by the setter
"select_many+": []string{"optionB", "optionC"}, // test modifier fields
"created": "2022-01:01 10:00:00.000Z", // should be ignored
// ignore special auth fields
"oldPassword": "123",
"password": "456",
"passwordConfirm": "789",
},
record: core.NewRecord(demo1Col),
expected: []string{
`"text":"test_text"`,
`"number":456`,
`"select_many":["optionB","optionC"]`,
`"created":""`,
`"updated":""`,
`"json":null`,
},
notExpected: []string{
`"custom"`,
`"password"`,
`"oldPassword"`,
`"passwordConfirm"`,
`"select_many-"`,
`"select_many+"`,
},
},
{
name: "auth collection record",
data: map[string]any{
"email": "test@example.com",
// special auth fields
"oldPassword": "123",
"password": "456",
"passwordConfirm": "789",
},
record: core.NewRecord(usersCol),
expected: []string{
`"email":"test@example.com"`,
`"password":"456"`,
},
notExpected: []string{
`"oldPassword"`,
`"passwordConfirm"`,
},
},
{
name: "hidden fields (manager)",
data: map[string]any{
"email": "test@example.com",
"tokenKey": "abc", // should be ignored
// special auth fields
"password": "456",
"oldPassword": "123",
"passwordConfirm": "789",
},
managerAccessLevel: true,
record: core.NewRecord(usersCol),
expected: []string{
`"email":"test@example.com"`,
`"tokenKey":""`,
`"password":"456"`,
},
notExpected: []string{
`"oldPassword"`,
`"passwordConfirm"`,
},
},
{
name: "hidden fields (superuser)",
data: map[string]any{
"email": "test@example.com",
"tokenKey": "abc",
// special auth fields
"password": "456",
"oldPassword": "123",
"passwordConfirm": "789",
},
superuserAccessLevel: true,
record: core.NewRecord(usersCol),
expected: []string{
`"email":"test@example.com"`,
`"tokenKey":"abc"`,
`"password":"456"`,
},
notExpected: []string{
`"oldPassword"`,
`"passwordConfirm"`,
},
},
{
name: "with file field",
data: map[string]any{
"file_one": file,
"url": file, // should be ignored for non-file fields
},
record: core.NewRecord(demo1Col),
expected: []string{
`"file_one":{`,
`"originalName":"test.txt"`,
`"url":""`,
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
form := forms.NewRecordUpsert(testApp, s.record)
if s.managerAccessLevel {
form.GrantManagerAccess()
}
if s.superuserAccessLevel {
form.GrantSuperuserAccess()
}
// ensure that the form access level was updated
if !form.HasManageAccess() && (s.superuserAccessLevel || s.managerAccessLevel) {
t.Fatalf("Expected the form to have manage access level (manager or superuser)")
}
form.Load(s.data)
loaded := map[string]any{}
maps.Copy(loaded, s.record.FieldsData())
maps.Copy(loaded, s.record.CustomData())
raw, err := json.Marshal(loaded)
if err != nil {
t.Fatalf("Failed to serialize data: %v", err)
}
rawStr := string(raw)
for _, str := range s.expected {
if !strings.Contains(rawStr, str) {
t.Fatalf("Couldn't find %q in \n%v", str, rawStr)
}
}
for _, str := range s.notExpected {
if strings.Contains(rawStr, str) {
t.Fatalf("Didn't expect %q in \n%v", str, rawStr)
}
}
})
}
}
func TestRecordUpsertDrySubmitFailure(t *testing.T) {
runTest := func(t *testing.T, testApp core.App) {
col, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
originalId := "imy661ixudk5izi"
record, err := testApp.FindRecordById(col, originalId)
if err != nil {
t.Fatal(err)
}
oldRaw, err := json.Marshal(record)
if err != nil {
t.Fatal(err)
}
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(testApp, record)
form.Load(map[string]any{
"text": "test_update",
"file_one": file,
"select_one": "!invalid", // should be allowed even if invalid since validations are not executed
})
calls := ""
testApp.OnRecordValidate(col.Name).BindFunc(func(e *core.RecordEvent) error {
calls += "a" // shouldn't be called
return e.Next()
})
result := form.DrySubmit(func(txApp core.App, drySavedRecord *core.Record) error {
calls += "b"
return errors.New("error...")
})
if result == nil {
t.Fatal("Expected DrySubmit error, got nil")
}
if calls != "b" {
t.Fatalf("Expected calls %q, got %q", "ab", calls)
}
// refresh the record to ensure that the changes weren't persisted
record, err = testApp.FindRecordById(col, originalId)
if err != nil {
t.Fatalf("Expected record with the original id %q to exist, got\n%v", originalId, record.PublicExport())
}
newRaw, err := json.Marshal(record)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(oldRaw, newRaw) {
t.Fatalf("Expected record\n%s\ngot\n%s", oldRaw, newRaw)
}
testFilesCount(t, testApp, record, 0)
}
t.Run("without parent transaction", func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
runTest(t, testApp)
})
t.Run("with parent transaction", func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
testApp.RunInTransaction(func(txApp core.App) error {
runTest(t, txApp)
return nil
})
})
}
func TestRecordUpsertDrySubmitCreateSuccess(t *testing.T) {
runTest := func(t *testing.T, testApp core.App) {
col, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
record := core.NewRecord(col)
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(testApp, record)
form.Load(map[string]any{
"id": "test",
"text": "test_update",
"file_one": file,
"select_one": "!invalid", // should be allowed even if invalid since validations are not executed
})
calls := ""
testApp.OnRecordValidate(col.Name).BindFunc(func(e *core.RecordEvent) error {
calls += "a" // shouldn't be called
return e.Next()
})
result := form.DrySubmit(func(txApp core.App, drySavedRecord *core.Record) error {
calls += "b"
return nil
})
if result != nil {
t.Fatalf("Expected DrySubmit success, got error: %v", result)
}
if calls != "b" {
t.Fatalf("Expected calls %q, got %q", "ab", calls)
}
// refresh the record to ensure that the changes weren't persisted
_, err = testApp.FindRecordById(col, record.Id)
if err == nil {
t.Fatal("Expected the created record to be deleted")
}
testFilesCount(t, testApp, record, 0)
}
t.Run("without parent transaction", func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
runTest(t, testApp)
})
t.Run("with parent transaction", func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
testApp.RunInTransaction(func(txApp core.App) error {
runTest(t, txApp)
return nil
})
})
}
func TestRecordUpsertDrySubmitUpdateSuccess(t *testing.T) {
runTest := func(t *testing.T, testApp core.App) {
col, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
record, err := testApp.FindRecordById(col, "imy661ixudk5izi")
if err != nil {
t.Fatal(err)
}
oldRaw, err := json.Marshal(record)
if err != nil {
t.Fatal(err)
}
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(testApp, record)
form.Load(map[string]any{
"text": "test_update",
"file_one": file,
})
calls := ""
testApp.OnRecordValidate(col.Name).BindFunc(func(e *core.RecordEvent) error {
calls += "a" // shouldn't be called
return e.Next()
})
result := form.DrySubmit(func(txApp core.App, drySavedRecord *core.Record) error {
calls += "b"
return nil
})
if result != nil {
t.Fatalf("Expected DrySubmit success, got error: %v", result)
}
if calls != "b" {
t.Fatalf("Expected calls %q, got %q", "ab", calls)
}
// refresh the record to ensure that the changes weren't persisted
record, err = testApp.FindRecordById(col, record.Id)
if err != nil {
t.Fatal(err)
}
newRaw, err := json.Marshal(record)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(oldRaw, newRaw) {
t.Fatalf("Expected record\n%s\ngot\n%s", oldRaw, newRaw)
}
testFilesCount(t, testApp, record, 0)
}
t.Run("without parent transaction", func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
runTest(t, testApp)
})
t.Run("with parent transaction", func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
testApp.RunInTransaction(func(txApp core.App) error {
runTest(t, txApp)
return nil
})
})
}
func TestRecordUpsertSubmitValidations(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo2Col, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
t.Fatal(err)
}
demo2Rec, err := app.FindRecordById(demo2Col, "llvuca81nly1qls")
if err != nil {
t.Fatal(err)
}
usersCol, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
userRec, err := app.FindRecordById(usersCol, "4q1xlclmfloku33")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
record *core.Record
data map[string]any
managerAccess bool
expectedErrors []string
}{
// base
{
name: "new base collection record with empty data",
record: core.NewRecord(demo2Col),
data: map[string]any{},
expectedErrors: []string{"title"},
},
{
name: "new base collection record with invalid data",
record: core.NewRecord(demo2Col),
data: map[string]any{
"title": "",
// should be ignored
"custom": "abc",
"oldPassword": "123",
"password": "456",
"passwordConfirm": "789",
},
expectedErrors: []string{"title"},
},
{
name: "new base collection record with valid data",
record: core.NewRecord(demo2Col),
data: map[string]any{
"title": "abc",
// should be ignored
"custom": "abc",
"oldPassword": "123",
"password": "456",
"passwordConfirm": "789",
},
expectedErrors: []string{},
},
{
name: "existing base collection record with empty data",
record: demo2Rec,
data: map[string]any{},
expectedErrors: []string{},
},
{
name: "existing base collection record with invalid data",
record: demo2Rec,
data: map[string]any{
"title": "",
},
expectedErrors: []string{"title"},
},
{
name: "existing base collection record with valid data",
record: demo2Rec,
data: map[string]any{
"title": "abc",
},
expectedErrors: []string{},
},
// auth
{
name: "new auth collection record with empty data",
record: core.NewRecord(usersCol),
data: map[string]any{},
expectedErrors: []string{"password", "passwordConfirm"},
},
{
name: "new auth collection record with invalid record and invalid form data (without manager acess)",
record: core.NewRecord(usersCol),
data: map[string]any{
"verified": true,
"emailVisibility": true,
"email": "test@example.com",
"password": "456",
"passwordConfirm": "789",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
"oldPassword": "123",
},
// fail the form validator
expectedErrors: []string{"verified", "passwordConfirm"},
},
{
name: "new auth collection record with invalid record and valid form data (without manager acess)",
record: core.NewRecord(usersCol),
data: map[string]any{
"verified": false,
"emailVisibility": true,
"email": "test@example.com",
"password": "456",
"passwordConfirm": "456",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
"oldPassword": "123",
},
// fail the record fields validator
expectedErrors: []string{"password", "username"},
},
{
name: "new auth collection record with invalid record and invalid form data (with manager acess)",
record: core.NewRecord(usersCol),
managerAccess: true,
data: map[string]any{
"verified": true,
"emailVisibility": true,
"email": "test@example.com",
"password": "456",
"passwordConfirm": "789",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
"oldPassword": "123",
},
// fail the form validator
expectedErrors: []string{"passwordConfirm"},
},
{
name: "new auth collection record with invalid record and valid form data (with manager acess)",
record: core.NewRecord(usersCol),
managerAccess: true,
data: map[string]any{
"verified": true,
"emailVisibility": true,
"email": "test@example.com",
"password": "456",
"passwordConfirm": "456",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
"oldPassword": "123",
},
// fail the record fields validator
expectedErrors: []string{"password", "username"},
},
{
name: "new auth collection record with valid data",
record: core.NewRecord(usersCol),
data: map[string]any{
"emailVisibility": true,
"email": "test_new@example.com",
"password": "1234567890",
"passwordConfirm": "1234567890",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
"oldPassword": "123",
},
expectedErrors: []string{},
},
{
name: "new auth collection record with valid data and duplicated email",
record: core.NewRecord(usersCol),
data: map[string]any{
"email": "test@example.com",
"password": "1234567890",
"passwordConfirm": "1234567890",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
"oldPassword": "123",
},
// fail the unique db validator
expectedErrors: []string{"email"},
},
{
name: "existing auth collection record with empty data",
record: userRec,
data: map[string]any{},
expectedErrors: []string{},
},
{
name: "existing auth collection record with invalid record data and invalid form data (without manager access)",
record: userRec,
data: map[string]any{
"verified": true,
"email": "test_new@example.com", // not allowed to change
"oldPassword": "123",
"password": "456",
"passwordConfirm": "789",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
},
// fail form validator
expectedErrors: []string{"verified", "email", "oldPassword", "passwordConfirm"},
},
{
name: "existing auth collection record with invalid record data and valid form data (without manager access)",
record: userRec,
data: map[string]any{
"oldPassword": "1234567890",
"password": "12345678901",
"passwordConfirm": "12345678901",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
},
// fail record fields validator
expectedErrors: []string{"username"},
},
{
name: "existing auth collection record with invalid record data and invalid form data (with manager access)",
record: userRec,
managerAccess: true,
data: map[string]any{
"verified": true,
"email": "test_new@example.com",
"oldPassword": "123", // should be ignored
"password": "456",
"passwordConfirm": "789",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
},
// fail form validator
expectedErrors: []string{"passwordConfirm"},
},
{
name: "existing auth collection record with invalid record data and valid form data (with manager access)",
record: userRec,
managerAccess: true,
data: map[string]any{
"verified": true,
"email": "test_new@example.com",
"oldPassword": "1234567890",
"password": "12345678901",
"passwordConfirm": "12345678901",
"username": "!invalid",
// should be ignored (custom or hidden fields)
"tokenKey": strings.Repeat("a", 2),
"custom": "abc",
},
// fail record fields validator
expectedErrors: []string{"username"},
},
{
name: "existing auth collection record with base valid data",
record: userRec,
data: map[string]any{
"name": "test",
},
expectedErrors: []string{},
},
{
name: "existing auth collection record with valid password and invalid oldPassword data",
record: userRec,
data: map[string]any{
"name": "test",
"oldPassword": "invalid",
"password": "1234567890",
"passwordConfirm": "1234567890",
},
expectedErrors: []string{"oldPassword"},
},
{
name: "existing auth collection record with valid password data",
record: userRec,
data: map[string]any{
"name": "test",
"oldPassword": "1234567890",
"password": "0987654321",
"passwordConfirm": "0987654321",
},
expectedErrors: []string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
form := forms.NewRecordUpsert(testApp, s.record.Original())
if s.managerAccess {
form.GrantManagerAccess()
}
form.Load(s.data)
result := form.Submit()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestRecordUpsertSubmitFailure(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
col, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
record, err := testApp.FindRecordById(col, "imy661ixudk5izi")
if err != nil {
t.Fatal(err)
}
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(testApp, record)
form.Load(map[string]any{
"text": "test_update",
"file_one": file,
"select_one": "invalid",
})
validateCalls := 0
testApp.OnRecordValidate(col.Name).BindFunc(func(e *core.RecordEvent) error {
validateCalls++
return e.Next()
})
result := form.Submit()
if result == nil {
t.Fatal("Expected Submit error, got nil")
}
if validateCalls != 1 {
t.Fatalf("Expected validateCalls %d, got %d", 1, validateCalls)
}
// refresh the record to ensure that the changes weren't persisted
record, err = testApp.FindRecordById(col, record.Id)
if err != nil {
t.Fatal(err)
}
if v := record.GetString("text"); v == "test_update" {
t.Fatalf("Expected record.text to remain the same, got %q", v)
}
if v := record.GetString("select_one"); v != "" {
t.Fatalf("Expected record.select_one to remain the same, got %q", v)
}
if v := record.GetString("file_one"); v != "" {
t.Fatalf("Expected record.file_one to remain the same, got %q", v)
}
testFilesCount(t, testApp, record, 0)
}
func TestRecordUpsertSubmitSuccess(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
col, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
record, err := testApp.FindRecordById(col, "imy661ixudk5izi")
if err != nil {
t.Fatal(err)
}
file, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
form := forms.NewRecordUpsert(testApp, record)
form.Load(map[string]any{
"text": "test_update",
"file_one": file,
"select_one": "optionC",
})
validateCalls := 0
testApp.OnRecordValidate(col.Name).BindFunc(func(e *core.RecordEvent) error {
validateCalls++
return e.Next()
})
result := form.Submit()
if result != nil {
t.Fatalf("Expected Submit success, got error: %v", result)
}
if validateCalls != 1 {
t.Fatalf("Expected validateCalls %d, got %d", 1, validateCalls)
}
// refresh the record to ensure that the changes were persisted
record, err = testApp.FindRecordById(col, record.Id)
if err != nil {
t.Fatal(err)
}
if v := record.GetString("text"); v != "test_update" {
t.Fatalf("Expected record.text %q, got %q", "test_update", v)
}
if v := record.GetString("select_one"); v != "optionC" {
t.Fatalf("Expected record.select_one %q, got %q", "optionC", v)
}
if v := record.GetString("file_one"); v != file.Name {
t.Fatalf("Expected record.file_one %q, got %q", file.Name, v)
}
testFilesCount(t, testApp, record, 2) // the file + attrs
}
func TestRecordUpsertPasswordsSync(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
users, err := testApp.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
t.Run("new user without password", func(t *testing.T) {
record := core.NewRecord(users)
form := forms.NewRecordUpsert(testApp, record)
err := form.Submit()
tests.TestValidationErrors(t, err, []string{"password", "passwordConfirm"})
})
t.Run("new user with manual password", func(t *testing.T) {
record := core.NewRecord(users)
form := forms.NewRecordUpsert(testApp, record)
record.SetPassword("1234567890")
err := form.Submit()
if err != nil {
t.Fatalf("Expected no errors, got %v", err)
}
})
t.Run("new user with random password", func(t *testing.T) {
record := core.NewRecord(users)
form := forms.NewRecordUpsert(testApp, record)
record.SetRandomPassword()
err := form.Submit()
if err != nil {
t.Fatalf("Expected no errors, got %v", err)
}
})
t.Run("update user with no password change", func(t *testing.T) {
record, err := testApp.FindAuthRecordByEmail(users, "test@example.com")
if err != nil {
t.Fatal(err)
}
oldHash := record.GetString("password:hash")
form := forms.NewRecordUpsert(testApp, record)
err = form.Submit()
if err != nil {
t.Fatalf("Expected no errors, got %v", err)
}
newHash := record.GetString("password:hash")
if newHash == "" || newHash != oldHash {
t.Fatal("Expected no password change")
}
})
t.Run("update user with manual password change", func(t *testing.T) {
record, err := testApp.FindAuthRecordByEmail(users, "test@example.com")
if err != nil {
t.Fatal(err)
}
oldHash := record.GetString("password:hash")
form := forms.NewRecordUpsert(testApp, record)
record.SetPassword("1234567890")
err = form.Submit()
if err != nil {
t.Fatalf("Expected no errors, got %v", err)
}
newHash := record.GetString("password:hash")
if newHash == "" || newHash == oldHash {
t.Fatal("Expected password change")
}
})
t.Run("update user with random password change", func(t *testing.T) {
record, err := testApp.FindAuthRecordByEmail(users, "test@example.com")
if err != nil {
t.Fatal(err)
}
oldHash := record.GetString("password:hash")
form := forms.NewRecordUpsert(testApp, record)
record.SetRandomPassword()
err = form.Submit()
if err != nil {
t.Fatalf("Expected no errors, got %v", err)
}
newHash := record.GetString("password:hash")
if newHash == "" || newHash == oldHash {
t.Fatal("Expected password change")
}
})
}
// -------------------------------------------------------------------
func testFilesCount(t *testing.T, app core.App, record *core.Record, count int) {
storageDir := filepath.Join(app.DataDir(), "storage", record.Collection().Id, record.Id)
entries, _ := os.ReadDir(storageDir)
if len(entries) != count {
t.Errorf("Expected %d entries, got %d\n%v", count, len(entries), entries)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/forms/apple_client_secret_create.go | forms/apple_client_secret_create.go | package forms
import (
"regexp"
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/pocketbase/core"
)
var privateKeyRegex = regexp.MustCompile(`(?m)-----BEGIN PRIVATE KEY----[\s\S]+-----END PRIVATE KEY-----`)
// AppleClientSecretCreate is a form struct to generate a new Apple Client Secret.
//
// Reference: https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
type AppleClientSecretCreate struct {
app core.App
// ClientId is the identifier of your app (aka. Service ID).
ClientId string `form:"clientId" json:"clientId"`
// TeamId is a 10-character string associated with your developer account
// (usually could be found next to your name in the Apple Developer site).
TeamId string `form:"teamId" json:"teamId"`
// KeyId is a 10-character key identifier generated for the "Sign in with Apple"
// private key associated with your developer account.
KeyId string `form:"keyId" json:"keyId"`
// PrivateKey is the private key associated to your app.
// Usually wrapped within -----BEGIN PRIVATE KEY----- X -----END PRIVATE KEY-----.
PrivateKey string `form:"privateKey" json:"privateKey"`
// Duration specifies how long the generated JWT should be considered valid.
// The specified value must be in seconds and max 15777000 (~6months).
Duration int `form:"duration" json:"duration"`
}
// NewAppleClientSecretCreate creates a new [AppleClientSecretCreate] form with initializer
// config created from the provided [core.App] instances.
func NewAppleClientSecretCreate(app core.App) *AppleClientSecretCreate {
form := &AppleClientSecretCreate{
app: app,
}
return form
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *AppleClientSecretCreate) Validate() error {
return validation.ValidateStruct(form,
validation.Field(&form.ClientId, validation.Required),
validation.Field(&form.TeamId, validation.Required, validation.Length(10, 10)),
validation.Field(&form.KeyId, validation.Required, validation.Length(10, 10)),
validation.Field(&form.PrivateKey, validation.Required, validation.Match(privateKeyRegex)),
validation.Field(&form.Duration, validation.Required, validation.Min(1), validation.Max(15777000)),
)
}
// Submit validates the form and returns a new Apple Client Secret JWT.
func (form *AppleClientSecretCreate) Submit() (string, error) {
if err := form.Validate(); err != nil {
return "", err
}
signKey, err := jwt.ParseECPrivateKeyFromPEM([]byte(strings.TrimSpace(form.PrivateKey)))
if err != nil {
return "", err
}
now := time.Now()
claims := &jwt.RegisteredClaims{
Audience: jwt.ClaimStrings{"https://appleid.apple.com"},
Subject: form.ClientId,
Issuer: form.TeamId,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(form.Duration) * time.Second)),
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header["kid"] = form.KeyId
return token.SignedString(signKey)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/ghupdate/ghupdate.go | plugins/ghupdate/ghupdate.go | // Package ghupdate implements a new command to selfupdate the current
// PocketBase executable with the latest GitHub release.
//
// Example usage:
//
// ghupdate.MustRegister(app, app.RootCmd, ghupdate.Config{})
package ghupdate
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/fatih/color"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/archive"
"github.com/pocketbase/pocketbase/tools/osutils"
"github.com/spf13/cobra"
)
// HttpClient is a base HTTP client interface (usually used for test purposes).
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Config defines the config options of the ghupdate plugin.
//
// NB! This plugin is considered experimental and its config options may change in the future.
type Config struct {
// Owner specifies the account owner of the repository (default to "pocketbase").
Owner string
// Repo specifies the name of the repository (default to "pocketbase").
Repo string
// ArchiveExecutable specifies the name of the executable file in the release archive
// (default to "pocketbase"; an additional ".exe" check is also performed as a fallback).
ArchiveExecutable string
// Optional context to use when fetching and downloading the latest release.
Context context.Context
// The HTTP client to use when fetching and downloading the latest release.
// Defaults to `http.DefaultClient`.
HttpClient HttpClient
}
// MustRegister registers the ghupdate plugin to the provided app instance
// and panic if it fails.
func MustRegister(app core.App, rootCmd *cobra.Command, config Config) {
if err := Register(app, rootCmd, config); err != nil {
panic(err)
}
}
// Register registers the ghupdate plugin to the provided app instance.
func Register(app core.App, rootCmd *cobra.Command, config Config) error {
p := &plugin{
app: app,
currentVersion: rootCmd.Version,
config: config,
}
if p.config.Owner == "" {
p.config.Owner = "pocketbase"
}
if p.config.Repo == "" {
p.config.Repo = "pocketbase"
}
if p.config.ArchiveExecutable == "" {
p.config.ArchiveExecutable = "pocketbase"
}
if p.config.HttpClient == nil {
p.config.HttpClient = http.DefaultClient
}
if p.config.Context == nil {
p.config.Context = context.Background()
}
rootCmd.AddCommand(p.updateCmd())
return nil
}
type plugin struct {
app core.App
config Config
currentVersion string
}
func (p *plugin) updateCmd() *cobra.Command {
var withBackup bool
command := &cobra.Command{
Use: "update",
Short: "Automatically updates the current app executable with the latest available version",
SilenceUsage: true,
RunE: func(command *cobra.Command, args []string) error {
var needConfirm bool
if isMaybeRunningInDocker() {
needConfirm = true
color.Yellow("NB! It seems that you are in a Docker container.")
color.Yellow("The update command may not work as expected in this context because usually the version of the app is managed by the container image itself.")
} else if isMaybeRunningInNixOS() {
needConfirm = true
color.Yellow("NB! It seems that you are in a NixOS.")
color.Yellow("Due to the non-standard filesystem implementation of the environment, the update command may not work as expected.")
}
if needConfirm {
confirm := osutils.YesNoPrompt("Do you want to proceed with the update?", false)
if !confirm {
fmt.Println("The command has been cancelled.")
return nil
}
}
return p.update(withBackup)
},
}
command.PersistentFlags().BoolVar(
&withBackup,
"backup",
true,
"Creates a pb_data backup at the end of the update process",
)
return command
}
func (p *plugin) update(withBackup bool) error {
color.Yellow("Fetching release information...")
latest, err := fetchLatestRelease(
p.config.Context,
p.config.HttpClient,
p.config.Owner,
p.config.Repo,
)
if err != nil {
return err
}
if compareVersions(strings.TrimPrefix(p.currentVersion, "v"), strings.TrimPrefix(latest.Tag, "v")) <= 0 {
color.Green("You already have the latest version %s.", p.currentVersion)
return nil
}
suffix := archiveSuffix(runtime.GOOS, runtime.GOARCH)
if suffix == "" {
return errors.New("unsupported platform")
}
asset, err := latest.findAssetBySuffix(suffix)
if err != nil {
return err
}
releaseDir := filepath.Join(p.app.DataDir(), core.LocalTempDirName)
defer os.RemoveAll(releaseDir)
color.Yellow("Downloading %s...", asset.Name)
// download the release asset
assetZip := filepath.Join(releaseDir, asset.Name)
if err := downloadFile(p.config.Context, p.config.HttpClient, asset.DownloadUrl, assetZip); err != nil {
return err
}
color.Yellow("Extracting %s...", asset.Name)
extractDir := filepath.Join(releaseDir, "extracted_"+asset.Name)
defer os.RemoveAll(extractDir)
if err := archive.Extract(assetZip, extractDir); err != nil {
return err
}
color.Yellow("Replacing the executable...")
oldExec, err := os.Executable()
if err != nil {
return err
}
renamedOldExec := oldExec + ".old"
defer os.Remove(renamedOldExec)
newExec := filepath.Join(extractDir, p.config.ArchiveExecutable)
if _, err := os.Stat(newExec); err != nil {
// try again with an .exe extension
newExec = newExec + ".exe"
if _, fallbackErr := os.Stat(newExec); fallbackErr != nil {
return fmt.Errorf("the executable in the extracted path is missing or it is inaccessible: %v, %v", err, fallbackErr)
}
}
// rename the current executable
if err := os.Rename(oldExec, renamedOldExec); err != nil {
return fmt.Errorf("failed to rename the current executable: %w", err)
}
tryToRevertExecChanges := func() {
if revertErr := os.Rename(renamedOldExec, oldExec); revertErr != nil {
p.app.Logger().Debug(
"Failed to revert executable",
slog.String("old", renamedOldExec),
slog.String("new", oldExec),
slog.String("error", revertErr.Error()),
)
}
}
// replace with the extracted binary
if err := os.Rename(newExec, oldExec); err != nil {
tryToRevertExecChanges()
return fmt.Errorf("failed replacing the executable: %w", err)
}
if withBackup {
color.Yellow("Creating pb_data backup...")
backupName := fmt.Sprintf("@update_%s.zip", latest.Tag)
if err := p.app.CreateBackup(p.config.Context, backupName); err != nil {
tryToRevertExecChanges()
return err
}
}
color.HiBlack("---")
color.Green("Update completed successfully! You can start the executable as usual.")
// print the release notes
if latest.Body != "" {
fmt.Print("\n")
color.Cyan("Here is a list with some of the %s changes:", latest.Tag)
// remove the update command note to avoid "stuttering"
// (@todo consider moving to a config option)
releaseNotes := strings.TrimSpace(strings.Replace(latest.Body, "> _To update the prebuilt executable you can run `./"+p.config.ArchiveExecutable+" update`._", "", 1))
color.Cyan(releaseNotes)
fmt.Print("\n")
}
return nil
}
func fetchLatestRelease(
ctx context.Context,
client HttpClient,
owner string,
repo string,
) (*release, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
rawBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// http.Client doesn't treat non 2xx responses as error
if res.StatusCode >= 400 {
return nil, fmt.Errorf(
"(%d) failed to fetch latest releases:\n%s",
res.StatusCode,
string(rawBody),
)
}
result := &release{}
if err := json.Unmarshal(rawBody, result); err != nil {
return nil, err
}
return result, nil
}
func downloadFile(
ctx context.Context,
client HttpClient,
url string,
destPath string,
) error {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// http.Client doesn't treat non 2xx responses as error
if res.StatusCode >= 400 {
return fmt.Errorf("(%d) failed to send download file request", res.StatusCode)
}
// ensure that the dest parent dir(s) exist
if err := os.MkdirAll(filepath.Dir(destPath), os.ModePerm); err != nil {
return err
}
dest, err := os.Create(destPath)
if err != nil {
return err
}
defer dest.Close()
if _, err := io.Copy(dest, res.Body); err != nil {
return err
}
return nil
}
func archiveSuffix(goos, goarch string) string {
switch goos {
case "linux":
switch goarch {
case "amd64":
return "_linux_amd64.zip"
case "arm64":
return "_linux_arm64.zip"
case "arm":
return "_linux_armv7.zip"
}
case "darwin":
switch goarch {
case "amd64":
return "_darwin_amd64.zip"
case "arm64":
return "_darwin_arm64.zip"
}
case "windows":
switch goarch {
case "amd64":
return "_windows_amd64.zip"
case "arm64":
return "_windows_arm64.zip"
}
}
return ""
}
func compareVersions(a, b string) int {
aSplit := strings.Split(a, ".")
aTotal := len(aSplit)
bSplit := strings.Split(b, ".")
bTotal := len(bSplit)
limit := aTotal
if bTotal > aTotal {
limit = bTotal
}
for i := 0; i < limit; i++ {
var x, y int
if i < aTotal {
x, _ = strconv.Atoi(aSplit[i])
}
if i < bTotal {
y, _ = strconv.Atoi(bSplit[i])
}
if x < y {
return 1 // b is newer
}
if x > y {
return -1 // a is newer
}
}
return 0 // equal
}
// note: not completely reliable as it may not work on all platforms
// but should at least provide a warning for the most common use cases
func isMaybeRunningInDocker() bool {
_, err := os.Stat("/.dockerenv")
return err == nil
}
// note: untested
func isMaybeRunningInNixOS() bool {
_, err := os.Stat("/etc/NIXOS")
return err == nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/ghupdate/release.go | plugins/ghupdate/release.go | package ghupdate
import (
"errors"
"strings"
)
type releaseAsset struct {
Name string `json:"name"`
DownloadUrl string `json:"browser_download_url"`
Id int `json:"id"`
Size int `json:"size"`
}
type release struct {
Name string `json:"name"`
Tag string `json:"tag_name"`
Published string `json:"published_at"`
Url string `json:"html_url"`
Body string `json:"body"`
Assets []*releaseAsset `json:"assets"`
Id int `json:"id"`
}
// findAssetBySuffix returns the first available asset containing the specified suffix.
func (r *release) findAssetBySuffix(suffix string) (*releaseAsset, error) {
if suffix != "" {
for _, asset := range r.Assets {
if strings.HasSuffix(asset.Name, suffix) {
return asset, nil
}
}
}
return nil, errors.New("missing asset containing " + suffix)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/ghupdate/ghupdate_test.go | plugins/ghupdate/ghupdate_test.go | package ghupdate
import "testing"
func TestCompareVersions(t *testing.T) {
scenarios := []struct {
a string
b string
expected int
}{
{"", "", 0},
{"0", "", 0},
{"1", "1.0.0", 0},
{"1.1", "1.1.0", 0},
{"1.1", "1.1.1", 1},
{"1.1", "1.0.1", -1},
{"1.0", "1.0.1", 1},
{"1.10", "1.9", -1},
{"1.2", "1.12", 1},
{"3.2", "1.6", -1},
{"0.0.2", "0.0.1", -1},
{"0.16.2", "0.17.0", 1},
{"1.15.0", "0.16.1", -1},
{"1.2.9", "1.2.10", 1},
{"3.2", "4.0", 1},
{"3.2.4", "3.2.3", -1},
}
for _, s := range scenarios {
t.Run(s.a+"VS"+s.b, func(t *testing.T) {
result := compareVersions(s.a, s.b)
if result != s.expected {
t.Fatalf("Expected %q vs %q to result in %d, got %d", s.a, s.b, s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/ghupdate/release_test.go | plugins/ghupdate/release_test.go | package ghupdate
import "testing"
func TestReleaseFindAssetBySuffix(t *testing.T) {
r := release{
Assets: []*releaseAsset{
{Name: "test1.zip", Id: 1},
{Name: "test2.zip", Id: 2},
{Name: "test22.zip", Id: 22},
{Name: "test3.zip", Id: 3},
},
}
asset, err := r.findAssetBySuffix("2.zip")
if err != nil {
t.Fatalf("Expected nil, got err: %v", err)
}
if asset.Id != 2 {
t.Fatalf("Expected asset with id %d, got %v", 2, asset)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/jsvm.go | plugins/jsvm/jsvm.go | // Package jsvm implements pluggable utilities for binding a JS goja runtime
// to the PocketBase instance (loading migrations, attaching to app hooks, etc.).
//
// Example:
//
// jsvm.MustRegister(app, jsvm.Config{
// HooksWatch: true,
// })
package jsvm
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/buffer"
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/process"
"github.com/dop251/goja_nodejs/require"
"github.com/fatih/color"
"github.com/fsnotify/fsnotify"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/plugins/jsvm/internal/types/generated"
"github.com/pocketbase/pocketbase/tools/template"
)
const typesFileName = "types.d.ts"
var defaultScriptPath = "pb.js"
func init() {
// For backward compatibility and consistency with the Go exposed
// methods that operate with relative paths (e.g. `$os.writeFile`),
// we define the "current JS module" as if it is a file in the current working directory
// (the filename itself doesn't really matter and in our case the hook handlers are executed as separate "programs").
//
// This is necessary for `require(module)` to properly traverse parents node_modules (goja_nodejs#95).
cwd, err := os.Getwd()
if err != nil {
// truly rare case, log just for debug purposes
color.Yellow("Failed to retrieve the current working directory: %v", err)
} else {
defaultScriptPath = filepath.Join(cwd, defaultScriptPath)
}
}
// Config defines the config options of the jsvm plugin.
type Config struct {
// OnInit is an optional function that will be called
// after a JS runtime is initialized, allowing you to
// attach custom Go variables and functions.
OnInit func(vm *goja.Runtime)
// HooksWatch enables auto app restarts when a JS app hook file changes.
//
// Note that currently the application cannot be automatically restarted on Windows
// because the restart process relies on execve.
HooksWatch bool
// HooksDir specifies the JS app hooks directory.
//
// If not set it fallbacks to a relative "pb_data/../pb_hooks" directory.
HooksDir string
// HooksFilesPattern specifies a regular expression pattern that
// identify which file to load by the hook vm(s).
//
// If not set it fallbacks to `^.*(\.pb\.js|\.pb\.ts)$`, aka. any
// HookdsDir file ending in ".pb.js" or ".pb.ts" (the last one is to enforce IDE linters).
HooksFilesPattern string
// HooksPoolSize specifies how many goja.Runtime instances to prewarm
// and keep for the JS app hooks gorotines execution.
//
// Zero or negative value means that it will create a new goja.Runtime
// on every fired goroutine.
HooksPoolSize int
// MigrationsDir specifies the JS migrations directory.
//
// If not set it fallbacks to a relative "pb_data/../pb_migrations" directory.
MigrationsDir string
// If not set it fallbacks to `^.*(\.js|\.ts)$`, aka. any MigrationDir file
// ending in ".js" or ".ts" (the last one is to enforce IDE linters).
MigrationsFilesPattern string
// TypesDir specifies the directory where to store the embedded
// TypeScript declarations file.
//
// If not set it fallbacks to "pb_data".
//
// Note: Avoid using the same directory as the HooksDir when HooksWatch is enabled
// to prevent unnecessary app restarts when the types file is initially created.
TypesDir string
}
// MustRegister registers the jsvm plugin in the provided app instance
// and panics if it fails.
//
// Example usage:
//
// jsvm.MustRegister(app, jsvm.Config{
// OnInit: func(vm *goja.Runtime) {
// // register custom bindings
// vm.Set("myCustomVar", 123)
// },
// })
func MustRegister(app core.App, config Config) {
if err := Register(app, config); err != nil {
panic(err)
}
}
// Register registers the jsvm plugin in the provided app instance.
func Register(app core.App, config Config) error {
p := &plugin{app: app, config: config}
if p.config.HooksDir == "" {
p.config.HooksDir = filepath.Join(app.DataDir(), "../pb_hooks")
}
if p.config.MigrationsDir == "" {
p.config.MigrationsDir = filepath.Join(app.DataDir(), "../pb_migrations")
}
if p.config.HooksFilesPattern == "" {
p.config.HooksFilesPattern = `^.*(\.pb\.js|\.pb\.ts)$`
}
if p.config.MigrationsFilesPattern == "" {
p.config.MigrationsFilesPattern = `^.*(\.js|\.ts)$`
}
if p.config.TypesDir == "" {
p.config.TypesDir = app.DataDir()
}
p.app.OnBootstrap().BindFunc(func(e *core.BootstrapEvent) error {
err := e.Next()
if err != nil {
return err
}
// ensure that the user has the latest types declaration
err = p.refreshTypesFile()
if err != nil {
color.Yellow("Unable to refresh app types file: %v", err)
}
return nil
})
if err := p.registerMigrations(); err != nil {
return fmt.Errorf("registerMigrations: %w", err)
}
if err := p.registerHooks(); err != nil {
return fmt.Errorf("registerHooks: %w", err)
}
return nil
}
type plugin struct {
app core.App
config Config
}
// registerMigrations registers the JS migrations loader.
func (p *plugin) registerMigrations() error {
// fetch all js migrations sorted by their filename
files, err := filesContent(p.config.MigrationsDir, p.config.MigrationsFilesPattern)
if err != nil {
return err
}
absHooksDir, err := filepath.Abs(p.config.HooksDir)
if err != nil {
return err
}
registry := new(require.Registry) // this can be shared by multiple runtimes
templateRegistry := template.NewRegistry()
for file, content := range files {
vm := goja.New()
registry.Enable(vm)
console.Enable(vm)
process.Enable(vm)
buffer.Enable(vm)
baseBinds(vm)
dbxBinds(vm)
securityBinds(vm)
osBinds(vm)
filepathBinds(vm)
httpClientBinds(vm)
filesystemBinds(vm)
formsBinds(vm)
mailsBinds(vm)
vm.Set("$template", templateRegistry)
vm.Set("__hooks", absHooksDir)
vm.Set("migrate", func(up, down func(txApp core.App) error) {
core.AppMigrations.Register(up, down, file)
})
if p.config.OnInit != nil {
p.config.OnInit(vm)
}
_, err := vm.RunScript(defaultScriptPath, string(content))
if err != nil {
return fmt.Errorf("failed to run migration %s: %w", file, err)
}
}
return nil
}
// registerHooks registers the JS app hooks loader.
func (p *plugin) registerHooks() error {
// fetch all js hooks sorted by their filename
files, err := filesContent(p.config.HooksDir, p.config.HooksFilesPattern)
if err != nil {
return err
}
// prepend the types reference directive
//
// note: it is loaded during startup to handle conveniently also
// the case when the HooksWatch option is enabled and the application
// restart on newly created file
for name, content := range files {
if len(content) != 0 {
// skip non-empty files for now to prevent accidental overwrite
continue
}
path := filepath.Join(p.config.HooksDir, name)
directive := `/// <reference path="` + p.relativeTypesPath(p.config.HooksDir) + `" />`
if err := prependToEmptyFile(path, directive+"\n\n"); err != nil {
color.Yellow("Unable to prepend the types reference: %v", err)
}
}
// initialize the hooks dir watcher
if p.config.HooksWatch {
if err := p.watchHooks(); err != nil {
color.Yellow("Unable to init hooks watcher: %v", err)
}
}
if len(files) == 0 {
// no need to register the vms since there are no entrypoint files anyway
return nil
}
absHooksDir, err := filepath.Abs(p.config.HooksDir)
if err != nil {
return err
}
p.app.OnServe().BindFunc(func(e *core.ServeEvent) error {
e.Router.BindFunc(p.normalizeServeExceptions)
return e.Next()
})
// safe to be shared across multiple vms
requireRegistry := new(require.Registry)
templateRegistry := template.NewRegistry()
sharedBinds := func(vm *goja.Runtime) {
requireRegistry.Enable(vm)
console.Enable(vm)
process.Enable(vm)
buffer.Enable(vm)
baseBinds(vm)
dbxBinds(vm)
filesystemBinds(vm)
securityBinds(vm)
osBinds(vm)
filepathBinds(vm)
httpClientBinds(vm)
formsBinds(vm)
apisBinds(vm)
mailsBinds(vm)
vm.Set("$app", p.app)
vm.Set("$template", templateRegistry)
vm.Set("__hooks", absHooksDir)
if p.config.OnInit != nil {
p.config.OnInit(vm)
}
}
// initiliaze the executor vms
executors := newPool(p.config.HooksPoolSize, func() *goja.Runtime {
executor := goja.New()
sharedBinds(executor)
return executor
})
// initialize the loader vm
loader := goja.New()
sharedBinds(loader)
hooksBinds(p.app, loader, executors)
cronBinds(p.app, loader, executors)
routerBinds(p.app, loader, executors)
for file, content := range files {
func() {
defer func() {
if err := recover(); err != nil {
fmtErr := fmt.Errorf("failed to execute %s:\n - %v", file, err)
if p.config.HooksWatch {
color.Red("%v", fmtErr)
} else {
panic(fmtErr)
}
}
}()
_, err := loader.RunScript(defaultScriptPath, string(content))
if err != nil {
panic(err)
}
}()
}
return nil
}
// normalizeExceptions registers a global error handler that
// wraps the extracted goja exception error value for consistency
// when throwing or returning errors.
func (p *plugin) normalizeServeExceptions(e *core.RequestEvent) error {
err := e.Next()
if err == nil || e.Written() {
return err // no error or already committed
}
return normalizeException(err)
}
// watchHooks initializes a hooks file watcher that will restart the
// application (*if possible) in case of a change in the hooks directory.
//
// This method does nothing if the hooks directory is missing.
func (p *plugin) watchHooks() error {
watchDir := p.config.HooksDir
hooksDirInfo, err := os.Lstat(p.config.HooksDir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil // no hooks dir to watch
}
return err
}
if hooksDirInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
watchDir, err = filepath.EvalSymlinks(p.config.HooksDir)
if err != nil {
return fmt.Errorf("failed to resolve hooksDir symlink: %w", err)
}
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
var debounceTimer *time.Timer
stopDebounceTimer := func() {
if debounceTimer != nil {
debounceTimer.Stop()
debounceTimer = nil
}
}
p.app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error {
watcher.Close()
stopDebounceTimer()
return e.Next()
})
// start listening for events.
go func() {
defer stopDebounceTimer()
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
stopDebounceTimer()
debounceTimer = time.AfterFunc(50*time.Millisecond, func() {
// app restart is currently not supported on Windows
if runtime.GOOS == "windows" {
color.Yellow("File %s changed, please restart the app manually", event.Name)
} else {
color.Yellow("File %s changed, restarting...", event.Name)
if err := p.app.Restart(); err != nil {
color.Red("Failed to restart the app:", err)
}
}
})
case err, ok := <-watcher.Errors:
if !ok {
return
}
color.Red("Watch error:", err)
}
}
}()
// add directories to watch
//
// @todo replace once recursive watcher is added (https://github.com/fsnotify/fsnotify/issues/18)
dirsErr := filepath.WalkDir(watchDir, func(path string, entry fs.DirEntry, err error) error {
// ignore hidden directories, node_modules, symlinks, sockets, etc.
if !entry.IsDir() || entry.Name() == "node_modules" || strings.HasPrefix(entry.Name(), ".") {
return nil
}
return watcher.Add(path)
})
if dirsErr != nil {
watcher.Close()
}
return dirsErr
}
// fullTypesPathReturns returns the full path to the generated TS file.
func (p *plugin) fullTypesPath() string {
return filepath.Join(p.config.TypesDir, typesFileName)
}
// relativeTypesPath returns a path to the generated TS file relative
// to the specified basepath.
//
// It fallbacks to the full path if generating the relative path fails.
func (p *plugin) relativeTypesPath(basepath string) string {
fullPath := p.fullTypesPath()
rel, err := filepath.Rel(basepath, fullPath)
if err != nil {
// fallback to the full path
rel = fullPath
}
return rel
}
// refreshTypesFile saves the embedded TS declarations as a file on the disk.
func (p *plugin) refreshTypesFile() error {
fullPath := p.fullTypesPath()
// ensure that the types directory exists
dir := filepath.Dir(fullPath)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
// retrieve the types data to write
data, err := generated.Types.ReadFile(typesFileName)
if err != nil {
return err
}
// read the first timestamp line of the old file (if exists) and compare it to the embedded one
// (note: ignore errors to allow always overwriting the file if it is invalid)
existingFile, err := os.Open(fullPath)
if err == nil {
timestamp := make([]byte, 13)
io.ReadFull(existingFile, timestamp)
existingFile.Close()
if len(data) >= len(timestamp) && bytes.Equal(data[:13], timestamp) {
return nil // nothing new to save
}
}
return os.WriteFile(fullPath, data, 0644)
}
// prependToEmptyFile prepends the specified text to an empty file.
//
// If the file is not empty this method does nothing.
func prependToEmptyFile(path, text string) error {
info, err := os.Stat(path)
if err == nil && info.Size() == 0 {
return os.WriteFile(path, []byte(text), 0644)
}
return err
}
// filesContent returns a map with all direct files within the specified dir and their content.
//
// If directory with dirPath is missing or no files matching the pattern were found,
// it returns an empty map and no error.
//
// If pattern is empty string it matches all root files.
func filesContent(dirPath string, pattern string) (map[string][]byte, error) {
files, err := os.ReadDir(dirPath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return map[string][]byte{}, nil
}
return nil, err
}
var exp *regexp.Regexp
if pattern != "" {
var err error
if exp, err = regexp.Compile(pattern); err != nil {
return nil, err
}
}
result := map[string][]byte{}
for _, f := range files {
if f.IsDir() || (exp != nil && !exp.MatchString(f.Name())) {
continue
}
raw, err := os.ReadFile(filepath.Join(dirPath, f.Name()))
if err != nil {
return nil, err
}
result[f.Name()] = raw
}
return result, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/mapper_test.go | plugins/jsvm/mapper_test.go | package jsvm_test
import (
"reflect"
"testing"
"github.com/pocketbase/pocketbase/plugins/jsvm"
)
func TestFieldMapper(t *testing.T) {
mapper := jsvm.FieldMapper{}
scenarios := []struct {
name string
expected string
}{
{"", ""},
{"test", "test"},
{"Test", "test"},
{"miXeD", "miXeD"},
{"MiXeD", "miXeD"},
{"ResolveRequestAsJSON", "resolveRequestAsJSON"},
{"Variable_with_underscore", "variable_with_underscore"},
{"ALLCAPS", "allcaps"},
{"ALL_CAPS_WITH_UNDERSCORE", "all_caps_with_underscore"},
{"OIDCMap", "oidcMap"},
{"MD5", "md5"},
{"OAuth2", "oauth2"},
}
for i, s := range scenarios {
field := reflect.StructField{Name: s.name}
if v := mapper.FieldName(nil, field); v != s.expected {
t.Fatalf("[%d] Expected FieldName %q, got %q", i, s.expected, v)
}
method := reflect.Method{Name: s.name}
if v := mapper.MethodName(nil, method); v != s.expected {
t.Fatalf("[%d] Expected MethodName %q, got %q", i, s.expected, v)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/form_data.go | plugins/jsvm/form_data.go | package jsvm
import (
"bytes"
"io"
"mime/multipart"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/spf13/cast"
)
// FormData represents an interface similar to the browser's [FormData].
//
// The value of each FormData entry must be a string or [*filesystem.File] instance.
//
// It is intended to be used together with the JSVM `$http.send` when
// sending multipart/form-data requests.
//
// [FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData.
type FormData map[string][]any
// Append appends a new value onto an existing key inside the current FormData,
// or adds the key if it does not already exist.
func (data FormData) Append(key string, value any) {
data[key] = append(data[key], value)
}
// Set sets a new value for an existing key inside the current FormData,
// or adds the key/value if it does not already exist.
func (data FormData) Set(key string, value any) {
data[key] = []any{value}
}
// Delete deletes a key and its value(s) from the current FormData.
func (data FormData) Delete(key string) {
delete(data, key)
}
// Get returns the first value associated with a given key from
// within the current FormData.
//
// If you expect multiple values and want all of them,
// use the [FormData.GetAll] method instead.
func (data FormData) Get(key string) any {
values, ok := data[key]
if !ok || len(values) == 0 {
return nil
}
return values[0]
}
// GetAll returns all the values associated with a given key
// from within the current FormData.
func (data FormData) GetAll(key string) []any {
values, ok := data[key]
if !ok {
return nil
}
return values
}
// Has returns whether a FormData object contains a certain key.
func (data FormData) Has(key string) bool {
values, ok := data[key]
return ok && len(values) > 0
}
// Keys returns all keys contained in the current FormData.
func (data FormData) Keys() []string {
result := make([]string, 0, len(data))
for k := range data {
result = append(result, k)
}
return result
}
// Keys returns all values contained in the current FormData.
func (data FormData) Values() []any {
result := make([]any, 0, len(data))
for _, values := range data {
result = append(result, values...)
}
return result
}
// Entries returns a [key, value] slice pair for each FormData entry.
func (data FormData) Entries() [][]any {
result := make([][]any, 0, len(data))
for k, values := range data {
for _, v := range values {
result = append(result, []any{k, v})
}
}
return result
}
// toMultipart converts the current FormData entries into multipart encoded data.
func (data FormData) toMultipart() (*bytes.Buffer, *multipart.Writer, error) {
body := new(bytes.Buffer)
mp := multipart.NewWriter(body)
defer mp.Close()
for k, values := range data {
for _, rawValue := range values {
switch v := rawValue.(type) {
case *filesystem.File:
err := func() error {
mpw, err := mp.CreateFormFile(k, v.OriginalName)
if err != nil {
return err
}
file, err := v.Reader.Open()
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(mpw, file)
if err != nil {
return err
}
return nil
}()
if err != nil {
return nil, nil, err
}
default:
err := mp.WriteField(k, cast.ToString(v))
if err != nil {
return nil, nil, err
}
}
}
}
return body, mp, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/pool.go | plugins/jsvm/pool.go | package jsvm
import (
"sync"
"github.com/dop251/goja"
)
type poolItem struct {
mux sync.Mutex
busy bool
vm *goja.Runtime
}
type vmsPool struct {
mux sync.RWMutex
factory func() *goja.Runtime
items []*poolItem
}
// newPool creates a new pool with pre-warmed vms generated from the specified factory.
func newPool(size int, factory func() *goja.Runtime) *vmsPool {
pool := &vmsPool{
factory: factory,
items: make([]*poolItem, size),
}
for i := 0; i < size; i++ {
vm := pool.factory()
pool.items[i] = &poolItem{vm: vm}
}
return pool
}
// run executes "call" with a vm created from the pool
// (either from the buffer or a new one if all buffered vms are busy)
func (p *vmsPool) run(call func(vm *goja.Runtime) error) error {
p.mux.RLock()
// try to find a free item
var freeItem *poolItem
for _, item := range p.items {
item.mux.Lock()
if item.busy {
item.mux.Unlock()
continue
}
item.busy = true
item.mux.Unlock()
freeItem = item
break
}
p.mux.RUnlock()
// create a new one-off item if of all of the pool items are currently busy
//
// note: if turned out not efficient we may change this in the future
// by adding the created item in the pool with some timer for removal
if freeItem == nil {
return call(p.factory())
}
execErr := call(freeItem.vm)
// "free" the vm
freeItem.mux.Lock()
freeItem.busy = false
freeItem.mux.Unlock()
return execErr
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/form_data_test.go | plugins/jsvm/form_data_test.go | package jsvm
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/list"
)
func TestFormDataAppendAndSet(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("a", 2)
data.Append("b", 3)
data.Append("b", 4)
data.Set("b", 5) // should overwrite the previous 2 calls
data.Set("c", 6)
data.Set("c", 7)
if len(data["a"]) != 2 {
t.Fatalf("Expected 2 'a' values, got %v", data["a"])
}
if data["a"][0] != 1 || data["a"][1] != 2 {
t.Fatalf("Expected 1 and 2 'a' key values, got %v", data["a"])
}
if len(data["b"]) != 1 {
t.Fatalf("Expected 1 'b' values, got %v", data["b"])
}
if data["b"][0] != 5 {
t.Fatalf("Expected 5 as 'b' key value, got %v", data["b"])
}
if len(data["c"]) != 1 {
t.Fatalf("Expected 1 'c' values, got %v", data["c"])
}
if data["c"][0] != 7 {
t.Fatalf("Expected 7 as 'c' key value, got %v", data["c"])
}
}
func TestFormDataDelete(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("a", 2)
data.Append("b", 3)
data.Delete("missing") // should do nothing
data.Delete("a")
if len(data) != 1 {
t.Fatalf("Expected exactly 1 data remaining key, got %v", data)
}
if data["b"][0] != 3 {
t.Fatalf("Expected 3 as 'b' key value, got %v", data["b"])
}
}
func TestFormDataGet(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("a", 2)
if v := data.Get("missing"); v != nil {
t.Fatalf("Expected %v for key 'missing', got %v", nil, v)
}
if v := data.Get("a"); v != 1 {
t.Fatalf("Expected %v for key 'a', got %v", 1, v)
}
}
func TestFormDataGetAll(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("a", 2)
if v := data.GetAll("missing"); v != nil {
t.Fatalf("Expected %v for key 'a', got %v", nil, v)
}
values := data.GetAll("a")
if len(values) != 2 || values[0] != 1 || values[1] != 2 {
t.Fatalf("Expected 1 and 2 values, got %v", values)
}
}
func TestFormDataHas(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
if v := data.Has("missing"); v {
t.Fatalf("Expected key 'missing' to not exist: %v", v)
}
if v := data.Has("a"); !v {
t.Fatalf("Expected key 'a' to exist: %v", v)
}
}
func TestFormDataKeys(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("b", 1)
data.Append("c", 1)
data.Append("a", 1)
keys := data.Keys()
expectedKeys := []string{"a", "b", "c"}
for _, expected := range expectedKeys {
if !list.ExistInSlice(expected, keys) {
t.Fatalf("Expected key %s to exists in %v", expected, keys)
}
}
}
func TestFormDataValues(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("b", 2)
data.Append("c", 3)
data.Append("a", 4)
values := data.Values()
expectedKeys := []any{1, 2, 3, 4}
for _, expected := range expectedKeys {
if !list.ExistInSlice(expected, values) {
t.Fatalf("Expected key %s to exists in %v", expected, values)
}
}
}
func TestFormDataEntries(t *testing.T) {
t.Parallel()
data := FormData{}
data.Append("a", 1)
data.Append("b", 2)
data.Append("c", 3)
data.Append("a", 4)
entries := data.Entries()
rawEntries, err := json.Marshal(entries)
if err != nil {
t.Fatal(err)
}
if len(entries) != 4 {
t.Fatalf("Expected 4 entries")
}
expectedEntries := []string{`["a",1]`, `["a",4]`, `["b",2]`, `["c",3]`}
for _, expected := range expectedEntries {
if !bytes.Contains(rawEntries, []byte(expected)) {
t.Fatalf("Expected entry %s to exists in %s", expected, rawEntries)
}
}
}
func TestFormDataToMultipart(t *testing.T) {
t.Parallel()
f, err := filesystem.NewFileFromBytes([]byte("abc"), "test")
if err != nil {
t.Fatal(err)
}
data := FormData{}
data.Append("a", 1) // should be casted
data.Append("b", "test1")
data.Append("b", "test2")
data.Append("c", f)
body, mp, err := data.toMultipart()
if err != nil {
t.Fatal(err)
}
bodyStr := body.String()
// content type checks
contentType := mp.FormDataContentType()
expectedContentType := "multipart/form-data; boundary="
if !strings.Contains(contentType, expectedContentType) {
t.Fatalf("Expected to find content-type %s in %s", expectedContentType, contentType)
}
// body checks
expectedBodyParts := []string{
"Content-Disposition: form-data; name=\"a\"\r\n\r\n1",
"Content-Disposition: form-data; name=\"b\"\r\n\r\ntest1",
"Content-Disposition: form-data; name=\"b\"\r\n\r\ntest2",
"Content-Disposition: form-data; name=\"c\"; filename=\"test\"\r\nContent-Type: application/octet-stream\r\n\r\nabc",
}
for _, part := range expectedBodyParts {
if !strings.Contains(bodyStr, part) {
t.Fatalf("Expected to find %s in body\n%s", part, bodyStr)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/mapper.go | plugins/jsvm/mapper.go | package jsvm
import (
"reflect"
"strings"
"unicode"
"github.com/dop251/goja"
)
var (
_ goja.FieldNameMapper = (*FieldMapper)(nil)
)
// FieldMapper provides custom mapping between Go and JavaScript property names.
//
// It is similar to the builtin "uncapFieldNameMapper" but also converts
// all uppercase identifiers to their lowercase equivalent (eg. "GET" -> "get").
type FieldMapper struct {
}
// FieldName implements the [FieldNameMapper.FieldName] interface method.
func (u FieldMapper) FieldName(_ reflect.Type, f reflect.StructField) string {
return convertGoToJSName(f.Name)
}
// MethodName implements the [FieldNameMapper.MethodName] interface method.
func (u FieldMapper) MethodName(_ reflect.Type, m reflect.Method) string {
return convertGoToJSName(m.Name)
}
var nameExceptions = map[string]string{"OAuth2": "oauth2"}
func convertGoToJSName(name string) string {
if v, ok := nameExceptions[name]; ok {
return v
}
startUppercase := make([]rune, 0, len(name))
for _, c := range name {
if c != '_' && !unicode.IsUpper(c) && !unicode.IsDigit(c) {
break
}
startUppercase = append(startUppercase, c)
}
totalStartUppercase := len(startUppercase)
// all uppercase eg. "JSON" -> "json"
if len(name) == totalStartUppercase {
return strings.ToLower(name)
}
// eg. "JSONField" -> "jsonField"
if totalStartUppercase > 1 {
return strings.ToLower(name[0:totalStartUppercase-1]) + name[totalStartUppercase-1:]
}
// eg. "GetField" -> "getField"
if totalStartUppercase == 1 {
return strings.ToLower(name[0:1]) + name[1:]
}
return name
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/binds_test.go | plugins/jsvm/binds_test.go | package jsvm
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/dop251/goja"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/router"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
func testBindsCount(vm *goja.Runtime, namespace string, count int, t *testing.T) {
v, err := vm.RunString(`Object.keys(` + namespace + `).length`)
if err != nil {
t.Fatal(err)
}
total, _ := v.Export().(int64)
if int(total) != count {
t.Fatalf("Expected %d %s binds, got %d", count, namespace, total)
}
}
// note: this test is useful as a reminder to update the tests in case
// a new base binding is added.
func TestBaseBindsCount(t *testing.T) {
vm := goja.New()
baseBinds(vm)
testBindsCount(vm, "this", 41, t)
}
func TestBaseBindsSleep(t *testing.T) {
vm := goja.New()
baseBinds(vm)
vm.Set("reader", strings.NewReader("test"))
start := time.Now()
_, err := vm.RunString(`
sleep(100);
`)
if err != nil {
t.Fatal(err)
}
lasted := time.Since(start).Milliseconds()
if lasted < 100 || lasted > 150 {
t.Fatalf("Expected to sleep for ~100ms, got %d", lasted)
}
}
func TestBaseBindsReaderToString(t *testing.T) {
vm := goja.New()
baseBinds(vm)
vm.Set("reader", strings.NewReader("test"))
_, err := vm.RunString(`
let result = readerToString(reader)
if (result != "test") {
throw new Error('Expected "test", got ' + result);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsToString(t *testing.T) {
vm := goja.New()
baseBinds(vm)
vm.Set("scenarios", []struct {
Name string
Value any
Expected string
}{
{"null", nil, ""},
{"string", "test", "test"},
{"number", -12.4, "-12.4"},
{"bool", true, "true"},
{"arr", []int{1, 2, 3}, `[1,2,3]`},
{"obj", map[string]any{"test": 123}, `{"test":123}`},
{"reader", strings.NewReader("test"), "test"},
{"struct", struct {
Name string
private string
}{Name: "123", private: "456"}, `{"Name":"123"}`},
})
_, err := vm.RunString(`
for (let s of scenarios) {
let str = toString(s.value)
if (str != s.expected) {
throw new Error('[' + s.name + '] Expected string ' + s.expected + ', got ' + str);
}
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsToBytes(t *testing.T) {
vm := goja.New()
baseBinds(vm)
vm.Set("bytesEqual", bytes.Equal)
vm.Set("scenarios", []struct {
Name string
Value any
Expected []byte
}{
{"null", nil, []byte{}},
{"string", "test", []byte("test")},
{"number", -12.4, []byte("-12.4")},
{"bool", true, []byte("true")},
{"arr", []int{1, 2, 3}, []byte{1, 2, 3}},
{"jsonraw", types.JSONRaw{1, 2, 3}, []byte{1, 2, 3}},
{"reader", strings.NewReader("test"), []byte("test")},
{"obj", map[string]any{"test": 123}, []byte(`{"test":123}`)},
{"struct", struct {
Name string
private string
}{Name: "123", private: "456"}, []byte(`{"Name":"123"}`)},
})
_, err := vm.RunString(`
for (let s of scenarios) {
let b = toBytes(s.value)
if (!Array.isArray(b)) {
throw new Error('[' + s.name + '] Expected toBytes to return an array');
}
if (!bytesEqual(b, s.expected)) {
throw new Error('[' + s.name + '] Expected bytes ' + s.expected + ', got ' + b);
}
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsUnmarshal(t *testing.T) {
vm := goja.New()
baseBinds(vm)
vm.Set("data", &map[string]any{"a": 123})
_, err := vm.RunString(`
unmarshal({"b": 456}, data)
if (data.a != 123) {
throw new Error('Expected data.a 123, got ' + data.a);
}
if (data.b != 456) {
throw new Error('Expected data.b 456, got ' + data.b);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsContext(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
const base = new Context(null, "a", 123);
const sub = new Context(base, "b", 456);
const scenarios = [
{key: "a", expected: 123},
{key: "b", expected: 456},
];
for (let s of scenarios) {
if (sub.value(s.key) != s.expected) {
throw new("Expected " +s.key + " value " + s.expected + ", got " + sub.value(s.key));
}
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsCookie(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
const cookie = new Cookie({
name: "example_name",
value: "example_value",
path: "/example_path",
domain: "example.com",
maxAge: 10,
secure: true,
httpOnly: true,
sameSite: 3,
});
const result = cookie.string();
const expected = "example_name=example_value; Path=/example_path; Domain=example.com; Max-Age=10; HttpOnly; Secure; SameSite=Strict";
if (expected != result) {
throw new("Expected \n" + expected + "\ngot\n" + result);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsSubscriptionMessage(t *testing.T) {
vm := goja.New()
baseBinds(vm)
vm.Set("bytesToString", func(b []byte) string {
return string(b)
})
_, err := vm.RunString(`
const payload = {
name: "test",
data: '{"test":123}'
}
const result = new SubscriptionMessage(payload);
if (result.name != payload.name) {
throw new("Expected name " + payload.name + ", got " + result.name);
}
if (bytesToString(result.data) != payload.data) {
throw new("Expected data '" + payload.data + "', got '" + bytesToString(result.data) + "'");
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsRecord(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCachedCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
vm := goja.New()
baseBinds(vm)
vm.Set("collection", collection)
// without record data
// ---
v1, err := vm.RunString(`new Record(collection)`)
if err != nil {
t.Fatal(err)
}
m1, ok := v1.Export().(*core.Record)
if !ok {
t.Fatalf("Expected m1 to be models.Record, got \n%v", m1)
}
// with record data
// ---
v2, err := vm.RunString(`new Record(collection, { email: "test@example.com" })`)
if err != nil {
t.Fatal(err)
}
m2, ok := v2.Export().(*core.Record)
if !ok {
t.Fatalf("Expected m2 to be core.Record, got \n%v", m2)
}
if m2.Collection().Name != "users" {
t.Fatalf("Expected record with collection %q, got \n%v", "users", m2.Collection())
}
if m2.Email() != "test@example.com" {
t.Fatalf("Expected record with email field set to %q, got \n%v", "test@example.com", m2)
}
}
func TestBaseBindsCollection(t *testing.T) {
vm := goja.New()
baseBinds(vm)
v, err := vm.RunString(`new Collection({ name: "test", createRule: "@request.auth.id != ''", fields: [{name: "title", "type": "text"}] })`)
if err != nil {
t.Fatal(err)
}
m, ok := v.Export().(*core.Collection)
if !ok {
t.Fatalf("Expected core.Collection, got %v", m)
}
if m.Name != "test" {
t.Fatalf("Expected collection with name %q, got %q", "test", m.Name)
}
expectedRule := "@request.auth.id != ''"
if m.CreateRule == nil || *m.CreateRule != expectedRule {
t.Fatalf("Expected create rule %q, got %v", "@request.auth.id != ''", m.CreateRule)
}
if f := m.Fields.GetByName("title"); f == nil {
t.Fatalf("Expected fields to be set, got %v", m.Fields)
}
}
func TestBaseBindsFieldsList(t *testing.T) {
vm := goja.New()
baseBinds(vm)
v, err := vm.RunString(`new FieldsList([{name: "title", "type": "text"}])`)
if err != nil {
t.Fatal(err)
}
m, ok := v.Export().(*core.FieldsList)
if !ok {
t.Fatalf("Expected core.FieldsList, got %v", m)
}
if f := m.GetByName("title"); f == nil {
t.Fatalf("Expected fields list to be loaded, got %v", m)
}
}
func TestBaseBindsField(t *testing.T) {
vm := goja.New()
baseBinds(vm)
v, err := vm.RunString(`new Field({name: "test", "type": "bool"})`)
if err != nil {
t.Fatal(err)
}
f, ok := v.Export().(*core.BoolField)
if !ok {
t.Fatalf("Expected *core.BoolField, got %v", f)
}
if f.Name != "test" {
t.Fatalf("Expected field %q, got %v", "test", f)
}
}
func isType[T any](v any) bool {
_, ok := v.(T)
return ok
}
func TestBaseBindsNamedFields(t *testing.T) {
t.Parallel()
vm := goja.New()
baseBinds(vm)
scenarios := []struct {
js string
typeFunc func(v any) bool
}{
{
"new NumberField({name: 'test'})",
isType[*core.NumberField],
},
{
"new BoolField({name: 'test'})",
isType[*core.BoolField],
},
{
"new TextField({name: 'test'})",
isType[*core.TextField],
},
{
"new URLField({name: 'test'})",
isType[*core.URLField],
},
{
"new EmailField({name: 'test'})",
isType[*core.EmailField],
},
{
"new EditorField({name: 'test'})",
isType[*core.EditorField],
},
{
"new PasswordField({name: 'test'})",
isType[*core.PasswordField],
},
{
"new DateField({name: 'test'})",
isType[*core.DateField],
},
{
"new AutodateField({name: 'test'})",
isType[*core.AutodateField],
},
{
"new JSONField({name: 'test'})",
isType[*core.JSONField],
},
{
"new RelationField({name: 'test'})",
isType[*core.RelationField],
},
{
"new SelectField({name: 'test'})",
isType[*core.SelectField],
},
{
"new FileField({name: 'test'})",
isType[*core.FileField],
},
{
"new GeoPointField({name: 'test'})",
isType[*core.GeoPointField],
},
}
for _, s := range scenarios {
t.Run(s.js, func(t *testing.T) {
v, err := vm.RunString(s.js)
if err != nil {
t.Fatal(err)
}
f, ok := v.Export().(core.Field)
if !ok {
t.Fatalf("Expected core.Field instance, got %T (%v)", f, f)
}
if !s.typeFunc(f) {
t.Fatalf("Unexpected field type %T (%v)", f, f)
}
if f.GetName() != "test" {
t.Fatalf("Expected field %q, got %v", "test", f)
}
})
}
}
func TestBaseBindsMailerMessage(t *testing.T) {
vm := goja.New()
baseBinds(vm)
v, err := vm.RunString(`new MailerMessage({
from: {name: "test_from", address: "test_from@example.com"},
to: [
{name: "test_to1", address: "test_to1@example.com"},
{name: "test_to2", address: "test_to2@example.com"},
],
bcc: [
{name: "test_bcc1", address: "test_bcc1@example.com"},
{name: "test_bcc2", address: "test_bcc2@example.com"},
],
cc: [
{name: "test_cc1", address: "test_cc1@example.com"},
{name: "test_cc2", address: "test_cc2@example.com"},
],
subject: "test_subject",
html: "test_html",
text: "test_text",
headers: {
header1: "a",
header2: "b",
}
})`)
if err != nil {
t.Fatal(err)
}
m, ok := v.Export().(*mailer.Message)
if !ok {
t.Fatalf("Expected mailer.Message, got %v", m)
}
raw, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
expected := `{"from":{"Name":"test_from","Address":"test_from@example.com"},"to":[{"Name":"test_to1","Address":"test_to1@example.com"},{"Name":"test_to2","Address":"test_to2@example.com"}],"bcc":[{"Name":"test_bcc1","Address":"test_bcc1@example.com"},{"Name":"test_bcc2","Address":"test_bcc2@example.com"}],"cc":[{"Name":"test_cc1","Address":"test_cc1@example.com"},{"Name":"test_cc2","Address":"test_cc2@example.com"}],"subject":"test_subject","html":"test_html","text":"test_text","headers":{"header1":"a","header2":"b"},"attachments":null,"inlineAttachments":null}`
if string(raw) != expected {
t.Fatalf("Expected \n%s, \ngot \n%s", expected, raw)
}
}
func TestBaseBindsCommand(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
let runCalls = 0;
let cmd = new Command({
use: "test",
run: (c, args) => {
runCalls++;
}
});
cmd.run(null, []);
if (cmd.use != "test") {
throw new Error('Expected cmd.use "test", got: ' + cmd.use);
}
if (runCalls != 1) {
throw new Error('Expected runCalls 1, got: ' + runCalls);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsRequestInfo(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
const info = new RequestInfo({
body: {"name": "test2"}
});
if (info.body?.name != "test2") {
throw new Error('Expected info.body.name to be test2, got: ' + info.body?.name);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsMiddleware(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
const m = new Middleware(
(e) => {},
10,
"test"
);
if (!m) {
throw new Error('Expected non-empty Middleware instance');
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsTimezone(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
const v0 = (new Timezone()).string();
if (v0 != "UTC") {
throw new Error("(v0) Expected UTC got " + v0)
}
const v1 = (new Timezone("invalid")).string();
if (v1 != "UTC") {
throw new Error("(v1) Expected UTC got " + v1)
}
const v2 = (new Timezone("EET")).string();
if (v2 != "EET") {
throw new Error("(v2) Expected EET got " + v2)
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsDateTime(t *testing.T) {
vm := goja.New()
baseBinds(vm)
_, err := vm.RunString(`
const now = new DateTime();
if (now.isZero()) {
throw new Error('(now) Expected to fallback to now, got zero value');
}
const nowPart = now.string().substring(0, 19)
const scenarios = [
// empty datetime string and no custom location
{date: new DateTime(''), expected: nowPart},
// empty datetime string and custom default location (should be ignored)
{date: new DateTime('', 'Asia/Tokyo'), expected: nowPart},
// full datetime string and no custom default location
{date: new DateTime('2023-01-01 00:00:00.000Z'), expected: "2023-01-01 00:00:00.000Z"},
// invalid location (fallback to UTC)
{date: new DateTime('2025-10-26 03:00:00', 'invalid'), expected: "2025-10-26 03:00:00.000Z"},
// CET
{date: new DateTime('2025-10-26 03:00:00', 'Europe/Amsterdam'), expected: "2025-10-26 02:00:00.000Z"},
// CEST
{date: new DateTime('2025-10-26 01:00:00', 'Europe/Amsterdam'), expected: "2025-10-25 23:00:00.000Z"},
// with timezone/offset in the date string (aka. should ignore the custom default location)
{date: new DateTime('2025-10-26 01:00:00 +0200', 'Asia/Tokyo'), expected: "2025-10-25 23:00:00.000Z"},
];
for (let i = 0; i < scenarios.length; i++) {
const s = scenarios[i];
if (!s.date.string().includes(s.expected)) {
throw new Error('(' + i + ') ' + s.date.string() + ' does not contain expected ' + s.expected);
}
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestBaseBindsValidationError(t *testing.T) {
vm := goja.New()
baseBinds(vm)
scenarios := []struct {
js string
expectCode string
expectMessage string
}{
{
`new ValidationError()`,
"",
"",
},
{
`new ValidationError("test_code")`,
"test_code",
"",
},
{
`new ValidationError("test_code", "test_message")`,
"test_code",
"test_message",
},
}
for _, s := range scenarios {
v, err := vm.RunString(s.js)
if err != nil {
t.Fatal(err)
}
m, ok := v.Export().(validation.Error)
if !ok {
t.Fatalf("[%s] Expected validation.Error, got %v", s.js, m)
}
if m.Code() != s.expectCode {
t.Fatalf("[%s] Expected code %q, got %q", s.js, s.expectCode, m.Code())
}
if m.Message() != s.expectMessage {
t.Fatalf("[%s] Expected message %q, got %q", s.js, s.expectMessage, m.Message())
}
}
}
func TestDbxBinds(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
vm := goja.New()
vm.Set("db", app.DB())
baseBinds(vm)
dbxBinds(vm)
testBindsCount(vm, "$dbx", 15, t)
sceneraios := []struct {
js string
expected string
}{
{
`$dbx.exp("a = 1").build(db, {})`,
"a = 1",
},
{
`$dbx.hashExp({
"a": 1,
b: null,
c: [1, 2, 3],
}).build(db, {})`,
"`a`={:p0} AND `b` IS NULL AND `c` IN ({:p1}, {:p2}, {:p3})",
},
{
`$dbx.not($dbx.exp("a = 1")).build(db, {})`,
"NOT (a = 1)",
},
{
`$dbx.and($dbx.exp("a = 1"), $dbx.exp("b = 2")).build(db, {})`,
"(a = 1) AND (b = 2)",
},
{
`$dbx.or($dbx.exp("a = 1"), $dbx.exp("b = 2")).build(db, {})`,
"(a = 1) OR (b = 2)",
},
{
`$dbx.in("a", 1, 2, 3).build(db, {})`,
"`a` IN ({:p0}, {:p1}, {:p2})",
},
{
`$dbx.notIn("a", 1, 2, 3).build(db, {})`,
"`a` NOT IN ({:p0}, {:p1}, {:p2})",
},
{
`$dbx.like("a", "test1", "test2").match(true, false).build(db, {})`,
"`a` LIKE {:p0} AND `a` LIKE {:p1}",
},
{
`$dbx.orLike("a", "test1", "test2").match(false, true).build(db, {})`,
"`a` LIKE {:p0} OR `a` LIKE {:p1}",
},
{
`$dbx.notLike("a", "test1", "test2").match(true, false).build(db, {})`,
"`a` NOT LIKE {:p0} AND `a` NOT LIKE {:p1}",
},
{
`$dbx.orNotLike("a", "test1", "test2").match(false, false).build(db, {})`,
"`a` NOT LIKE {:p0} OR `a` NOT LIKE {:p1}",
},
{
`$dbx.exists($dbx.exp("a = 1")).build(db, {})`,
"EXISTS (a = 1)",
},
{
`$dbx.notExists($dbx.exp("a = 1")).build(db, {})`,
"NOT EXISTS (a = 1)",
},
{
`$dbx.between("a", 1, 2).build(db, {})`,
"`a` BETWEEN {:p0} AND {:p1}",
},
{
`$dbx.notBetween("a", 1, 2).build(db, {})`,
"`a` NOT BETWEEN {:p0} AND {:p1}",
},
}
for _, s := range sceneraios {
result, err := vm.RunString(s.js)
if err != nil {
t.Fatalf("[%s] Failed to execute js script, got %v", s.js, err)
}
v, _ := result.Export().(string)
if v != s.expected {
t.Fatalf("[%s] Expected \n%s, \ngot \n%s", s.js, s.expected, v)
}
}
}
func TestMailsBindsCount(t *testing.T) {
vm := goja.New()
mailsBinds(vm)
testBindsCount(vm, "$mails", 5, t)
}
func TestMailsBinds(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
record, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
vm := goja.New()
baseBinds(vm)
mailsBinds(vm)
vm.Set("$app", app)
vm.Set("record", record)
_, vmErr := vm.RunString(`
$mails.sendRecordPasswordReset($app, record);
if (!$app.testMailer.lastMessage().html.includes("/_/#/auth/confirm-password-reset/")) {
throw new Error("Expected record password reset email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
$mails.sendRecordVerification($app, record);
if (!$app.testMailer.lastMessage().html.includes("/_/#/auth/confirm-verification/")) {
throw new Error("Expected record verification email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
$mails.sendRecordChangeEmail($app, record, "new@example.com");
if (!$app.testMailer.lastMessage().html.includes("/_/#/auth/confirm-email-change/")) {
throw new Error("Expected record email change email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
$mails.sendRecordOTP($app, record, "test_otp_id", "test_otp_pass");
if (!$app.testMailer.lastMessage().html.includes("test_otp_pass")) {
throw new Error("Expected record OTP email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
$mails.sendRecordAuthAlert($app, record, "test_alert_info");
if (!$app.testMailer.lastMessage().html.includes("test_alert_info")) {
throw new Error("Expected record OTP email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
`)
if vmErr != nil {
t.Fatal(vmErr)
}
}
func TestSecurityBindsCount(t *testing.T) {
vm := goja.New()
securityBinds(vm)
testBindsCount(vm, "$security", 16, t)
}
func TestSecurityCryptoBinds(t *testing.T) {
vm := goja.New()
baseBinds(vm)
securityBinds(vm)
sceneraios := []struct {
js string
expected string
}{
{`$security.md5("123")`, "202cb962ac59075b964b07152d234b70"},
{`$security.sha256("123")`, "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"},
{`$security.sha512("123")`, "3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2"},
{`$security.hs256("hello", "test")`, "f151ea24bda91a18e89b8bb5793ef324b2a02133cce15a28a719acbd2e58a986"},
{`$security.hs512("hello", "test")`, "44f280e11103e295c26cd61dd1cdd8178b531b860466867c13b1c37a26b6389f8af110efbe0bb0717b9d9c87f6fe1c97b3b1690936578890e5669abf279fe7fd"},
{`$security.equal("abc", "abc")`, "true"},
{`$security.equal("abc", "abcd")`, "false"},
}
for _, s := range sceneraios {
t.Run(s.js, func(t *testing.T) {
result, err := vm.RunString(s.js)
if err != nil {
t.Fatalf("Failed to execute js script, got %v", err)
}
v := cast.ToString(result.Export())
if v != s.expected {
t.Fatalf("Expected %v \ngot \n%v", s.expected, v)
}
})
}
}
func TestSecurityRandomStringBinds(t *testing.T) {
vm := goja.New()
baseBinds(vm)
securityBinds(vm)
sceneraios := []struct {
js string
length int
}{
{`$security.randomString(6)`, 6},
{`$security.randomStringWithAlphabet(7, "abc")`, 7},
{`$security.pseudorandomString(8)`, 8},
{`$security.pseudorandomStringWithAlphabet(9, "abc")`, 9},
{`$security.randomStringByRegex("abc")`, 3},
}
for _, s := range sceneraios {
t.Run(s.js, func(t *testing.T) {
result, err := vm.RunString(s.js)
if err != nil {
t.Fatalf("Failed to execute js script, got %v", err)
}
v, _ := result.Export().(string)
if len(v) != s.length {
t.Fatalf("Expected %d length string, \ngot \n%v", s.length, v)
}
})
}
}
func TestSecurityJWTBinds(t *testing.T) {
sceneraios := []struct {
name string
js string
}{
{
"$security.parseUnverifiedJWT",
`
const result = $security.parseUnverifiedJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.aXzC7q7z1lX_hxk5P0R368xEU7H1xRwnBQQcLAmG0EY")
if (result.name != "John Doe") {
throw new Error("Expected result.name 'John Doe', got " + result.name)
}
if (result.sub != "1234567890") {
throw new Error("Expected result.sub '1234567890', got " + result.sub)
}
`,
},
{
"$security.parseJWT",
`
const result = $security.parseJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.aXzC7q7z1lX_hxk5P0R368xEU7H1xRwnBQQcLAmG0EY", "test")
if (result.name != "John Doe") {
throw new Error("Expected result.name 'John Doe', got " + result.name)
}
if (result.sub != "1234567890") {
throw new Error("Expected result.sub '1234567890', got " + result.sub)
}
`,
},
{
"$security.createJWT",
`
// overwrite the exp claim for static token
const result = $security.createJWT({"exp": 123}, "test", 0)
const expected = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEyM30.7gbv7w672gApdBRASI6OniCtKwkKjhieSxsr6vxSrtw";
if (result != expected) {
throw new Error("Expected token \n" + expected + ", got \n" + result)
}
`,
},
}
for _, s := range sceneraios {
t.Run(s.name, func(t *testing.T) {
vm := goja.New()
baseBinds(vm)
securityBinds(vm)
_, err := vm.RunString(s.js)
if err != nil {
t.Fatalf("Failed to execute js script, got %v", err)
}
})
}
}
func TestSecurityEncryptAndDecryptBinds(t *testing.T) {
vm := goja.New()
baseBinds(vm)
securityBinds(vm)
_, err := vm.RunString(`
const key = "abcdabcdabcdabcdabcdabcdabcdabcd"
const encrypted = $security.encrypt("123", key)
const decrypted = $security.decrypt(encrypted, key)
if (decrypted != "123") {
throw new Error("Expected decrypted '123', got " + decrypted)
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestFilesystemBinds(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/error" {
w.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(w, "test")
}))
defer srv.Close()
vm := goja.New()
vm.Set("mh", &multipart.FileHeader{Filename: "test"})
vm.Set("testFile", filepath.Join(app.DataDir(), "data.db"))
vm.Set("baseURL", srv.URL)
baseBinds(vm)
filesystemBinds(vm)
testBindsCount(vm, "$filesystem", 4, t)
// fileFromPath
{
v, err := vm.RunString(`$filesystem.fileFromPath(testFile)`)
if err != nil {
t.Fatal(err)
}
file, _ := v.Export().(*filesystem.File)
if file == nil || file.OriginalName != "data.db" {
t.Fatalf("[fileFromPath] Expected file with name %q, got %v", file.OriginalName, file)
}
}
// fileFromBytes
{
v, err := vm.RunString(`$filesystem.fileFromBytes([1, 2, 3], "test")`)
if err != nil {
t.Fatal(err)
}
file, _ := v.Export().(*filesystem.File)
if file == nil || file.OriginalName != "test" {
t.Fatalf("[fileFromBytes] Expected file with name %q, got %v", file.OriginalName, file)
}
}
// fileFromMultipart
{
v, err := vm.RunString(`$filesystem.fileFromMultipart(mh)`)
if err != nil {
t.Fatal(err)
}
file, _ := v.Export().(*filesystem.File)
if file == nil || file.OriginalName != "test" {
t.Fatalf("[fileFromMultipart] Expected file with name %q, got %v", file.OriginalName, file)
}
}
// fileFromURL (success)
{
v, err := vm.RunString(`$filesystem.fileFromURL(baseURL + "/test")`)
if err != nil {
t.Fatal(err)
}
file, _ := v.Export().(*filesystem.File)
if file == nil || file.OriginalName != "test" {
t.Fatalf("[fileFromURL] Expected file with name %q, got %v", file.OriginalName, file)
}
}
// fileFromURL (failure)
{
_, err := vm.RunString(`$filesystem.fileFromURL(baseURL + "/error")`)
if err == nil {
t.Fatal("Expected url fetch error")
}
}
}
func TestFormsBinds(t *testing.T) {
vm := goja.New()
formsBinds(vm)
testBindsCount(vm, "this", 4, t)
}
func TestApisBindsCount(t *testing.T) {
vm := goja.New()
apisBinds(vm)
testBindsCount(vm, "this", 8, t)
testBindsCount(vm, "$apis", 11, t)
}
func TestApisBindsApiError(t *testing.T) {
vm := goja.New()
apisBinds(vm)
scenarios := []struct {
js string
expectStatus int
expectMessage string
expectData string
}{
{"new ApiError()", 0, "", "null"},
{"new ApiError(100, 'test', {'test': 1})", 100, "Test.", `{"test":1}`},
{"new NotFoundError()", 404, "The requested resource wasn't found.", "null"},
{"new NotFoundError('test', {'test': 1})", 404, "Test.", `{"test":1}`},
{"new BadRequestError()", 400, "Something went wrong while processing your request.", "null"},
{"new BadRequestError('test', {'test': 1})", 400, "Test.", `{"test":1}`},
{"new ForbiddenError()", 403, "You are not allowed to perform this request.", "null"},
{"new ForbiddenError('test', {'test': 1})", 403, "Test.", `{"test":1}`},
{"new UnauthorizedError()", 401, "Missing or invalid authentication.", "null"},
{"new UnauthorizedError('test', {'test': 1})", 401, "Test.", `{"test":1}`},
{"new TooManyRequestsError()", 429, "Too Many Requests.", "null"},
{"new TooManyRequestsError('test', {'test': 1})", 429, "Test.", `{"test":1}`},
{"new InternalServerError()", 500, "Something went wrong while processing your request.", "null"},
{"new InternalServerError('test', {'test': 1})", 500, "Test.", `{"test":1}`},
}
for _, s := range scenarios {
v, err := vm.RunString(s.js)
if err != nil {
t.Errorf("[%s] %v", s.js, err)
continue
}
apiErr, ok := v.Export().(*router.ApiError)
if !ok {
t.Errorf("[%s] Expected ApiError, got %v", s.js, v)
continue
}
if apiErr.Status != s.expectStatus {
t.Errorf("[%s] Expected Status %d, got %d", s.js, s.expectStatus, apiErr.Status)
}
if apiErr.Message != s.expectMessage {
t.Errorf("[%s] Expected Message %q, got %q", s.js, s.expectMessage, apiErr.Message)
}
dataRaw, _ := json.Marshal(apiErr.RawData())
if string(dataRaw) != s.expectData {
t.Errorf("[%s] Expected Data %q, got %q", s.js, s.expectData, dataRaw)
}
}
}
func TestLoadingDynamicModel(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
vm := goja.New()
baseBinds(vm)
dbxBinds(vm)
vm.Set("$app", app)
_, err := vm.RunString(`
let result = new DynamicModel({
string: "",
nullString: nullString(),
nullStringEmpty: nullString(),
bool: false,
nullBool: nullBool(),
nullBoolEmpty: nullBool(),
int: 0,
nullInt: nullInt(),
nullIntEmpty: nullInt(),
float: -0,
nullFloat: nullFloat(),
nullFloatEmpty: nullFloat(),
array: [],
nullArray: nullArray(),
nullArrayEmpty: nullArray(),
object: {},
nullObject: nullObject(),
nullObjectEmpty: nullObject(),
})
const expectations = {
"string": "a",
"nullString": "b",
"nullStringEmpty": null,
"bool": false,
"nullBool": true,
"nullBoolEmpty": null,
"int": 1,
"nullInt": 2,
"nullIntEmpty": null,
"float": 1.1,
"nullFloat": 1.2,
"nullFloatEmpty": null,
"array": [1,2],
"nullArray": [3,4],
"nullArrayEmpty": null,
"object": {a:1},
"nullObject": {a:2},
"nullObjectEmpty": null,
};
// constuct dummy SELECT column value literals based on the expectations
const selectColumns = [];
for (const col in expectations) {
const val = expectations[col]
if (val === null) {
selectColumns.push("null as [[" + col + "]]")
} else if (typeof val === "string") {
selectColumns.push("'" + val + "' as [[" + col + "]]")
} else if (typeof val === "object") {
selectColumns.push("'" + JSON.stringify(val) + "' as [[" + col + "]]")
} else {
selectColumns.push(val + " as [[" + col + "]]")
}
}
$app.db()
.newQuery("SELECT " + selectColumns.join(", "))
.one(result)
for (const col in expectations) {
let expVal = expectations[col];
let resVal = result[col];
if (expVal !== null && typeof expVal === "object") {
expVal = JSON.stringify(expVal)
resVal = JSON.stringify(resVal)
}
if (expVal != resVal) {
throw new Error("Expected '" + col + "' value " + expVal + ", got " + resVal);
}
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestDynamicModelMapFieldCaching(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
vm := goja.New()
baseBinds(vm)
dbxBinds(vm)
vm.Set("$app", app)
_, err := vm.RunString(`
let m1 = new DynamicModel({
int: 0,
float: -0,
text: "",
bool: false,
obj: {},
arr: [],
})
let m2 = new DynamicModel({
int: 0,
float: -0,
text: "",
bool: false,
obj: {},
arr: [],
})
m1.int = 1
m1.float = 1.5
m1.text = "a"
m1.bool = true
m1.obj.set("a", 1)
m1.arr.push(1)
m2.int = 2
m2.float = 2.5
m2.text = "b"
m2.bool = false
m2.obj.set("b", 1)
m2.arr.push(2)
let m1Expected = '{"arr":[1],"bool":true,"float":1.5,"int":1,"obj":{"a":1},"text":"a"}';
let m1Serialized = JSON.stringify(m1);
if (m1Serialized != m1Expected) {
throw new Error("Expected m1 \n" + m1Expected + "\ngot\n" + m1Serialized);
}
let m2Expected = '{"arr":[2],"bool":false,"float":2.5,"int":2,"obj":{"b":1},"text":"b"}';
let m2Serialized = JSON.stringify(m2);
if (m2Serialized != m2Expected) {
throw new Error("Expected m2 \n" + m2Expected + "\ngot\n" + m2Serialized);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestLoadingArrayOf(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
vm := goja.New()
baseBinds(vm)
dbxBinds(vm)
vm.Set("$app", app)
_, err := vm.RunString(`
let result = arrayOf(new DynamicModel({
id: "",
text: "",
}))
$app.db()
.select("id", "text")
.from("demo1")
.where($dbx.exp("id='84nmscqy84lsi1t' OR id='al1h9ijdeojtsjy'"))
.limit(2)
.orderBy("text ASC")
.all(result)
if (result.length != 2) {
throw new Error('Expected 2 list items, got ' + result.length);
}
if (result[0].id != "84nmscqy84lsi1t") {
throw new Error('Expected 0.id "84nmscqy84lsi1t", got ' + result[0].id);
}
if (result[0].text != "test") {
throw new Error('Expected 0.text "test", got ' + result[0].text);
}
if (result[1].id != "al1h9ijdeojtsjy") {
throw new Error('Expected 1.id "al1h9ijdeojtsjy", got ' + result[1].id);
}
if (result[1].text != "test2") {
throw new Error('Expected 1.text "test2", got ' + result[1].text);
}
`)
if err != nil {
t.Fatal(err)
}
}
func TestHttpClientBindsCount(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
vm := goja.New()
httpClientBinds(vm)
testBindsCount(vm, "this", 2, t) // + FormData
testBindsCount(vm, "$http", 1, t)
}
func TestHttpClientBindsSend(t *testing.T) {
t.Parallel()
// start a test server
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/binds.go | plugins/jsvm/binds.go | package jsvm
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"slices"
"sort"
"strings"
"time"
"github.com/dop251/goja"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/router"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/store"
"github.com/pocketbase/pocketbase/tools/subscriptions"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
"github.com/spf13/cobra"
)
// hooksBinds adds wrapped "on*" hook methods by reflecting on core.App.
func hooksBinds(app core.App, loader *goja.Runtime, executors *vmsPool) {
fm := FieldMapper{}
appType := reflect.TypeOf(app)
appValue := reflect.ValueOf(app)
totalMethods := appType.NumMethod()
excludeHooks := []string{"OnServe"}
for i := 0; i < totalMethods; i++ {
method := appType.Method(i)
if !strings.HasPrefix(method.Name, "On") || slices.Contains(excludeHooks, method.Name) {
continue // not a hook or excluded
}
jsName := fm.MethodName(appType, method)
// register the hook to the loader
loader.Set(jsName, func(callback string, tags ...string) {
// overwrite the global $app with the hook scoped instance
callback = `function(e) { $app = e.app; return (` + callback + `).call(undefined, e) }`
pr := goja.MustCompile(defaultScriptPath, "{("+callback+").apply(undefined, __args)}", true)
tagsAsValues := make([]reflect.Value, len(tags))
for i, tag := range tags {
tagsAsValues[i] = reflect.ValueOf(tag)
}
hookInstance := appValue.MethodByName(method.Name).Call(tagsAsValues)[0]
hookBindFunc := hookInstance.MethodByName("BindFunc")
handlerType := hookBindFunc.Type().In(0)
handler := reflect.MakeFunc(handlerType, func(args []reflect.Value) (results []reflect.Value) {
handlerArgs := make([]any, len(args))
for i, arg := range args {
handlerArgs[i] = arg.Interface()
}
err := executors.run(func(executor *goja.Runtime) error {
executor.Set("$app", goja.Undefined())
executor.Set("__args", handlerArgs)
res, err := executor.RunProgram(pr)
executor.Set("__args", goja.Undefined())
// check for returned Go error value
if resErr := checkGojaValueForError(app, res); resErr != nil {
return resErr
}
return normalizeException(err)
})
return []reflect.Value{reflect.ValueOf(&err).Elem()}
})
// register the wrapped hook handler
hookBindFunc.Call([]reflect.Value{handler})
})
}
}
func cronBinds(app core.App, loader *goja.Runtime, executors *vmsPool) {
cronAdd := func(jobId, cronExpr, handler string) {
pr := goja.MustCompile(defaultScriptPath, "{("+handler+").apply(undefined)}", true)
err := app.Cron().Add(jobId, cronExpr, func() {
err := executors.run(func(executor *goja.Runtime) error {
_, err := executor.RunProgram(pr)
return err
})
if err != nil {
app.Logger().Error(
"[cronAdd] failed to execute cron job",
slog.String("jobId", jobId),
slog.String("error", err.Error()),
)
}
})
if err != nil {
panic("[cronAdd] failed to register cron job " + jobId + ": " + err.Error())
}
}
loader.Set("cronAdd", cronAdd)
cronRemove := func(jobId string) {
app.Cron().Remove(jobId)
}
loader.Set("cronRemove", cronRemove)
// register the removal helper also in the executors to allow removing cron jobs from everywhere
oldFactory := executors.factory
executors.factory = func() *goja.Runtime {
vm := oldFactory()
vm.Set("cronAdd", cronAdd)
vm.Set("cronRemove", cronRemove)
return vm
}
for _, item := range executors.items {
item.vm.Set("cronAdd", cronAdd)
item.vm.Set("cronRemove", cronRemove)
}
}
func routerBinds(app core.App, loader *goja.Runtime, executors *vmsPool) {
loader.Set("routerAdd", func(method string, path string, handler goja.Value, middlewares ...goja.Value) {
wrappedMiddlewares, err := wrapMiddlewares(executors, middlewares...)
if err != nil {
panic("[routerAdd] failed to wrap middlewares: " + err.Error())
}
wrappedHandler, err := wrapHandlerFunc(executors, handler)
if err != nil {
panic("[routerAdd] failed to wrap handler: " + err.Error())
}
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
e.Router.Route(strings.ToUpper(method), path, wrappedHandler).Bind(wrappedMiddlewares...)
return e.Next()
})
})
loader.Set("routerUse", func(middlewares ...goja.Value) {
wrappedMiddlewares, err := wrapMiddlewares(executors, middlewares...)
if err != nil {
panic("[routerUse] failed to wrap middlewares: " + err.Error())
}
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
e.Router.Bind(wrappedMiddlewares...)
return e.Next()
})
})
}
func wrapHandlerFunc(executors *vmsPool, handler goja.Value) (func(*core.RequestEvent) error, error) {
if handler == nil {
return nil, errors.New("handler must be non-nil")
}
switch h := handler.Export().(type) {
case func(*core.RequestEvent) error:
// "native" handler func - no need to wrap
return h, nil
case func(goja.FunctionCall) goja.Value, string:
pr := goja.MustCompile(defaultScriptPath, "{("+handler.String()+").apply(undefined, __args)}", true)
wrappedHandler := func(e *core.RequestEvent) error {
return executors.run(func(executor *goja.Runtime) error {
executor.Set("$app", e.App) // overwrite the global $app with the hook scoped instance
executor.Set("__args", []any{e})
res, err := executor.RunProgram(pr)
executor.Set("__args", goja.Undefined())
// check for returned Go error value
if resErr := checkGojaValueForError(e.App, res); resErr != nil {
return resErr
}
return normalizeException(err)
})
}
return wrappedHandler, nil
default:
return nil, errors.New("unsupported goja handler type")
}
}
type gojaHookHandler struct {
id string
serializedFunc string
priority int
}
func wrapMiddlewares(executors *vmsPool, rawMiddlewares ...goja.Value) ([]*hook.Handler[*core.RequestEvent], error) {
wrappedMiddlewares := make([]*hook.Handler[*core.RequestEvent], len(rawMiddlewares))
for i, m := range rawMiddlewares {
if m == nil {
return nil, errors.New("middleware must be non-nil")
}
switch v := m.Export().(type) {
case *hook.Handler[*core.RequestEvent]:
// "native" middleware handler - no need to wrap
wrappedMiddlewares[i] = v
case func(*core.RequestEvent) error:
// "native" middleware func - wrap as handler
wrappedMiddlewares[i] = &hook.Handler[*core.RequestEvent]{
Func: v,
}
case *gojaHookHandler:
if v.serializedFunc == "" {
return nil, errors.New("missing or invalid Middleware function")
}
pr := goja.MustCompile(defaultScriptPath, "{("+v.serializedFunc+").apply(undefined, __args)}", true)
wrappedMiddlewares[i] = &hook.Handler[*core.RequestEvent]{
Id: v.id,
Priority: v.priority,
Func: func(e *core.RequestEvent) error {
return executors.run(func(executor *goja.Runtime) error {
executor.Set("$app", e.App) // overwrite the global $app with the hook scoped instance
executor.Set("__args", []any{e})
res, err := executor.RunProgram(pr)
executor.Set("__args", goja.Undefined())
// check for returned Go error value
if resErr := checkGojaValueForError(e.App, res); resErr != nil {
return resErr
}
return normalizeException(err)
})
},
}
case func(goja.FunctionCall) goja.Value, string:
pr := goja.MustCompile(defaultScriptPath, "{("+m.String()+").apply(undefined, __args)}", true)
wrappedMiddlewares[i] = &hook.Handler[*core.RequestEvent]{
Func: func(e *core.RequestEvent) error {
return executors.run(func(executor *goja.Runtime) error {
executor.Set("$app", e.App) // overwrite the global $app with the hook scoped instance
executor.Set("__args", []any{e})
res, err := executor.RunProgram(pr)
executor.Set("__args", goja.Undefined())
// check for returned Go error value
if resErr := checkGojaValueForError(e.App, res); resErr != nil {
return resErr
}
return normalizeException(err)
})
},
}
default:
return nil, errors.New("unsupported goja middleware type")
}
}
return wrappedMiddlewares, nil
}
var cachedArrayOfTypes = store.New[reflect.Type, reflect.Type](nil)
func baseBinds(vm *goja.Runtime) {
vm.SetFieldNameMapper(FieldMapper{})
// deprecated: use toString
vm.Set("readerToString", func(r io.Reader, maxBytes int) (string, error) {
if maxBytes == 0 {
maxBytes = router.DefaultMaxMemory
}
limitReader := io.LimitReader(r, int64(maxBytes))
bodyBytes, readErr := io.ReadAll(limitReader)
if readErr != nil {
return "", readErr
}
return string(bodyBytes), nil
})
// note: throw only on reader error
vm.Set("toBytes", func(raw any, maxReaderBytes int) ([]byte, error) {
switch v := raw.(type) {
case nil:
return []byte{}, nil
case string:
return []byte(v), nil
case []byte:
return v, nil
case types.JSONRaw:
return v, nil
case io.Reader:
if maxReaderBytes == 0 {
maxReaderBytes = router.DefaultMaxMemory
}
limitReader := io.LimitReader(v, int64(maxReaderBytes))
return io.ReadAll(limitReader)
default:
b, err := cast.ToUint8SliceE(v)
if err == nil {
return b, nil
}
str, err := cast.ToStringE(v)
if err == nil {
return []byte(str), nil
}
// as a last attempt try to json encode the value
rawBytes, _ := json.Marshal(raw)
return rawBytes, nil
}
})
// note: throw only on reader error
vm.Set("toString", func(raw any, maxReaderBytes int) (string, error) {
switch v := raw.(type) {
case io.Reader:
if maxReaderBytes == 0 {
maxReaderBytes = router.DefaultMaxMemory
}
limitReader := io.LimitReader(v, int64(maxReaderBytes))
bodyBytes, readErr := io.ReadAll(limitReader)
if readErr != nil {
return "", readErr
}
return string(bodyBytes), nil
default:
str, err := cast.ToStringE(v)
if err == nil {
return str, nil
}
// as a last attempt try to json encode the value
rawBytes, _ := json.Marshal(raw)
return string(rawBytes), nil
}
})
vm.Set("sleep", func(milliseconds int64) {
time.Sleep(time.Duration(milliseconds) * time.Millisecond)
})
vm.Set("arrayOf", func(model any) any {
mt := reflect.TypeOf(model)
st := cachedArrayOfTypes.GetOrSet(mt, func() reflect.Type {
return reflect.SliceOf(mt)
})
return reflect.New(st).Elem().Addr().Interface()
})
vm.Set("unmarshal", func(data, dst any) error {
raw, err := json.Marshal(data)
if err != nil {
return err
}
return json.Unmarshal(raw, &dst)
})
vm.Set("Context", func(call goja.ConstructorCall) *goja.Object {
var instance context.Context
oldCtx, ok := call.Argument(0).Export().(context.Context)
if ok {
instance = oldCtx
} else {
instance = context.Background()
}
key := call.Argument(1).Export()
if key != nil {
instance = context.WithValue(instance, key, call.Argument(2).Export())
}
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
vm.Set("DynamicModel", func(call goja.ConstructorCall) *goja.Object {
shape, ok := call.Argument(0).Export().(map[string]any)
if !ok || len(shape) == 0 {
panic("[DynamicModel] missing shape data")
}
instance := newDynamicModel(shape)
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
// nullable helpers usually used as DynamicModel shape values
vm.Set("nullString", func() *string {
var v string
return &v
})
vm.Set("nullFloat", func() *float64 {
var v float64
return &v
})
vm.Set("nullInt", func() *int64 {
var v int64
return &v
})
vm.Set("nullBool", func() *bool {
var v bool
return &v
})
vm.Set("nullArray", func() *types.JSONArray[any] {
var v types.JSONArray[any]
return &v
})
vm.Set("nullObject", func() *types.JSONMap[any] {
var v types.JSONMap[any]
return &v
})
vm.Set("Record", func(call goja.ConstructorCall) *goja.Object {
var instance *core.Record
collection, ok := call.Argument(0).Export().(*core.Collection)
if ok {
instance = core.NewRecord(collection)
data, ok := call.Argument(1).Export().(map[string]any)
if ok {
instance.Load(data)
}
} else {
instance = &core.Record{}
}
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
vm.Set("Collection", func(call goja.ConstructorCall) *goja.Object {
instance := &core.Collection{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("FieldsList", func(call goja.ConstructorCall) *goja.Object {
instance := &core.FieldsList{}
return structConstructorUnmarshal(vm, call, instance)
})
// fields
// ---
vm.Set("Field", func(call goja.ConstructorCall) *goja.Object {
data, _ := call.Argument(0).Export().(map[string]any)
rawDataSlice, _ := json.Marshal([]any{data})
fieldsList := core.NewFieldsList()
_ = fieldsList.UnmarshalJSON(rawDataSlice)
if len(fieldsList) == 0 {
return nil
}
field := fieldsList[0]
fieldValue := vm.ToValue(field).(*goja.Object)
fieldValue.SetPrototype(call.This.Prototype())
return fieldValue
})
vm.Set("NumberField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.NumberField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("BoolField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.BoolField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("TextField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.TextField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("URLField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.URLField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("EmailField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.EmailField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("EditorField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.EditorField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("PasswordField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.PasswordField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("DateField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.DateField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("AutodateField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.AutodateField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("JSONField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.JSONField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("RelationField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.RelationField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("SelectField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.SelectField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("FileField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.FileField{}
return structConstructorUnmarshal(vm, call, instance)
})
vm.Set("GeoPointField", func(call goja.ConstructorCall) *goja.Object {
instance := &core.GeoPointField{}
return structConstructorUnmarshal(vm, call, instance)
})
// ---
vm.Set("MailerMessage", func(call goja.ConstructorCall) *goja.Object {
instance := &mailer.Message{}
return structConstructor(vm, call, instance)
})
vm.Set("Command", func(call goja.ConstructorCall) *goja.Object {
instance := &cobra.Command{}
return structConstructor(vm, call, instance)
})
vm.Set("RequestInfo", func(call goja.ConstructorCall) *goja.Object {
instance := &core.RequestInfo{Context: core.RequestInfoContextDefault}
return structConstructor(vm, call, instance)
})
// ```js
// new Middleware((e) => {
// return e.next()
// }, 100, "example_middleware")
// ```
vm.Set("Middleware", func(call goja.ConstructorCall) *goja.Object {
instance := &gojaHookHandler{}
instance.serializedFunc = call.Argument(0).String()
instance.priority = cast.ToInt(call.Argument(1).Export())
instance.id = cast.ToString(call.Argument(2).Export())
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
// note: named Timezone to avoid conflicts with the JS Location interface.
vm.Set("Timezone", func(call goja.ConstructorCall) *goja.Object {
name, _ := call.Argument(0).Export().(string)
instance, err := time.LoadLocation(name)
if err != nil {
instance = time.UTC
}
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
vm.Set("DateTime", func(call goja.ConstructorCall) *goja.Object {
instance := types.NowDateTime()
rawDate, _ := call.Argument(0).Export().(string)
locName, _ := call.Argument(1).Export().(string)
if rawDate != "" && locName != "" {
loc, err := time.LoadLocation(locName)
if err != nil {
loc = time.UTC
}
instance, _ = types.ParseDateTime(cast.ToTimeInDefaultLocation(rawDate, loc))
} else if rawDate != "" {
// forward directly to ParseDateTime to preserve the original behavior
instance, _ = types.ParseDateTime(rawDate)
}
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return structConstructor(vm, call, instance)
})
vm.Set("ValidationError", func(call goja.ConstructorCall) *goja.Object {
code, _ := call.Argument(0).Export().(string)
message, _ := call.Argument(1).Export().(string)
instance := validation.NewError(code, message)
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
vm.Set("Cookie", func(call goja.ConstructorCall) *goja.Object {
instance := &http.Cookie{}
return structConstructor(vm, call, instance)
})
vm.Set("SubscriptionMessage", func(call goja.ConstructorCall) *goja.Object {
instance := &subscriptions.Message{}
return structConstructor(vm, call, instance)
})
}
func dbxBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$dbx", obj)
obj.Set("exp", dbx.NewExp)
obj.Set("hashExp", func(data map[string]any) dbx.HashExp {
return dbx.HashExp(data)
})
obj.Set("not", dbx.Not)
obj.Set("and", dbx.And)
obj.Set("or", dbx.Or)
obj.Set("in", dbx.In)
obj.Set("notIn", dbx.NotIn)
obj.Set("like", dbx.Like)
obj.Set("orLike", dbx.OrLike)
obj.Set("notLike", dbx.NotLike)
obj.Set("orNotLike", dbx.OrNotLike)
obj.Set("exists", dbx.Exists)
obj.Set("notExists", dbx.NotExists)
obj.Set("between", dbx.Between)
obj.Set("notBetween", dbx.NotBetween)
}
func mailsBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$mails", obj)
obj.Set("sendRecordPasswordReset", mails.SendRecordPasswordReset)
obj.Set("sendRecordVerification", mails.SendRecordVerification)
obj.Set("sendRecordChangeEmail", mails.SendRecordChangeEmail)
obj.Set("sendRecordOTP", mails.SendRecordOTP)
obj.Set("sendRecordAuthAlert", mails.SendRecordAuthAlert)
}
func securityBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$security", obj)
// crypto
obj.Set("md5", security.MD5)
obj.Set("sha256", security.SHA256)
obj.Set("sha512", security.SHA512)
obj.Set("hs256", security.HS256)
obj.Set("hs512", security.HS512)
obj.Set("equal", security.Equal)
// random
obj.Set("randomString", security.RandomString)
obj.Set("randomStringByRegex", security.RandomStringByRegex)
obj.Set("randomStringWithAlphabet", security.RandomStringWithAlphabet)
obj.Set("pseudorandomString", security.PseudorandomString)
obj.Set("pseudorandomStringWithAlphabet", security.PseudorandomStringWithAlphabet)
// jwt
obj.Set("parseUnverifiedJWT", func(token string) (map[string]any, error) {
return security.ParseUnverifiedJWT(token)
})
obj.Set("parseJWT", func(token string, verificationKey string) (map[string]any, error) {
return security.ParseJWT(token, verificationKey)
})
obj.Set("createJWT", func(payload jwt.MapClaims, signingKey string, secDuration int) (string, error) {
return security.NewJWT(payload, signingKey, time.Duration(secDuration)*time.Second)
})
// encryption
obj.Set("encrypt", security.Encrypt)
obj.Set("decrypt", func(cipherText, key string) (string, error) {
result, err := security.Decrypt(cipherText, key)
if err != nil {
return "", err
}
return string(result), err
})
}
func filesystemBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$filesystem", obj)
obj.Set("fileFromPath", filesystem.NewFileFromPath)
obj.Set("fileFromBytes", filesystem.NewFileFromBytes)
obj.Set("fileFromMultipart", filesystem.NewFileFromMultipart)
obj.Set("fileFromURL", func(url string, secTimeout int) (*filesystem.File, error) {
if secTimeout == 0 {
secTimeout = 120
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(secTimeout)*time.Second)
defer cancel()
return filesystem.NewFileFromURL(ctx, url)
})
}
func filepathBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$filepath", obj)
obj.Set("base", filepath.Base)
obj.Set("clean", filepath.Clean)
obj.Set("dir", filepath.Dir)
obj.Set("ext", filepath.Ext)
obj.Set("fromSlash", filepath.FromSlash)
obj.Set("glob", filepath.Glob)
obj.Set("isAbs", filepath.IsAbs)
obj.Set("join", filepath.Join)
obj.Set("match", filepath.Match)
obj.Set("rel", filepath.Rel)
obj.Set("split", filepath.Split)
obj.Set("splitList", filepath.SplitList)
obj.Set("toSlash", filepath.ToSlash)
obj.Set("walk", filepath.Walk)
obj.Set("walkDir", filepath.WalkDir)
}
func osBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$os", obj)
obj.Set("args", os.Args)
obj.Set("exec", exec.Command) // @deprecated
obj.Set("cmd", exec.Command)
obj.Set("exit", os.Exit)
obj.Set("getenv", os.Getenv)
obj.Set("dirFS", os.DirFS)
obj.Set("stat", os.Stat)
obj.Set("readFile", os.ReadFile)
obj.Set("writeFile", os.WriteFile)
obj.Set("readDir", os.ReadDir)
obj.Set("tempDir", os.TempDir)
obj.Set("truncate", os.Truncate)
obj.Set("getwd", os.Getwd)
obj.Set("mkdir", os.Mkdir)
obj.Set("mkdirAll", os.MkdirAll)
obj.Set("rename", os.Rename)
obj.Set("remove", os.Remove)
obj.Set("removeAll", os.RemoveAll)
obj.Set("openRoot", os.OpenRoot)
obj.Set("openInRoot", os.OpenInRoot)
}
func formsBinds(vm *goja.Runtime) {
registerFactoryAsConstructor(vm, "AppleClientSecretCreateForm", forms.NewAppleClientSecretCreate)
registerFactoryAsConstructor(vm, "RecordUpsertForm", forms.NewRecordUpsert)
registerFactoryAsConstructor(vm, "TestEmailSendForm", forms.NewTestEmailSend)
registerFactoryAsConstructor(vm, "TestS3FilesystemForm", forms.NewTestS3Filesystem)
}
func apisBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$apis", obj)
obj.Set("static", func(dir string, indexFallback bool) func(*core.RequestEvent) error {
return apis.Static(os.DirFS(dir), indexFallback)
})
// middlewares
obj.Set("requireGuestOnly", apis.RequireGuestOnly)
obj.Set("requireAuth", apis.RequireAuth)
obj.Set("requireSuperuserAuth", apis.RequireSuperuserAuth)
obj.Set("requireSuperuserOrOwnerAuth", apis.RequireSuperuserOrOwnerAuth)
obj.Set("skipSuccessActivityLog", apis.SkipSuccessActivityLog)
obj.Set("gzip", apis.Gzip)
obj.Set("bodyLimit", apis.BodyLimit)
// record helpers
obj.Set("recordAuthResponse", apis.RecordAuthResponse)
obj.Set("enrichRecord", apis.EnrichRecord)
obj.Set("enrichRecords", apis.EnrichRecords)
// api errors
registerFactoryAsConstructor(vm, "ApiError", router.NewApiError)
registerFactoryAsConstructor(vm, "NotFoundError", router.NewNotFoundError)
registerFactoryAsConstructor(vm, "BadRequestError", router.NewBadRequestError)
registerFactoryAsConstructor(vm, "ForbiddenError", router.NewForbiddenError)
registerFactoryAsConstructor(vm, "UnauthorizedError", router.NewUnauthorizedError)
registerFactoryAsConstructor(vm, "TooManyRequestsError", router.NewTooManyRequestsError)
registerFactoryAsConstructor(vm, "InternalServerError", router.NewInternalServerError)
}
func httpClientBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$http", obj)
vm.Set("FormData", func(call goja.ConstructorCall) *goja.Object {
instance := FormData{}
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
type sendResult struct {
JSON any `json:"json"`
Headers map[string][]string `json:"headers"`
Cookies map[string]*http.Cookie `json:"cookies"`
// Deprecated: consider using Body instead
Raw string `json:"raw"`
Body []byte `json:"body"`
StatusCode int `json:"statusCode"`
}
type sendConfig struct {
// Deprecated: consider using Body instead
Data map[string]any
Body any // raw string or FormData
Headers map[string]string
Method string
Url string
Timeout int // seconds (default to 120)
}
obj.Set("send", func(params map[string]any) (*sendResult, error) {
config := sendConfig{
Method: "GET",
}
if v, ok := params["data"]; ok {
config.Data = cast.ToStringMap(v)
}
if v, ok := params["body"]; ok {
config.Body = v
}
if v, ok := params["headers"]; ok {
config.Headers = cast.ToStringMapString(v)
}
if v, ok := params["method"]; ok {
config.Method = cast.ToString(v)
}
if v, ok := params["url"]; ok {
config.Url = cast.ToString(v)
}
if v, ok := params["timeout"]; ok {
config.Timeout = cast.ToInt(v)
}
if config.Timeout <= 0 {
config.Timeout = 120
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second)
defer cancel()
var reqBody io.Reader
var contentType string
// legacy json body data
if len(config.Data) != 0 {
encoded, err := json.Marshal(config.Data)
if err != nil {
return nil, err
}
reqBody = bytes.NewReader(encoded)
} else {
switch v := config.Body.(type) {
case io.Reader:
reqBody = v
case FormData:
body, mp, err := v.toMultipart()
if err != nil {
return nil, err
}
reqBody = body
contentType = mp.FormDataContentType()
default:
reqBody = strings.NewReader(cast.ToString(config.Body))
}
}
req, err := http.NewRequestWithContext(ctx, strings.ToUpper(config.Method), config.Url, reqBody)
if err != nil {
return nil, err
}
for k, v := range config.Headers {
req.Header.Add(k, v)
}
// set the explicit content type
// (overwriting the user provided header value if any)
if contentType != "" {
req.Header.Set("content-type", contentType)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
bodyRaw, _ := io.ReadAll(res.Body)
result := &sendResult{
StatusCode: res.StatusCode,
Headers: map[string][]string{},
Cookies: map[string]*http.Cookie{},
Raw: string(bodyRaw),
Body: bodyRaw,
}
for k, v := range res.Header {
result.Headers[k] = v
}
for _, v := range res.Cookies() {
result.Cookies[v.Name] = v
}
if len(result.Body) > 0 {
// try as map
result.JSON = map[string]any{}
if err := json.Unmarshal(bodyRaw, &result.JSON); err != nil {
// try as slice
result.JSON = []any{}
if err := json.Unmarshal(bodyRaw, &result.JSON); err != nil {
result.JSON = nil
}
}
}
return result, nil
})
}
// -------------------------------------------------------------------
// checkGojaValueForError resolves the provided goja.Value and tries
// to extract its underlying error value (if any).
func checkGojaValueForError(app core.App, value goja.Value) error {
if value == nil {
return nil
}
exported := value.Export()
switch v := exported.(type) {
case error:
return v
case *goja.Promise:
// Promise as return result is not officially supported but try to
// resolve any thrown exception to avoid silently ignoring it
app.Logger().Warn("the handler must a non-async function and not return a Promise")
if promiseErr, ok := v.Result().Export().(error); ok {
return normalizeException(promiseErr)
}
}
return nil
}
// normalizeException checks if the provided error is a goja.Exception
// and attempts to return its underlying Go error.
//
// note: using just goja.Exception.Unwrap() is insufficient and may falsely result in nil.
func normalizeException(err error) error {
if err == nil {
return nil
}
jsException, ok := err.(*goja.Exception)
if !ok {
return err // no exception
}
switch v := jsException.Value().Export().(type) {
case error:
err = v
case map[string]any: // goja.GoError
if vErr, ok := v["value"].(error); ok {
err = vErr
}
}
return err
}
var cachedFactoryFuncTypes = store.New[string, reflect.Type](nil)
// registerFactoryAsConstructor registers the factory function as native JS constructor.
//
// If there is missing or nil arguments, their type zero value is used.
func registerFactoryAsConstructor(vm *goja.Runtime, constructorName string, factoryFunc any) {
rv := reflect.ValueOf(factoryFunc)
rt := cachedFactoryFuncTypes.GetOrSet(constructorName, func() reflect.Type {
return reflect.TypeOf(factoryFunc)
})
totalArgs := rt.NumIn()
vm.Set(constructorName, func(call goja.ConstructorCall) *goja.Object {
args := make([]reflect.Value, totalArgs)
for i := 0; i < totalArgs; i++ {
v := call.Argument(i).Export()
// use the arg type zero value
if v == nil {
args[i] = reflect.New(rt.In(i)).Elem()
} else if number, ok := v.(int64); ok {
// goja uses int64 for "int"-like numbers but we rarely do that and use int most of the times
// (at later stage we can use reflection on the arguments to validate the types in case this is not sufficient anymore)
args[i] = reflect.ValueOf(int(number))
} else {
args[i] = reflect.ValueOf(v)
}
}
result := rv.Call(args)
if len(result) != 1 {
panic("the factory function should return only 1 item")
}
value := vm.ToValue(result[0].Interface()).(*goja.Object)
value.SetPrototype(call.This.Prototype())
return value
})
}
// structConstructor wraps the provided struct with a native JS constructor.
//
// If the constructor argument is a map, each entry of the map will be loaded into the wrapped goja.Object.
func structConstructor(vm *goja.Runtime, call goja.ConstructorCall, instance any) *goja.Object {
data, _ := call.Argument(0).Export().(map[string]any)
instanceValue := vm.ToValue(instance).(*goja.Object)
for k, v := range data {
instanceValue.Set(k, v)
}
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
}
// structConstructorUnmarshal wraps the provided struct with a native JS constructor.
//
// The constructor first argument will be loaded via json.Unmarshal into the instance.
func structConstructorUnmarshal(vm *goja.Runtime, call goja.ConstructorCall, instance any) *goja.Object {
if data := call.Argument(0).Export(); data != nil {
if raw, err := json.Marshal(data); err == nil {
_ = json.Unmarshal(raw, instance)
}
}
instanceValue := vm.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
}
var cachedDynamicModelStructs = store.New[string, reflect.Type](nil)
// newDynamicModel creates a new dynamic struct with fields based
// on the specified "shape".
//
// The "shape" values are used as defaults and could be of type:
//
// - int64 (ex.: 0)
// - *int64 (ex.: nullInt())
// - float64 (ex.: -0)
// - *float64 (ex.: nullFloat())
// - string (ex.: "")
// - *string (ex.: nullString())
// - bool (ex.: false)
// - *bool (ex.: nullBool())
// - slice/arr (ex.: [])
// - *slice/arr (ex.: nullArray())
// - map (ex.: {})
// - *map (ex.: nullObject())
//
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/internal/types/types.go | plugins/jsvm/internal/types/types.go | package main
import (
"fmt"
"log"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/plugins/jsvm"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/tygoja"
)
const heading = `
// -------------------------------------------------------------------
// cronBinds
// -------------------------------------------------------------------
/**
* CronAdd registers a new cron job.
*
* If a cron job with the specified name already exist, it will be
* replaced with the new one.
*
* Example:
*
* ` + "```" + `js
* // prints "Hello world!" on every 30 minutes
* cronAdd("hello", "*\/30 * * * *", () => {
* console.log("Hello world!")
* })
* ` + "```" + `
*
* _Note that this method is available only in pb_hooks context._
*
* @group PocketBase
*/
declare function cronAdd(
jobId: string,
cronExpr: string,
handler: () => void,
): void;
/**
* CronRemove removes a single registered cron job by its name.
*
* Example:
*
* ` + "```" + `js
* cronRemove("hello")
* ` + "```" + `
*
* _Note that this method is available only in pb_hooks context._
*
* @group PocketBase
*/
declare function cronRemove(jobId: string): void;
// -------------------------------------------------------------------
// routerBinds
// -------------------------------------------------------------------
/**
* RouterAdd registers a new route definition.
*
* Example:
*
* ` + "```" + `js
* routerAdd("GET", "/hello", (e) => {
* return e.json(200, {"message": "Hello!"})
* }, $apis.requireAuth())
* ` + "```" + `
*
* _Note that this method is available only in pb_hooks context._
*
* @group PocketBase
*/
declare function routerAdd(
method: string,
path: string,
handler: (e: core.RequestEvent) => void,
...middlewares: Array<string|((e: core.RequestEvent) => void)|Middleware>,
): void;
/**
* RouterUse registers one or more global middlewares that are executed
* along the handler middlewares after a matching route is found.
*
* Example:
*
* ` + "```" + `js
* routerUse((e) => {
* console.log(e.request.url.path)
* return e.next()
* })
* ` + "```" + `
*
* _Note that this method is available only in pb_hooks context._
*
* @group PocketBase
*/
declare function routerUse(...middlewares: Array<string|((e: core.RequestEvent) => void)|Middleware>): void;
// -------------------------------------------------------------------
// baseBinds
// -------------------------------------------------------------------
/**
* Global helper variable that contains the absolute path to the app pb_hooks directory.
*
* @group PocketBase
*/
declare var __hooks: string
// Utility type to exclude the on* hook methods from a type
// (hooks are separately generated as global methods).
//
// See https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as
type excludeHooks<Type> = {
[Property in keyof Type as Exclude<Property, ` + "`on${string}`" + `|'cron'>]: Type[Property]
};
// core.App without the on* hook methods
type CoreApp = excludeHooks<ORIGINAL_CORE_APP>
// pocketbase.PocketBase without the on* hook methods
type PocketBase = excludeHooks<ORIGINAL_POCKETBASE>
/**
* ` + "`$app`" + ` is the current running PocketBase instance that is globally
* available in each .pb.js file.
*
* _Note that this variable is available only in pb_hooks context._
*
* @namespace
* @group PocketBase
*/
declare var $app: PocketBase
/**
* ` + "`$template`" + ` is a global helper to load and cache HTML templates on the fly.
*
* The templates uses the standard Go [html/template](https://pkg.go.dev/html/template)
* and [text/template](https://pkg.go.dev/text/template) package syntax.
*
* Example:
*
* ` + "```" + `js
* const html = $template.loadFiles(
* "views/layout.html",
* "views/content.html",
* ).render({"name": "John"})
* ` + "```" + `
*
* @namespace
* @group PocketBase
*/
declare var $template: template.Registry
/**
* This method is superseded by toString.
*
* @deprecated
* @group PocketBase
*/
declare function readerToString(reader: any, maxBytes?: number): string;
/**
* toString stringifies the specified value.
*
* Support optional second maxBytes argument to limit the max read bytes
* when the value is a io.Reader (default to 32MB).
*
* Types that don't have explicit string representation are json serialized.
*
* Example:
*
* ` + "```" + `js
* // io.Reader
* const ex1 = toString(e.request.body)
*
* // slice of bytes
* const ex2 = toString([104 101 108 108 111]) // "hello"
*
* // null
* const ex3 = toString(null) // ""
* ` + "```" + `
*
* @group PocketBase
*/
declare function toString(val: any, maxBytes?: number): string;
/**
* toBytes converts the specified value into a bytes slice.
*
* Support optional second maxBytes argument to limit the max read bytes
* when the value is a io.Reader (default to 32MB).
*
* Types that don't have Go slice representation (bool, objects, etc.)
* are serialized to UTF8 string and its bytes slice is returned.
*
* Example:
*
* ` + "```" + `js
* // io.Reader
* const ex1 = toBytes(e.request.body)
*
* // string
* const ex2 = toBytes("hello") // [104 101 108 108 111]
*
* // object (the same as the string '{"test":1}')
* const ex3 = toBytes({"test":1}) // [123 34 116 101 115 116 34 58 49 125]
*
* // null
* const ex4 = toBytes(null) // []
* ` + "```" + `
*
* @group PocketBase
*/
declare function toBytes(val: any, maxBytes?: number): Array<number>;
/**
* sleep pauses the current goroutine for at least the specified user duration (in ms).
* A zero or negative duration returns immediately.
*
* Example:
*
* ` + "```" + `js
* sleep(250) // sleeps for 250ms
* ` + "```" + `
*
* @group PocketBase
*/
declare function sleep(milliseconds: number): void;
/**
* arrayOf creates a placeholder array of the specified models.
* Usually used to populate DB result into an array of models.
*
* Example:
*
* ` + "```" + `js
* const records = arrayOf(new Record)
*
* $app.recordQuery("articles").limit(10).all(records)
* ` + "```" + `
*
* @group PocketBase
*/
declare function arrayOf<T>(model: T): Array<T>;
/**
* DynamicModel creates a new dynamic model with fields from the provided data shape.
*
* Caveats:
* - In order to use 0 as double/float initialization number you have to negate it (` + "`-0`" + `).
* - You need to use lowerCamelCase when accessing the model fields (e.g. ` + "`model.roles`" + ` and not ` + "`model.Roles`" + ` even if in the model shape and in the DB table the column is capitalized).
* - Objects are loaded into types.JSONMap, meaning that they need to be accessed with ` + "`get(key)`" + ` (e.g. ` + "`model.meta.get('something')`" + `).
* - For describing nullable types you can use the ` + "`null*()`" + ` helpers - ` + "`nullString()`" + `, ` + "`nullInt()`" + `, ` + "`nullFloat()`" + `, ` + "`nullBool()`" + `, ` + "`nullArray()`" + `, ` + "`nullObject()`" + `.
*
* Example:
*
* ` + "```" + `js
* const model = new DynamicModel({
* name: "" // or nullString() if nullable
* age: 0, // or nullInt() if nullable
* totalSpent: -0, // or nullFloat() if nullable
* active: false, // or nullBool() if nullable
* Roles: [], // or nullArray() if nullable; maps to "Roles" in the DB/JSON but the prop would be accessible via "model.roles"
* meta: {}, // or nullObject() if nullable
* })
* ` + "```" + `
*
* @group PocketBase
*/
declare class DynamicModel {
[key: string]: any;
constructor(shape?: { [key:string]: any })
}
/**
* nullString creates an empty Go string pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` string value.
*
* @group PocketBase
*/
declare function nullString(): string;
/**
* nullInt creates an empty Go int64 pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` int value.
*
* @group PocketBase
*/
declare function nullInt(): number;
/**
* nullFloat creates an empty Go float64 pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` float value.
*
* @group PocketBase
*/
declare function nullFloat(): number;
/**
* nullBool creates an empty Go bool pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` bool value.
*
* @group PocketBase
*/
declare function nullBool(): boolean;
/**
* nullArray creates an empty Go types.JSONArray pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` JSON array value.
*
* @group PocketBase
*/
declare function nullArray(): Array<any>;
/**
* nullObject creates an empty Go types.JSONMap pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` JSON object value.
*
* @group PocketBase
*/
declare function nullObject(): { get(key:string):any; set(key:string,value:any):void };
interface Context extends context.Context{} // merge
/**
* Context creates a new empty Go context.Context.
*
* This is usually used as part of some Go transitive bindings.
*
* Example:
*
* ` + "```" + `js
* const blank = new Context()
*
* // with single key-value pair
* const base = new Context(null, "a", 123)
* console.log(base.value("a")) // 123
*
* // extend with additional key-value pair
* const sub = new Context(base, "b", 456)
* console.log(sub.value("a")) // 123
* console.log(sub.value("b")) // 456
* ` + "```" + `
*
* @group PocketBase
*/
declare class Context implements context.Context {
constructor(parentCtx?: Context, key?: any, value?: any)
}
/**
* Record model class.
*
* ` + "```" + `js
* const collection = $app.findCollectionByNameOrId("article")
*
* const record = new Record(collection, {
* title: "Lorem ipsum"
* })
*
* // or set field values after the initialization
* record.set("description", "...")
* ` + "```" + `
*
* @group PocketBase
*/
declare const Record: {
new(collection?: core.Collection, data?: { [key:string]: any }): core.Record
// note: declare as "newable" const due to conflict with the Record TS utility type
}
interface Collection extends core.Collection{
type: "base" | "view" | "auth"
} // merge
/**
* Collection model class.
*
* ` + "```" + `js
* const collection = new Collection({
* type: "base",
* name: "article",
* listRule: "@request.auth.id != '' || status = 'public'",
* viewRule: "@request.auth.id != '' || status = 'public'",
* deleteRule: "@request.auth.id != ''",
* fields: [
* {
* name: "title",
* type: "text",
* required: true,
* min: 6,
* max: 100,
* },
* {
* name: "description",
* type: "text",
* },
* ]
* })
* ` + "```" + `
*
* @group PocketBase
*/
declare class Collection implements core.Collection {
constructor(data?: Partial<Collection>)
}
interface FieldsList extends core.FieldsList{} // merge
/**
* FieldsList model class, usually used to define the Collection.fields.
*
* @group PocketBase
*/
declare class FieldsList implements core.FieldsList {
constructor(data?: Partial<core.FieldsList>)
}
interface Field extends core.Field{} // merge
/**
* Field model class, usually used as part of the FieldsList model.
*
* @group PocketBase
*/
declare class Field implements core.Field {
constructor(data?: Partial<core.Field>)
}
interface NumberField extends core.NumberField{} // merge
/**
* {@inheritDoc core.NumberField}
*
* @group PocketBase
*/
declare class NumberField implements core.NumberField {
constructor(data?: Partial<core.NumberField>)
}
interface BoolField extends core.BoolField{} // merge
/**
* {@inheritDoc core.BoolField}
*
* @group PocketBase
*/
declare class BoolField implements core.BoolField {
constructor(data?: Partial<core.BoolField>)
}
interface TextField extends core.TextField{} // merge
/**
* {@inheritDoc core.TextField}
*
* @group PocketBase
*/
declare class TextField implements core.TextField {
constructor(data?: Partial<core.TextField>)
}
interface URLField extends core.URLField{} // merge
/**
* {@inheritDoc core.URLField}
*
* @group PocketBase
*/
declare class URLField implements core.URLField {
constructor(data?: Partial<core.URLField>)
}
interface EmailField extends core.EmailField{} // merge
/**
* {@inheritDoc core.EmailField}
*
* @group PocketBase
*/
declare class EmailField implements core.EmailField {
constructor(data?: Partial<core.EmailField>)
}
interface EditorField extends core.EditorField{} // merge
/**
* {@inheritDoc core.EditorField}
*
* @group PocketBase
*/
declare class EditorField implements core.EditorField {
constructor(data?: Partial<core.EditorField>)
}
interface PasswordField extends core.PasswordField{} // merge
/**
* {@inheritDoc core.PasswordField}
*
* @group PocketBase
*/
declare class PasswordField implements core.PasswordField {
constructor(data?: Partial<core.PasswordField>)
}
interface DateField extends core.DateField{} // merge
/**
* {@inheritDoc core.DateField}
*
* @group PocketBase
*/
declare class DateField implements core.DateField {
constructor(data?: Partial<core.DateField>)
}
interface AutodateField extends core.AutodateField{} // merge
/**
* {@inheritDoc core.AutodateField}
*
* @group PocketBase
*/
declare class AutodateField implements core.AutodateField {
constructor(data?: Partial<core.AutodateField>)
}
interface JSONField extends core.JSONField{} // merge
/**
* {@inheritDoc core.JSONField}
*
* @group PocketBase
*/
declare class JSONField implements core.JSONField {
constructor(data?: Partial<core.JSONField>)
}
interface RelationField extends core.RelationField{} // merge
/**
* {@inheritDoc core.RelationField}
*
* @group PocketBase
*/
declare class RelationField implements core.RelationField {
constructor(data?: Partial<core.RelationField>)
}
interface SelectField extends core.SelectField{} // merge
/**
* {@inheritDoc core.SelectField}
*
* @group PocketBase
*/
declare class SelectField implements core.SelectField {
constructor(data?: Partial<core.SelectField>)
}
interface FileField extends core.FileField{} // merge
/**
* {@inheritDoc core.FileField}
*
* @group PocketBase
*/
declare class FileField implements core.FileField {
constructor(data?: Partial<core.FileField>)
}
interface GeoPointField extends core.GeoPointField{} // merge
/**
* {@inheritDoc core.GeoPointField}
*
* @group PocketBase
*/
declare class GeoPointField implements core.GeoPointField {
constructor(data?: Partial<core.GeoPointField>)
}
interface MailerMessage extends mailer.Message{} // merge
/**
* MailerMessage defines a single email message.
*
* ` + "```" + `js
* const message = new MailerMessage({
* from: {
* address: $app.settings().meta.senderAddress,
* name: $app.settings().meta.senderName,
* },
* to: [{address: "test@example.com"}],
* subject: "YOUR_SUBJECT...",
* html: "YOUR_HTML_BODY...",
* })
*
* $app.newMailClient().send(message)
* ` + "```" + `
*
* @group PocketBase
*/
declare class MailerMessage implements mailer.Message {
constructor(message?: Partial<mailer.Message>)
}
interface Command extends cobra.Command{} // merge
/**
* Command defines a single console command.
*
* Example:
*
* ` + "```" + `js
* const command = new Command({
* use: "hello",
* run: (cmd, args) => { console.log("Hello world!") },
* })
*
* $app.rootCmd.addCommand(command);
* ` + "```" + `
*
* @group PocketBase
*/
declare class Command implements cobra.Command {
constructor(cmd?: Partial<cobra.Command>)
}
/**
* RequestInfo defines a single core.RequestInfo instance, usually used
* as part of various filter checks.
*
* Example:
*
* ` + "```" + `js
* const authRecord = $app.findAuthRecordByEmail("users", "test@example.com")
*
* const info = new RequestInfo({
* auth: authRecord,
* body: {"name": 123},
* headers: {"x-token": "..."},
* })
*
* const record = $app.findFirstRecordByData("articles", "slug", "hello")
*
* const canAccess = $app.canAccessRecord(record, info, "@request.auth.id != '' && @request.body.name = 123")
* ` + "```" + `
*
* @group PocketBase
*/
declare const RequestInfo: {
new(info?: Partial<core.RequestInfo>): core.RequestInfo
// note: declare as "newable" const due to conflict with the RequestInfo TS node type
}
/**
* Middleware defines a single request middleware handler.
*
* This class is usually used when you want to explicitly specify a priority to your custom route middleware.
*
* Example:
*
* ` + "```" + `js
* routerUse(new Middleware((e) => {
* console.log(e.request.url.path)
* return e.next()
* }, -10))
* ` + "```" + `
*
* @group PocketBase
*/
declare class Middleware {
constructor(
func: string|((e: core.RequestEvent) => void),
priority?: number,
id?: string,
)
}
interface Timezone extends time.Location{} // merge
/**
* Timezone returns the timezone location with the given name.
*
* The name is expected to be a location name corresponding to a file
* in the IANA Time Zone database, such as "America/New_York".
*
* If the name is "Local", LoadLocation returns Local.
*
* If the name is "", invalid or "UTC", returns UTC.
*
* The constructor is equivalent to calling the Go ` + "`" + `time.LoadLocation(name)` + "`" + ` method.
*
* Example:
*
* ` + "```" + `js
* const zone = new Timezone("America/New_York")
* $app.cron().setTimezone(zone)
* ` + "```" + `
*
* @group PocketBase
*/
declare class Timezone implements time.Location {
constructor(name?: string)
}
interface DateTime extends types.DateTime{} // merge
/**
* DateTime defines a single DateTime type instance.
* The returned date is always represented in UTC.
*
* Example:
*
* ` + "```" + `js
* const dt0 = new DateTime() // now
*
* // full datetime string
* const dt1 = new DateTime('2023-07-01 00:00:00.000Z')
*
* // datetime string with default "parse in" timezone location
* //
* // similar to new DateTime('2023-07-01 00:00:00 +01:00') or new DateTime('2023-07-01 00:00:00 +02:00')
* // but accounts for the daylight saving time (DST)
* const dt2 = new DateTime('2023-07-01 00:00:00', 'Europe/Amsterdam')
* ` + "```" + `
*
* @group PocketBase
*/
declare class DateTime implements types.DateTime {
constructor(date?: string, defaultParseInLocation?: string)
}
interface ValidationError extends ozzo_validation.Error{} // merge
/**
* ValidationError defines a single formatted data validation error,
* usually used as part of an error response.
*
* ` + "```" + `js
* new ValidationError("invalid_title", "Title is not valid")
* ` + "```" + `
*
* @group PocketBase
*/
declare class ValidationError implements ozzo_validation.Error {
constructor(code?: string, message?: string)
}
interface Cookie extends http.Cookie{} // merge
/**
* A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an
* HTTP response.
*
* Example:
*
* ` + "```" + `js
* routerAdd("POST", "/example", (c) => {
* c.setCookie(new Cookie({
* name: "example_name",
* value: "example_value",
* path: "/",
* domain: "example.com",
* maxAge: 10,
* secure: true,
* httpOnly: true,
* sameSite: 3,
* }))
*
* return c.redirect(200, "/");
* })
* ` + "```" + `
*
* @group PocketBase
*/
declare class Cookie implements http.Cookie {
constructor(options?: Partial<http.Cookie>)
}
interface SubscriptionMessage extends subscriptions.Message{} // merge
/**
* SubscriptionMessage defines a realtime subscription payload.
*
* Example:
*
* ` + "```" + `js
* onRealtimeConnectRequest((e) => {
* e.client.send(new SubscriptionMessage({
* name: "example",
* data: '{"greeting": "Hello world"}'
* }))
* })
* ` + "```" + `
*
* @group PocketBase
*/
declare class SubscriptionMessage implements subscriptions.Message {
constructor(options?: Partial<subscriptions.Message>)
}
// -------------------------------------------------------------------
// dbxBinds
// -------------------------------------------------------------------
/**
* ` + "`$dbx`" + ` defines common utility for working with the DB abstraction.
* For examples and guides please check the [Database guide](https://pocketbase.io/docs/js-database).
*
* @group PocketBase
*/
declare namespace $dbx {
/**
* {@inheritDoc dbx.HashExp}
*/
export function hashExp(pairs: { [key:string]: any }): dbx.Expression
let _in: dbx._in
export { _in as in }
export let exp: dbx.newExp
export let not: dbx.not
export let and: dbx.and
export let or: dbx.or
export let notIn: dbx.notIn
export let like: dbx.like
export let orLike: dbx.orLike
export let notLike: dbx.notLike
export let orNotLike: dbx.orNotLike
export let exists: dbx.exists
export let notExists: dbx.notExists
export let between: dbx.between
export let notBetween: dbx.notBetween
}
// -------------------------------------------------------------------
// mailsBinds
// -------------------------------------------------------------------
/**
* ` + "`" + `$mails` + "`" + ` defines helpers to send common
* auth records emails like verification, password reset, etc.
*
* @group PocketBase
*/
declare namespace $mails {
let sendRecordPasswordReset: mails.sendRecordPasswordReset
let sendRecordVerification: mails.sendRecordVerification
let sendRecordChangeEmail: mails.sendRecordChangeEmail
let sendRecordOTP: mails.sendRecordOTP
let sendRecordAuthAlert: mails.sendRecordAuthAlert
}
// -------------------------------------------------------------------
// securityBinds
// -------------------------------------------------------------------
/**
* ` + "`" + `$security` + "`" + ` defines low level helpers for creating
* and parsing JWTs, random string generation, AES encryption, etc.
*
* @group PocketBase
*/
declare namespace $security {
let randomString: security.randomString
let randomStringWithAlphabet: security.randomStringWithAlphabet
let randomStringByRegex: security.randomStringByRegex
let pseudorandomString: security.pseudorandomString
let pseudorandomStringWithAlphabet: security.pseudorandomStringWithAlphabet
let encrypt: security.encrypt
let decrypt: security.decrypt
let hs256: security.hs256
let hs512: security.hs512
let equal: security.equal
let md5: security.md5
let sha256: security.sha256
let sha512: security.sha512
/**
* {@inheritDoc security.newJWT}
*/
export function createJWT(payload: { [key:string]: any }, signingKey: string, secDuration: number): string
/**
* {@inheritDoc security.parseUnverifiedJWT}
*/
export function parseUnverifiedJWT(token: string): _TygojaDict
/**
* {@inheritDoc security.parseJWT}
*/
export function parseJWT(token: string, verificationKey: string): _TygojaDict
}
// -------------------------------------------------------------------
// filesystemBinds
// -------------------------------------------------------------------
/**
* ` + "`" + `$filesystem` + "`" + ` defines common helpers for working
* with the PocketBase filesystem abstraction.
*
* @group PocketBase
*/
declare namespace $filesystem {
let fileFromPath: filesystem.newFileFromPath
let fileFromBytes: filesystem.newFileFromBytes
let fileFromMultipart: filesystem.newFileFromMultipart
/**
* fileFromURL creates a new File from the provided url by
* downloading the resource and creating a BytesReader.
*
* Example:
*
* ` + "```" + `js
* // with default max timeout of 120sec
* const file1 = $filesystem.fileFromURL("https://...")
*
* // with custom timeout of 15sec
* const file2 = $filesystem.fileFromURL("https://...", 15)
* ` + "```" + `
*/
export function fileFromURL(url: string, secTimeout?: number): filesystem.File
}
// -------------------------------------------------------------------
// filepathBinds
// -------------------------------------------------------------------
/**
* ` + "`$filepath`" + ` defines common helpers for manipulating filename
* paths in a way compatible with the target operating system-defined file paths.
*
* @group PocketBase
*/
declare namespace $filepath {
export let base: filepath.base
export let clean: filepath.clean
export let dir: filepath.dir
export let ext: filepath.ext
export let fromSlash: filepath.fromSlash
export let glob: filepath.glob
export let isAbs: filepath.isAbs
export let join: filepath.join
export let match: filepath.match
export let rel: filepath.rel
export let split: filepath.split
export let splitList: filepath.splitList
export let toSlash: filepath.toSlash
export let walk: filepath.walk
export let walkDir: filepath.walkDir
}
// -------------------------------------------------------------------
// osBinds
// -------------------------------------------------------------------
/**
* ` + "`$os`" + ` defines common helpers for working with the OS level primitives
* (eg. deleting directories, executing shell commands, etc.).
*
* @group PocketBase
*/
declare namespace $os {
/**
* Legacy alias for $os.cmd().
*/
export let exec: exec.command
/**
* Prepares an external OS command.
*
* Example:
*
* ` + "```" + `js
* // prepare the command to execute
* const cmd = $os.cmd('ls', '-sl')
*
* // execute the command and return its standard output as string
* const output = toString(cmd.output());
* ` + "```" + `
*/
export let cmd: exec.command
/**
* Args hold the command-line arguments, starting with the program name.
*/
export let args: Array<string>
export let exit: os.exit
export let getenv: os.getenv
export let dirFS: os.dirFS
export let readFile: os.readFile
export let writeFile: os.writeFile
export let stat: os.stat
export let readDir: os.readDir
export let tempDir: os.tempDir
export let truncate: os.truncate
export let getwd: os.getwd
export let mkdir: os.mkdir
export let mkdirAll: os.mkdirAll
export let rename: os.rename
export let remove: os.remove
export let removeAll: os.removeAll
export let openRoot: os.openRoot
export let openInRoot: os.openInRoot
}
// -------------------------------------------------------------------
// formsBinds
// -------------------------------------------------------------------
interface AppleClientSecretCreateForm extends forms.AppleClientSecretCreate{} // merge
/**
* @inheritDoc
* @group PocketBase
*/
declare class AppleClientSecretCreateForm implements forms.AppleClientSecretCreate {
constructor(app: CoreApp)
}
interface RecordUpsertForm extends forms.RecordUpsert{} // merge
/**
* @inheritDoc
* @group PocketBase
*/
declare class RecordUpsertForm implements forms.RecordUpsert {
constructor(app: CoreApp, record: core.Record)
}
interface TestEmailSendForm extends forms.TestEmailSend{} // merge
/**
* @inheritDoc
* @group PocketBase
*/
declare class TestEmailSendForm implements forms.TestEmailSend {
constructor(app: CoreApp)
}
interface TestS3FilesystemForm extends forms.TestS3Filesystem{} // merge
/**
* @inheritDoc
* @group PocketBase
*/
declare class TestS3FilesystemForm implements forms.TestS3Filesystem {
constructor(app: CoreApp)
}
// -------------------------------------------------------------------
// apisBinds
// -------------------------------------------------------------------
interface ApiError extends router.ApiError{} // merge
/**
* @inheritDoc
*
* @group PocketBase
*/
declare class ApiError implements router.ApiError {
constructor(status?: number, message?: string, data?: any)
}
interface NotFoundError extends router.ApiError{} // merge
/**
* NotFounderor returns 404 ApiError.
*
* @group PocketBase
*/
declare class NotFoundError implements router.ApiError {
constructor(message?: string, data?: any)
}
interface BadRequestError extends router.ApiError{} // merge
/**
* BadRequestError returns 400 ApiError.
*
* @group PocketBase
*/
declare class BadRequestError implements router.ApiError {
constructor(message?: string, data?: any)
}
interface ForbiddenError extends router.ApiError{} // merge
/**
* ForbiddenError returns 403 ApiError.
*
* @group PocketBase
*/
declare class ForbiddenError implements router.ApiError {
constructor(message?: string, data?: any)
}
interface UnauthorizedError extends router.ApiError{} // merge
/**
* UnauthorizedError returns 401 ApiError.
*
* @group PocketBase
*/
declare class UnauthorizedError implements router.ApiError {
constructor(message?: string, data?: any)
}
interface TooManyRequestsError extends router.ApiError{} // merge
/**
* TooManyRequestsError returns 429 ApiError.
*
* @group PocketBase
*/
declare class TooManyRequestsError implements router.ApiError {
constructor(message?: string, data?: any)
}
interface InternalServerError extends router.ApiError{} // merge
/**
* InternalServerError returns 429 ApiError.
*
* @group PocketBase
*/
declare class InternalServerError implements router.ApiError {
constructor(message?: string, data?: any)
}
/**
* ` + "`" + `$apis` + "`" + ` defines commonly used PocketBase api helpers and middlewares.
*
* @group PocketBase
*/
declare namespace $apis {
/**
* Route handler to serve static directory content (html, js, css, etc.).
*
* If a file resource is missing and indexFallback is set, the request
* will be forwarded to the base index.html (useful for SPA).
*/
export function static(dir: string, indexFallback: boolean): (e: core.RequestEvent) => void
let requireGuestOnly: apis.requireGuestOnly
let requireAuth: apis.requireAuth
let requireSuperuserAuth: apis.requireSuperuserAuth
let requireSuperuserOrOwnerAuth: apis.requireSuperuserOrOwnerAuth
let skipSuccessActivityLog: apis.skipSuccessActivityLog
let gzip: apis.gzip
let bodyLimit: apis.bodyLimit
let enrichRecord: apis.enrichRecord
let enrichRecords: apis.enrichRecords
/**
* RecordAuthResponse writes standardized json record auth response
* into the specified request event.
*
* The authMethod argument specify the name of the current authentication method (eg. password, oauth2, etc.)
* that it is used primarily as an auth identifier during MFA and for login alerts.
*
* Set authMethod to empty string if you want to ignore the MFA checks and the login alerts
* (can be also adjusted additionally via the onRecordAuthRequest hook).
*/
export function recordAuthResponse(e: core.RequestEvent, authRecord: core.Record, authMethod: string, meta?: any): void
}
// -------------------------------------------------------------------
// httpClientBinds
// -------------------------------------------------------------------
// extra FormData overload to prevent TS warnings when used with non File/Blob value.
interface FormData {
append(key:string, value:any): void
set(key:string, value:any): void
}
/**
* ` + "`" + `$http` + "`" + ` defines common methods for working with HTTP requests.
*
* @group PocketBase
*/
declare namespace $http {
/**
* Sends a single HTTP request.
*
* Example:
*
* ` + "```" + `js
* const res = $http.send({
* method: "POST",
* url: "https://example.com",
* body: JSON.stringify({"title": "test"}),
* headers: { 'Content-Type': 'application/json' }
* })
*
* console.log(res.statusCode) // the response HTTP status code
* console.log(res.headers) // the response headers (eg. res.headers['X-Custom'][0])
* console.log(res.cookies) // the response cookies (eg. res.cookies.sessionId.value)
* console.log(res.body) // the response body as raw bytes slice
* console.log(res.json) // the response body as parsed json array or map
* ` + "```" + `
*/
function send(config: {
url: string,
body?: string|FormData,
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/jsvm/internal/types/generated/embed.go | plugins/jsvm/internal/types/generated/embed.go | package generated
import "embed"
//go:embed types.d.ts
var Types embed.FS
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/migratecmd/templates.go | plugins/migratecmd/templates.go | package migratecmd
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/pocketbase/pocketbase/core"
)
const (
TemplateLangJS = "js"
TemplateLangGo = "go"
// note: this usually should be configurable similar to the jsvm plugin,
// but for simplicity is static as users can easily change the
// reference path if they use custom dirs structure
jsTypesDirective = `/// <reference path="../pb_data/types.d.ts" />` + "\n"
)
var ErrEmptyTemplate = errors.New("empty template")
// -------------------------------------------------------------------
// JavaScript templates
// -------------------------------------------------------------------
func (p *plugin) jsBlankTemplate() (string, error) {
const template = jsTypesDirective + `migrate((app) => {
// add up queries...
}, (app) => {
// add down queries...
})
`
return template, nil
}
func (p *plugin) jsSnapshotTemplate(collections []*core.Collection) (string, error) {
// unset timestamp fields
var collectionsData = make([]map[string]any, len(collections))
for i, c := range collections {
data, err := toMap(c)
if err != nil {
return "", fmt.Errorf("failed to serialize %q into a map: %w", c.Name, err)
}
delete(data, "created")
delete(data, "updated")
deleteNestedMapKey(data, "oauth2", "providers")
collectionsData[i] = data
}
jsonData, err := marhshalWithoutEscape(collectionsData, " ", " ")
if err != nil {
return "", fmt.Errorf("failed to serialize collections list: %w", err)
}
const template = jsTypesDirective + `migrate((app) => {
const snapshot = %s;
return app.importCollections(snapshot, false);
}, (app) => {
return null;
})
`
return fmt.Sprintf(template, string(jsonData)), nil
}
func (p *plugin) jsCreateTemplate(collection *core.Collection) (string, error) {
// unset timestamp fields
collectionData, err := toMap(collection)
if err != nil {
return "", err
}
delete(collectionData, "created")
delete(collectionData, "updated")
deleteNestedMapKey(collectionData, "oauth2", "providers")
jsonData, err := marhshalWithoutEscape(collectionData, " ", " ")
if err != nil {
return "", fmt.Errorf("failed to serialize collection: %w", err)
}
const template = jsTypesDirective + `migrate((app) => {
const collection = new Collection(%s);
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId(%q);
return app.delete(collection);
})
`
return fmt.Sprintf(template, string(jsonData), collection.Id), nil
}
func (p *plugin) jsDeleteTemplate(collection *core.Collection) (string, error) {
// unset timestamp fields
collectionData, err := toMap(collection)
if err != nil {
return "", err
}
delete(collectionData, "created")
delete(collectionData, "updated")
deleteNestedMapKey(collectionData, "oauth2", "providers")
jsonData, err := marhshalWithoutEscape(collectionData, " ", " ")
if err != nil {
return "", fmt.Errorf("failed to serialize collections list: %w", err)
}
const template = jsTypesDirective + `migrate((app) => {
const collection = app.findCollectionByNameOrId(%q);
return app.delete(collection);
}, (app) => {
const collection = new Collection(%s);
return app.save(collection);
})
`
return fmt.Sprintf(template, collection.Id, string(jsonData)), nil
}
func (p *plugin) jsDiffTemplate(new *core.Collection, old *core.Collection) (string, error) {
if new == nil && old == nil {
return "", errors.New("the diff template require at least one of the collection to be non-nil")
}
if new == nil {
return p.jsDeleteTemplate(old)
}
if old == nil {
return p.jsCreateTemplate(new)
}
upParts := []string{}
downParts := []string{}
varName := "collection"
newMap, err := toMap(new)
if err != nil {
return "", err
}
oldMap, err := toMap(old)
if err != nil {
return "", err
}
// non-fields
// -----------------------------------------------------------------
upDiff := diffMaps(oldMap, newMap, "fields", "created", "updated")
if len(upDiff) > 0 {
downDiff := diffMaps(newMap, oldMap, "fields", "created", "updated")
rawUpDiff, err := marhshalWithoutEscape(upDiff, " ", " ")
if err != nil {
return "", err
}
rawDownDiff, err := marhshalWithoutEscape(downDiff, " ", " ")
if err != nil {
return "", err
}
upParts = append(upParts, "// update collection data")
upParts = append(upParts, fmt.Sprintf("unmarshal(%s, %s)", string(rawUpDiff), varName)+"\n")
// ---
downParts = append(downParts, "// update collection data")
downParts = append(downParts, fmt.Sprintf("unmarshal(%s, %s)", string(rawDownDiff), varName)+"\n")
}
// fields
// -----------------------------------------------------------------
oldFieldsSlice, ok := oldMap["fields"].([]any)
if !ok {
return "", errors.New(`oldMap["fields"] is not []any`)
}
newFieldsSlice, ok := newMap["fields"].([]any)
if !ok {
return "", errors.New(`newMap["fields"] is not []any`)
}
// deleted fields
for i, oldField := range old.Fields {
if new.Fields.GetById(oldField.GetId()) != nil {
continue // exist
}
rawOldField, err := marhshalWithoutEscape(oldFieldsSlice[i], " ", " ")
if err != nil {
return "", err
}
upParts = append(upParts, "// remove field")
upParts = append(upParts, fmt.Sprintf("%s.fields.removeById(%q)\n", varName, oldField.GetId()))
downParts = append(downParts, "// add field")
downParts = append(downParts, fmt.Sprintf("%s.fields.addAt(%d, new Field(%s))\n", varName, i, rawOldField))
}
// created fields
for i, newField := range new.Fields {
if old.Fields.GetById(newField.GetId()) != nil {
continue // exist
}
rawNewField, err := marhshalWithoutEscape(newFieldsSlice[i], " ", " ")
if err != nil {
return "", err
}
upParts = append(upParts, "// add field")
upParts = append(upParts, fmt.Sprintf("%s.fields.addAt(%d, new Field(%s))\n", varName, i, rawNewField))
downParts = append(downParts, "// remove field")
downParts = append(downParts, fmt.Sprintf("%s.fields.removeById(%q)\n", varName, newField.GetId()))
}
// modified fields
// (note currently ignoring order-only changes as it comes with too many edge-cases)
for i, newField := range new.Fields {
var rawNewField, rawOldField []byte
rawNewField, err = marhshalWithoutEscape(newFieldsSlice[i], " ", " ")
if err != nil {
return "", err
}
var oldFieldIndex int
for j, oldField := range old.Fields {
if oldField.GetId() == newField.GetId() {
rawOldField, err = marhshalWithoutEscape(oldFieldsSlice[j], " ", " ")
if err != nil {
return "", err
}
oldFieldIndex = j
break
}
}
if rawOldField == nil || bytes.Equal(rawNewField, rawOldField) {
continue // new field or no change
}
upParts = append(upParts, "// update field")
upParts = append(upParts, fmt.Sprintf("%s.fields.addAt(%d, new Field(%s))\n", varName, i, rawNewField))
downParts = append(downParts, "// update field")
downParts = append(downParts, fmt.Sprintf("%s.fields.addAt(%d, new Field(%s))\n", varName, oldFieldIndex, rawOldField))
}
// -----------------------------------------------------------------
if len(upParts) == 0 && len(downParts) == 0 {
return "", ErrEmptyTemplate
}
up := strings.Join(upParts, "\n ")
down := strings.Join(downParts, "\n ")
const template = jsTypesDirective + `migrate((app) => {
const collection = app.findCollectionByNameOrId(%q)
%s
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId(%q)
%s
return app.save(collection)
})
`
return fmt.Sprintf(
template,
old.Id, strings.TrimSpace(up),
new.Id, strings.TrimSpace(down),
), nil
}
// -------------------------------------------------------------------
// Go templates
// -------------------------------------------------------------------
func (p *plugin) goBlankTemplate() (string, error) {
const template = `package %s
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
// add up queries...
return nil
}, func(app core.App) error {
// add down queries...
return nil
})
}
`
return fmt.Sprintf(template, filepath.Base(p.config.Dir)), nil
}
func (p *plugin) goSnapshotTemplate(collections []*core.Collection) (string, error) {
// unset timestamp fields
var collectionsData = make([]map[string]any, len(collections))
for i, c := range collections {
data, err := toMap(c)
if err != nil {
return "", fmt.Errorf("failed to serialize %q into a map: %w", c.Name, err)
}
delete(data, "created")
delete(data, "updated")
deleteNestedMapKey(data, "oauth2", "providers")
collectionsData[i] = data
}
jsonData, err := marhshalWithoutEscape(collectionsData, "\t\t", "\t")
if err != nil {
return "", fmt.Errorf("failed to serialize collections list: %w", err)
}
const template = `package %s
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
jsonData := ` + "`%s`" + `
return app.ImportCollectionsByMarshaledJSON([]byte(jsonData), false)
}, func(app core.App) error {
return nil
})
}
`
return fmt.Sprintf(
template,
filepath.Base(p.config.Dir),
escapeBacktick(string(jsonData)),
), nil
}
func (p *plugin) goCreateTemplate(collection *core.Collection) (string, error) {
// unset timestamp fields
collectionData, err := toMap(collection)
if err != nil {
return "", err
}
delete(collectionData, "created")
delete(collectionData, "updated")
deleteNestedMapKey(collectionData, "oauth2", "providers")
jsonData, err := marhshalWithoutEscape(collectionData, "\t\t", "\t")
if err != nil {
return "", fmt.Errorf("failed to serialize collections list: %w", err)
}
const template = `package %s
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
jsonData := ` + "`%s`" + `
collection := &core.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId(%q)
if err != nil {
return err
}
return app.Delete(collection)
})
}
`
return fmt.Sprintf(
template,
filepath.Base(p.config.Dir),
escapeBacktick(string(jsonData)),
collection.Id,
), nil
}
func (p *plugin) goDeleteTemplate(collection *core.Collection) (string, error) {
// unset timestamp fields
collectionData, err := toMap(collection)
if err != nil {
return "", err
}
delete(collectionData, "created")
delete(collectionData, "updated")
deleteNestedMapKey(collectionData, "oauth2", "providers")
jsonData, err := marhshalWithoutEscape(collectionData, "\t\t", "\t")
if err != nil {
return "", fmt.Errorf("failed to serialize collections list: %w", err)
}
const template = `package %s
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId(%q)
if err != nil {
return err
}
return app.Delete(collection)
}, func(app core.App) error {
jsonData := ` + "`%s`" + `
collection := &core.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
`
return fmt.Sprintf(
template,
filepath.Base(p.config.Dir),
collection.Id,
escapeBacktick(string(jsonData)),
), nil
}
func (p *plugin) goDiffTemplate(new *core.Collection, old *core.Collection) (string, error) {
if new == nil && old == nil {
return "", errors.New("the diff template require at least one of the collection to be non-nil")
}
if new == nil {
return p.goDeleteTemplate(old)
}
if old == nil {
return p.goCreateTemplate(new)
}
upParts := []string{}
downParts := []string{}
varName := "collection"
newMap, err := toMap(new)
if err != nil {
return "", err
}
oldMap, err := toMap(old)
if err != nil {
return "", err
}
// non-fields
// -----------------------------------------------------------------
upDiff := diffMaps(oldMap, newMap, "fields", "created", "updated")
if len(upDiff) > 0 {
downDiff := diffMaps(newMap, oldMap, "fields", "created", "updated")
rawUpDiff, err := marhshalWithoutEscape(upDiff, "\t\t", "\t")
if err != nil {
return "", err
}
rawDownDiff, err := marhshalWithoutEscape(downDiff, "\t\t", "\t")
if err != nil {
return "", err
}
upParts = append(upParts, "// update collection data")
upParts = append(upParts, goErrIf(fmt.Sprintf("json.Unmarshal([]byte(`%s`), &%s)", escapeBacktick(string(rawUpDiff)), varName)))
// ---
downParts = append(downParts, "// update collection data")
downParts = append(downParts, goErrIf(fmt.Sprintf("json.Unmarshal([]byte(`%s`), &%s)", escapeBacktick(string(rawDownDiff)), varName)))
}
// fields
// -----------------------------------------------------------------
oldFieldsSlice, ok := oldMap["fields"].([]any)
if !ok {
return "", errors.New(`oldMap["fields"] is not []any`)
}
newFieldsSlice, ok := newMap["fields"].([]any)
if !ok {
return "", errors.New(`newMap["fields"] is not []any`)
}
// deleted fields
for i, oldField := range old.Fields {
if new.Fields.GetById(oldField.GetId()) != nil {
continue // exist
}
rawOldField, err := marhshalWithoutEscape(oldFieldsSlice[i], "\t\t", "\t")
if err != nil {
return "", err
}
upParts = append(upParts, "// remove field")
upParts = append(upParts, fmt.Sprintf("%s.Fields.RemoveById(%q)\n", varName, oldField.GetId()))
downParts = append(downParts, "// add field")
downParts = append(downParts, goErrIf(fmt.Sprintf("%s.Fields.AddMarshaledJSONAt(%d, []byte(`%s`))", varName, i, escapeBacktick(string(rawOldField)))))
}
// created fields
for i, newField := range new.Fields {
if old.Fields.GetById(newField.GetId()) != nil {
continue // exist
}
rawNewField, err := marhshalWithoutEscape(newFieldsSlice[i], "\t\t", "\t")
if err != nil {
return "", err
}
upParts = append(upParts, "// add field")
upParts = append(upParts, goErrIf(fmt.Sprintf("%s.Fields.AddMarshaledJSONAt(%d, []byte(`%s`))", varName, i, escapeBacktick(string(rawNewField)))))
downParts = append(downParts, "// remove field")
downParts = append(downParts, fmt.Sprintf("%s.Fields.RemoveById(%q)\n", varName, newField.GetId()))
}
// modified fields
// (note currently ignoring order-only changes as it comes with too many edge-cases)
for i, newField := range new.Fields {
var rawNewField, rawOldField []byte
rawNewField, err = marhshalWithoutEscape(newFieldsSlice[i], "\t\t", "\t")
if err != nil {
return "", err
}
var oldFieldIndex int
for j, oldField := range old.Fields {
if oldField.GetId() == newField.GetId() {
rawOldField, err = marhshalWithoutEscape(oldFieldsSlice[j], "\t\t", "\t")
if err != nil {
return "", err
}
oldFieldIndex = j
break
}
}
if rawOldField == nil || bytes.Equal(rawNewField, rawOldField) {
continue // new field or no change
}
upParts = append(upParts, "// update field")
upParts = append(upParts, goErrIf(fmt.Sprintf("%s.Fields.AddMarshaledJSONAt(%d, []byte(`%s`))", varName, i, escapeBacktick(string(rawNewField)))))
downParts = append(downParts, "// update field")
downParts = append(downParts, goErrIf(fmt.Sprintf("%s.Fields.AddMarshaledJSONAt(%d, []byte(`%s`))", varName, oldFieldIndex, escapeBacktick(string(rawOldField)))))
}
// ---------------------------------------------------------------
if len(upParts) == 0 && len(downParts) == 0 {
return "", ErrEmptyTemplate
}
up := strings.Join(upParts, "\n\t\t")
down := strings.Join(downParts, "\n\t\t")
combined := up + down
// generate imports
// ---
var imports string
if strings.Contains(combined, "json.Unmarshal(") ||
strings.Contains(combined, "json.Marshal(") {
imports += "\n\t\"encoding/json\"\n"
}
imports += "\n\t\"github.com/pocketbase/pocketbase/core\""
imports += "\n\tm \"github.com/pocketbase/pocketbase/migrations\""
// ---
const template = `package %s
import (%s
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId(%q)
if err != nil {
return err
}
%s
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId(%q)
if err != nil {
return err
}
%s
return app.Save(collection)
})
}
`
return fmt.Sprintf(
template,
filepath.Base(p.config.Dir),
imports,
old.Id, strings.TrimSpace(up),
new.Id, strings.TrimSpace(down),
), nil
}
func marhshalWithoutEscape(v any, prefix string, indent string) ([]byte, error) {
raw, err := json.MarshalIndent(v, prefix, indent)
if err != nil {
return nil, err
}
// unescape escaped unicode characters
unescaped, err := strconv.Unquote(strings.ReplaceAll(strconv.Quote(string(raw)), `\\u`, `\u`))
if err != nil {
return nil, err
}
return []byte(unescaped), nil
}
func escapeBacktick(v string) string {
return strings.ReplaceAll(v, "`", "` + \"`\" + `")
}
func goErrIf(v string) string {
return "if err := " + v + "; err != nil {\n\t\t\treturn err\n\t\t}\n"
}
func toMap(v any) (map[string]any, error) {
raw, err := json.Marshal(v)
if err != nil {
return nil, err
}
result := map[string]any{}
err = json.Unmarshal(raw, &result)
if err != nil {
return nil, err
}
return result, nil
}
func diffMaps(old, new map[string]any, excludeKeys ...string) map[string]any {
diff := map[string]any{}
for k, vNew := range new {
if slices.Contains(excludeKeys, k) {
continue
}
vOld, ok := old[k]
if !ok {
// new field
diff[k] = vNew
continue
}
// compare the serialized version of the values in case of slice or other custom type
rawOld, _ := json.Marshal(vOld)
rawNew, _ := json.Marshal(vNew)
if !bytes.Equal(rawOld, rawNew) {
// if both are maps add recursively only the changed fields
vOldMap, ok1 := vOld.(map[string]any)
vNewMap, ok2 := vNew.(map[string]any)
if ok1 && ok2 {
subDiff := diffMaps(vOldMap, vNewMap)
if len(subDiff) > 0 {
diff[k] = subDiff
}
} else {
diff[k] = vNew
}
}
}
// unset missing fields
for k := range old {
if _, ok := diff[k]; ok || slices.Contains(excludeKeys, k) {
continue // already added
}
if _, ok := new[k]; !ok {
diff[k] = nil
}
}
return diff
}
func deleteNestedMapKey(data map[string]any, parts ...string) {
if len(parts) == 0 {
return
}
if len(parts) == 1 {
delete(data, parts[0])
return
}
v, ok := data[parts[0]].(map[string]any)
if ok {
deleteNestedMapKey(v, parts[1:]...)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/migratecmd/migratecmd.go | plugins/migratecmd/migratecmd.go | // Package migratecmd adds a new "migrate" command support to a PocketBase instance.
//
// It also comes with automigrations support and templates generation
// (both for JS and GO migration files).
//
// Example usage:
//
// migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{
// TemplateLang: migratecmd.TemplateLangJS, // default to migratecmd.TemplateLangGo
// Automigrate: true,
// Dir: "/custom/migrations/dir", // optional template migrations path; default to "pb_migrations" (for JS) and "migrations" (for Go)
// })
//
// Note: To allow running JS migrations you'll need to enable first
// [jsvm.MustRegister()].
package migratecmd
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/osutils"
"github.com/spf13/cobra"
)
// Config defines the config options of the migratecmd plugin.
type Config struct {
// Dir specifies the directory with the user defined migrations.
//
// If not set it fallbacks to a relative "pb_data/../pb_migrations" (for js)
// or "pb_data/../migrations" (for go) directory.
Dir string
// Automigrate specifies whether to enable automigrations.
Automigrate bool
// TemplateLang specifies the template language to use when
// generating migrations - js or go (default).
TemplateLang string
}
// MustRegister registers the migratecmd plugin to the provided app instance
// and panic if it fails.
//
// Example usage:
//
// migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{})
func MustRegister(app core.App, rootCmd *cobra.Command, config Config) {
if err := Register(app, rootCmd, config); err != nil {
panic(err)
}
}
// Register registers the migratecmd plugin to the provided app instance.
func Register(app core.App, rootCmd *cobra.Command, config Config) error {
p := &plugin{app: app, config: config}
if p.config.TemplateLang == "" {
p.config.TemplateLang = TemplateLangGo
}
if p.config.Dir == "" {
if p.config.TemplateLang == TemplateLangJS {
p.config.Dir = filepath.Join(p.app.DataDir(), "../pb_migrations")
} else {
p.config.Dir = filepath.Join(p.app.DataDir(), "../migrations")
}
}
// attach the migrate command
if rootCmd != nil {
rootCmd.AddCommand(p.createCommand())
}
// watch for collection changes
if p.config.Automigrate {
p.app.OnCollectionCreateRequest().BindFunc(p.automigrateOnCollectionChange)
p.app.OnCollectionUpdateRequest().BindFunc(p.automigrateOnCollectionChange)
p.app.OnCollectionDeleteRequest().BindFunc(p.automigrateOnCollectionChange)
}
return nil
}
type plugin struct {
app core.App
config Config
}
func (p *plugin) createCommand() *cobra.Command {
const cmdDesc = `Supported arguments are:
- up - runs all available migrations
- down [number] - reverts the last [number] applied migrations
- create name - creates new blank migration template file
- collections - creates new migration file with snapshot of the local collections configuration
- history-sync - ensures that the _migrations history table doesn't have references to deleted migration files
`
command := &cobra.Command{
Use: "migrate",
Short: "Executes app DB migration scripts",
Long: cmdDesc,
ValidArgs: []string{"up", "down", "create", "collections"},
SilenceUsage: true,
RunE: func(command *cobra.Command, args []string) error {
cmd := ""
if len(args) > 0 {
cmd = args[0]
}
switch cmd {
case "create":
if _, err := p.migrateCreateHandler("", args[1:], true); err != nil {
return err
}
case "collections":
if _, err := p.migrateCollectionsHandler(args[1:], true); err != nil {
return err
}
default:
// note: system migrations are always applied as part of the bootstrap process
var list = core.MigrationsList{}
list.Copy(core.SystemMigrations)
list.Copy(core.AppMigrations)
runner := core.NewMigrationsRunner(p.app, list)
if err := runner.Run(args...); err != nil {
return err
}
}
return nil
},
}
return command
}
func (p *plugin) migrateCreateHandler(template string, args []string, interactive bool) (string, error) {
if len(args) < 1 {
return "", errors.New("missing migration file name")
}
name := args[0]
dir := p.config.Dir
filename := fmt.Sprintf("%d_%s.%s", time.Now().Unix(), inflector.Snakecase(name), p.config.TemplateLang)
resultFilePath := path.Join(dir, filename)
if interactive {
confirm := osutils.YesNoPrompt(fmt.Sprintf("Do you really want to create migration %q?", resultFilePath), false)
if !confirm {
fmt.Println("The command has been cancelled")
return "", nil
}
}
// get default create template
if template == "" {
var templateErr error
if p.config.TemplateLang == TemplateLangJS {
template, templateErr = p.jsBlankTemplate()
} else {
template, templateErr = p.goBlankTemplate()
}
if templateErr != nil {
return "", fmt.Errorf("failed to resolve create template: %v", templateErr)
}
}
// ensure that the migrations dir exist
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return "", err
}
// save the migration file
if err := os.WriteFile(resultFilePath, []byte(template), 0644); err != nil {
return "", fmt.Errorf("failed to save migration file %q: %v", resultFilePath, err)
}
if interactive {
fmt.Printf("Successfully created file %q\n", resultFilePath)
}
return filename, nil
}
func (p *plugin) migrateCollectionsHandler(args []string, interactive bool) (string, error) {
createArgs := []string{"collections_snapshot"}
createArgs = append(createArgs, args...)
collections := []*core.Collection{}
if err := p.app.CollectionQuery().OrderBy("created ASC").All(&collections); err != nil {
return "", fmt.Errorf("failed to fetch migrations list: %v", err)
}
var template string
var templateErr error
if p.config.TemplateLang == TemplateLangJS {
template, templateErr = p.jsSnapshotTemplate(collections)
} else {
template, templateErr = p.goSnapshotTemplate(collections)
}
if templateErr != nil {
return "", fmt.Errorf("failed to resolve template: %v", templateErr)
}
return p.migrateCreateHandler(template, createArgs, interactive)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/migratecmd/migratecmd_test.go | plugins/migratecmd/migratecmd_test.go | package migratecmd_test
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestAutomigrateCollectionCreate(t *testing.T) {
t.Parallel()
scenarios := []struct {
lang string
expectedTemplate string
}{
{
migratecmd.TemplateLangJS,
`
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
},
"authRule": "",
"authToken": {
"duration": 604800
},
"confirmEmailChangeTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to confirm your new email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Confirm new email</a>\n</p>\n<p><i>If you didn't ask to change your email address, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Confirm your {APP_NAME} new email address"
},
"createRule": null,
"deleteRule": null,
"emailChangeToken": {
"duration": 1800
},
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text@TEST_RANDOM",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cost": 0,
"hidden": true,
"id": "password@TEST_RANDOM",
"max": 0,
"min": 8,
"name": "password",
"pattern": "",
"presentable": false,
"required": true,
"system": true,
"type": "password"
},
{
"autogeneratePattern": "[a-zA-Z0-9]{50}",
"hidden": true,
"id": "text@TEST_RANDOM",
"max": 60,
"min": 30,
"name": "tokenKey",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": true,
"type": "text"
},
{
"exceptDomains": null,
"hidden": false,
"id": "email@TEST_RANDOM",
"name": "email",
"onlyDomains": null,
"presentable": false,
"required": true,
"system": true,
"type": "email"
},
{
"hidden": false,
"id": "bool@TEST_RANDOM",
"name": "emailVisibility",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
},
{
"hidden": false,
"id": "bool@TEST_RANDOM",
"name": "verified",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
}
],
"fileToken": {
"duration": 180
},
"id": "@TEST_RANDOM",
"indexes": [
"create index test on new_name (id)",
"CREATE UNIQUE INDEX ` + "`" + `idx_tokenKey_@TEST_RANDOM` + "`" + ` ON ` + "`" + `new_name` + "`" + ` (` + "`" + `tokenKey` + "`" + `)",
"CREATE UNIQUE INDEX ` + "`" + `idx_email_@TEST_RANDOM` + "`" + ` ON ` + "`" + `new_name` + "`" + ` (` + "`" + `email` + "`" + `) WHERE ` + "`" + `email` + "`" + ` != ''"
],
"listRule": "@request.auth.id != '' && 1 > 0 || 'backtick` + "`" + `test' = 0",
"manageRule": "1 != 2",
"mfa": {
"duration": 1800,
"enabled": false,
"rule": ""
},
"name": "new_name",
"oauth2": {
"enabled": false,
"mappedFields": {
"avatarURL": "",
"id": "",
"name": "",
"username": ""
}
},
"otp": {
"duration": 180,
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>Your one-time password is: <strong>{OTP}</strong></p>\n<p><i>If you didn't ask for the one-time password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "OTP for {APP_NAME}"
},
"enabled": false,
"length": 8
},
"passwordAuth": {
"enabled": true,
"identityFields": [
"email"
]
},
"passwordResetToken": {
"duration": 1800
},
"resetPasswordTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to reset your password.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-password-reset/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Reset password</a>\n</p>\n<p><i>If you didn't ask to reset your password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Reset your {APP_NAME} password"
},
"system": true,
"type": "auth",
"updateRule": null,
"verificationTemplate": {
"body": "<p>Hello,</p>\n<p>Thank you for joining us at {APP_NAME}.</p>\n<p>Click on the button below to verify your email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Verify</a>\n</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Verify your {APP_NAME} email"
},
"verificationToken": {
"duration": 259200
},
"viewRule": "id = \"1\""
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("@TEST_RANDOM");
return app.delete(collection);
})
`,
},
{
migratecmd.TemplateLangGo,
`
package _test_migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
jsonData := ` + "`" + `{
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
},
"authRule": "",
"authToken": {
"duration": 604800
},
"confirmEmailChangeTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to confirm your new email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Confirm new email</a>\n</p>\n<p><i>If you didn't ask to change your email address, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Confirm your {APP_NAME} new email address"
},
"createRule": null,
"deleteRule": null,
"emailChangeToken": {
"duration": 1800
},
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text@TEST_RANDOM",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cost": 0,
"hidden": true,
"id": "password@TEST_RANDOM",
"max": 0,
"min": 8,
"name": "password",
"pattern": "",
"presentable": false,
"required": true,
"system": true,
"type": "password"
},
{
"autogeneratePattern": "[a-zA-Z0-9]{50}",
"hidden": true,
"id": "text@TEST_RANDOM",
"max": 60,
"min": 30,
"name": "tokenKey",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": true,
"type": "text"
},
{
"exceptDomains": null,
"hidden": false,
"id": "email@TEST_RANDOM",
"name": "email",
"onlyDomains": null,
"presentable": false,
"required": true,
"system": true,
"type": "email"
},
{
"hidden": false,
"id": "bool@TEST_RANDOM",
"name": "emailVisibility",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
},
{
"hidden": false,
"id": "bool@TEST_RANDOM",
"name": "verified",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
}
],
"fileToken": {
"duration": 180
},
"id": "@TEST_RANDOM",
"indexes": [
"create index test on new_name (id)",
"CREATE UNIQUE INDEX ` + "` + \"`\" + `" + `idx_tokenKey_@TEST_RANDOM` + "` + \"`\" + `" + ` ON ` + "` + \"`\" + `" + `new_name` + "` + \"`\" + `" + ` (` + "` + \"`\" + `" + `tokenKey` + "` + \"`\" + `" + `)",
"CREATE UNIQUE INDEX ` + "` + \"`\" + `" + `idx_email_@TEST_RANDOM` + "` + \"`\" + `" + ` ON ` + "` + \"`\" + `" + `new_name` + "` + \"`\" + `" + ` (` + "` + \"`\" + `" + `email` + "` + \"`\" + `" + `) WHERE ` + "` + \"`\" + `" + `email` + "` + \"`\" + `" + ` != ''"
],
"listRule": "@request.auth.id != '' && 1 > 0 || 'backtick` + "` + \"`\" + `" + `test' = 0",
"manageRule": "1 != 2",
"mfa": {
"duration": 1800,
"enabled": false,
"rule": ""
},
"name": "new_name",
"oauth2": {
"enabled": false,
"mappedFields": {
"avatarURL": "",
"id": "",
"name": "",
"username": ""
}
},
"otp": {
"duration": 180,
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>Your one-time password is: <strong>{OTP}</strong></p>\n<p><i>If you didn't ask for the one-time password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "OTP for {APP_NAME}"
},
"enabled": false,
"length": 8
},
"passwordAuth": {
"enabled": true,
"identityFields": [
"email"
]
},
"passwordResetToken": {
"duration": 1800
},
"resetPasswordTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to reset your password.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-password-reset/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Reset password</a>\n</p>\n<p><i>If you didn't ask to reset your password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Reset your {APP_NAME} password"
},
"system": true,
"type": "auth",
"updateRule": null,
"verificationTemplate": {
"body": "<p>Hello,</p>\n<p>Thank you for joining us at {APP_NAME}.</p>\n<p>Click on the button below to verify your email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Verify</a>\n</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Verify your {APP_NAME} email"
},
"verificationToken": {
"duration": 259200
},
"viewRule": "id = \"1\""
}` + "`" + `
collection := &core.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("@TEST_RANDOM")
if err != nil {
return err
}
return app.Delete(collection)
})
}
`,
},
}
for _, s := range scenarios {
t.Run(s.lang, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
migrationsDir := filepath.Join(app.DataDir(), "_test_migrations")
migratecmd.MustRegister(app, nil, migratecmd.Config{
TemplateLang: s.lang,
Automigrate: true,
Dir: migrationsDir,
})
app.Bootstrap()
collection := core.NewAuthCollection("new_name")
collection.System = true
collection.ListRule = types.Pointer("@request.auth.id != '' && 1 > 0 || 'backtick`test' = 0")
collection.ViewRule = types.Pointer(`id = "1"`)
collection.Indexes = types.JSONArray[string]{"create index test on new_name (id)"}
collection.ManageRule = types.Pointer("1 != 2")
// should be ignored
collection.OAuth2.Providers = []core.OAuth2ProviderConfig{{Name: "gitlab", ClientId: "abc", ClientSecret: "123"}}
testSecret := strings.Repeat("a", 30)
collection.AuthToken.Secret = testSecret
collection.FileToken.Secret = testSecret
collection.EmailChangeToken.Secret = testSecret
collection.PasswordResetToken.Secret = testSecret
collection.VerificationToken.Secret = testSecret
// save the newly created dummy collection (with mock request event)
event := new(core.CollectionRequestEvent)
event.RequestEvent = &core.RequestEvent{}
event.App = app
event.Collection = collection
err := app.OnCollectionCreateRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
return e.App.Save(e.Collection)
})
if err != nil {
t.Fatalf("Failed to save the created dummy collection, got: %v", err)
}
files, err := os.ReadDir(migrationsDir)
if err != nil {
t.Fatalf("Expected migrationsDir to be created, got %v", err)
}
if total := len(files); total != 1 {
t.Fatalf("Expected 1 file to be generated, got %d: %v", total, files)
}
expectedName := "_created_new_name." + s.lang
if !strings.Contains(files[0].Name(), expectedName) {
t.Fatalf("Expected filename to contains %q, got %q", expectedName, files[0].Name())
}
fullPath := filepath.Join(migrationsDir, files[0].Name())
content, err := os.ReadFile(fullPath)
if err != nil {
t.Fatalf("Failed to read the generated migration file: %v", err)
}
contentStr := strings.TrimSpace(string(content))
// replace @TEST_RANDOM placeholder with a regex pattern
expectedTemplate := strings.ReplaceAll(
"^"+regexp.QuoteMeta(strings.TrimSpace(s.expectedTemplate))+"$",
"@TEST_RANDOM",
`\w+`,
)
if !list.ExistInSliceWithRegex(contentStr, []string{expectedTemplate}) {
t.Fatalf("Expected template \n%v \ngot \n%v", s.expectedTemplate, contentStr)
}
})
}
}
func TestAutomigrateCollectionDelete(t *testing.T) {
t.Parallel()
scenarios := []struct {
lang string
expectedTemplate string
}{
{
migratecmd.TemplateLangJS,
`
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("@TEST_RANDOM");
return app.delete(collection);
}, (app) => {
const collection = new Collection({
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
},
"authRule": "",
"authToken": {
"duration": 604800
},
"confirmEmailChangeTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to confirm your new email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Confirm new email</a>\n</p>\n<p><i>If you didn't ask to change your email address, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Confirm your {APP_NAME} new email address"
},
"createRule": null,
"deleteRule": null,
"emailChangeToken": {
"duration": 1800
},
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text@TEST_RANDOM",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cost": 0,
"hidden": true,
"id": "password@TEST_RANDOM",
"max": 0,
"min": 8,
"name": "password",
"pattern": "",
"presentable": false,
"required": true,
"system": true,
"type": "password"
},
{
"autogeneratePattern": "[a-zA-Z0-9]{50}",
"hidden": true,
"id": "text@TEST_RANDOM",
"max": 60,
"min": 30,
"name": "tokenKey",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": true,
"type": "text"
},
{
"exceptDomains": null,
"hidden": false,
"id": "email3885137012",
"name": "email",
"onlyDomains": null,
"presentable": false,
"required": true,
"system": true,
"type": "email"
},
{
"hidden": false,
"id": "bool@TEST_RANDOM",
"name": "emailVisibility",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
},
{
"hidden": false,
"id": "bool256245529",
"name": "verified",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
}
],
"fileToken": {
"duration": 180
},
"id": "@TEST_RANDOM",
"indexes": [
"create index test on test123 (id)",
"CREATE UNIQUE INDEX ` + "`" + `idx_tokenKey_@TEST_RANDOM` + "`" + ` ON ` + "`" + `test123` + "`" + ` (` + "`" + `tokenKey` + "`" + `)",
"CREATE UNIQUE INDEX ` + "`" + `idx_email_@TEST_RANDOM` + "`" + ` ON ` + "`" + `test123` + "`" + ` (` + "`" + `email` + "`" + `) WHERE ` + "`" + `email` + "`" + ` != ''"
],
"listRule": "@request.auth.id != '' && 1 > 0 || 'backtick` + "`" + `test' = 0",
"manageRule": "1 != 2",
"mfa": {
"duration": 1800,
"enabled": false,
"rule": ""
},
"name": "test123",
"oauth2": {
"enabled": false,
"mappedFields": {
"avatarURL": "",
"id": "",
"name": "",
"username": ""
}
},
"otp": {
"duration": 180,
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>Your one-time password is: <strong>{OTP}</strong></p>\n<p><i>If you didn't ask for the one-time password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "OTP for {APP_NAME}"
},
"enabled": false,
"length": 8
},
"passwordAuth": {
"enabled": true,
"identityFields": [
"email"
]
},
"passwordResetToken": {
"duration": 1800
},
"resetPasswordTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to reset your password.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-password-reset/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Reset password</a>\n</p>\n<p><i>If you didn't ask to reset your password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Reset your {APP_NAME} password"
},
"system": false,
"type": "auth",
"updateRule": null,
"verificationTemplate": {
"body": "<p>Hello,</p>\n<p>Thank you for joining us at {APP_NAME}.</p>\n<p>Click on the button below to verify your email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Verify</a>\n</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Verify your {APP_NAME} email"
},
"verificationToken": {
"duration": 259200
},
"viewRule": "id = \"1\""
});
return app.save(collection);
})
`,
},
{
migratecmd.TemplateLangGo,
`
package _test_migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("@TEST_RANDOM")
if err != nil {
return err
}
return app.Delete(collection)
}, func(app core.App) error {
jsonData := ` + "`" + `{
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
},
"authRule": "",
"authToken": {
"duration": 604800
},
"confirmEmailChangeTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to confirm your new email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Confirm new email</a>\n</p>\n<p><i>If you didn't ask to change your email address, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Confirm your {APP_NAME} new email address"
},
"createRule": null,
"deleteRule": null,
"emailChangeToken": {
"duration": 1800
},
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text@TEST_RANDOM",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cost": 0,
"hidden": true,
"id": "password@TEST_RANDOM",
"max": 0,
"min": 8,
"name": "password",
"pattern": "",
"presentable": false,
"required": true,
"system": true,
"type": "password"
},
{
"autogeneratePattern": "[a-zA-Z0-9]{50}",
"hidden": true,
"id": "text@TEST_RANDOM",
"max": 60,
"min": 30,
"name": "tokenKey",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": true,
"type": "text"
},
{
"exceptDomains": null,
"hidden": false,
"id": "email3885137012",
"name": "email",
"onlyDomains": null,
"presentable": false,
"required": true,
"system": true,
"type": "email"
},
{
"hidden": false,
"id": "bool@TEST_RANDOM",
"name": "emailVisibility",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
},
{
"hidden": false,
"id": "bool256245529",
"name": "verified",
"presentable": false,
"required": false,
"system": true,
"type": "bool"
}
],
"fileToken": {
"duration": 180
},
"id": "@TEST_RANDOM",
"indexes": [
"create index test on test123 (id)",
"CREATE UNIQUE INDEX ` + "` + \"`\" + `" + `idx_tokenKey_@TEST_RANDOM` + "` + \"`\" + `" + ` ON ` + "` + \"`\" + `" + `test123` + "` + \"`\" + `" + ` (` + "` + \"`\" + `" + `tokenKey` + "` + \"`\" + `" + `)",
"CREATE UNIQUE INDEX ` + "` + \"`\" + `" + `idx_email_@TEST_RANDOM` + "` + \"`\" + `" + ` ON ` + "` + \"`\" + `" + `test123` + "` + \"`\" + `" + ` (` + "` + \"`\" + `" + `email` + "` + \"`\" + `" + `) WHERE ` + "` + \"`\" + `" + `email` + "` + \"`\" + `" + ` != ''"
],
"listRule": "@request.auth.id != '' && 1 > 0 || 'backtick` + "` + \"`\" + `" + `test' = 0",
"manageRule": "1 != 2",
"mfa": {
"duration": 1800,
"enabled": false,
"rule": ""
},
"name": "test123",
"oauth2": {
"enabled": false,
"mappedFields": {
"avatarURL": "",
"id": "",
"name": "",
"username": ""
}
},
"otp": {
"duration": 180,
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>Your one-time password is: <strong>{OTP}</strong></p>\n<p><i>If you didn't ask for the one-time password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "OTP for {APP_NAME}"
},
"enabled": false,
"length": 8
},
"passwordAuth": {
"enabled": true,
"identityFields": [
"email"
]
},
"passwordResetToken": {
"duration": 1800
},
"resetPasswordTemplate": {
"body": "<p>Hello,</p>\n<p>Click on the button below to reset your password.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-password-reset/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Reset password</a>\n</p>\n<p><i>If you didn't ask to reset your password, you can ignore this email.</i></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Reset your {APP_NAME} password"
},
"system": false,
"type": "auth",
"updateRule": null,
"verificationTemplate": {
"body": "<p>Hello,</p>\n<p>Thank you for joining us at {APP_NAME}.</p>\n<p>Click on the button below to verify your email address.</p>\n<p>\n <a class=\"btn\" href=\"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\" target=\"_blank\" rel=\"noopener\">Verify</a>\n</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Verify your {APP_NAME} email"
},
"verificationToken": {
"duration": 259200
},
"viewRule": "id = \"1\""
}` + "`" + `
collection := &core.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
`,
},
}
for _, s := range scenarios {
t.Run(s.lang, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
migrationsDir := filepath.Join(app.DataDir(), "_test_migrations")
// create dummy collection
collection := core.NewAuthCollection("test123")
collection.ListRule = types.Pointer("@request.auth.id != '' && 1 > 0 || 'backtick`test' = 0")
collection.ViewRule = types.Pointer(`id = "1"`)
collection.Indexes = types.JSONArray[string]{"create index test on test123 (id)"}
collection.ManageRule = types.Pointer("1 != 2")
if err := app.Save(collection); err != nil {
t.Fatalf("Failed to save dummy collection, got: %v", err)
}
migratecmd.MustRegister(app, nil, migratecmd.Config{
TemplateLang: s.lang,
Automigrate: true,
Dir: migrationsDir,
})
app.Bootstrap()
// delete the newly created dummy collection (with mock request event)
event := new(core.CollectionRequestEvent)
event.RequestEvent = &core.RequestEvent{}
event.App = app
event.Collection = collection
err := app.OnCollectionDeleteRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
return e.App.Delete(e.Collection)
})
if err != nil {
t.Fatalf("Failed to delete dummy collection, got: %v", err)
}
files, err := os.ReadDir(migrationsDir)
if err != nil {
t.Fatalf("Expected migrationsDir to be created, got: %v", err)
}
if total := len(files); total != 1 {
t.Fatalf("Expected 1 file to be generated, got %d", total)
}
expectedName := "_deleted_test123." + s.lang
if !strings.Contains(files[0].Name(), expectedName) {
t.Fatalf("Expected filename to contains %q, got %q", expectedName, files[0].Name())
}
fullPath := filepath.Join(migrationsDir, files[0].Name())
content, err := os.ReadFile(fullPath)
if err != nil {
t.Fatalf("Failed to read the generated migration file: %v", err)
}
contentStr := strings.TrimSpace(string(content))
// replace @TEST_RANDOM placeholder with a regex pattern
expectedTemplate := strings.ReplaceAll(
"^"+regexp.QuoteMeta(strings.TrimSpace(s.expectedTemplate))+"$",
"@TEST_RANDOM",
`\w+`,
)
if !list.ExistInSliceWithRegex(contentStr, []string{expectedTemplate}) {
t.Fatalf("Expected template \n%v \ngot \n%v", s.expectedTemplate, contentStr)
}
})
}
}
func TestAutomigrateCollectionUpdate(t *testing.T) {
t.Parallel()
scenarios := []struct {
lang string
expectedTemplate string
}{
{
migratecmd.TemplateLangJS,
`
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("@TEST_RANDOM")
// update collection data
unmarshal({
"createRule": "id = \"nil_update\"",
"deleteRule": null,
"fileToken": {
"duration": 10
},
"indexes": [
"create index test1 on test123_update (f1_name)",
"CREATE UNIQUE INDEX ` + "`" + `idx_tokenKey_@TEST_RANDOM` + "`" + ` ON ` + "`" + `test123_update` + "`" + ` (` + "`" + `tokenKey` + "`" + `)",
"CREATE UNIQUE INDEX ` + "`" + `idx_email_@TEST_RANDOM` + "`" + ` ON ` + "`" + `test123_update` + "`" + ` (` + "`" + `email` + "`" + `) WHERE ` + "`" + `email` + "`" + ` != ''"
],
"listRule": "@request.auth.id != ''",
"name": "test123_update",
"oauth2": {
"enabled": true
},
"updateRule": "id = \"2_update\""
}, collection)
// remove field
collection.fields.removeById("f3_id")
// add field
collection.fields.addAt(8, new Field({
"autogeneratePattern": "",
"hidden": false,
"id": "f4_id",
"max": 0,
"min": 0,
"name": "f4_name",
"pattern": "` + "`" + `test backtick` + "`" + `123",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}))
// update field
collection.fields.addAt(7, new Field({
"hidden": false,
"id": "f2_id",
"max": null,
"min": 10,
"name": "f2_name_new",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("@TEST_RANDOM")
// update collection data
unmarshal({
"createRule": null,
"deleteRule": "id = \"3\"",
"fileToken": {
"duration": 180
},
"indexes": [
"create index test1 on test123 (f1_name)",
"CREATE UNIQUE INDEX ` + "`" + `idx_tokenKey_@TEST_RANDOM` + "`" + ` ON ` + "`" + `test123` + "`" + ` (` + "`" + `tokenKey` + "`" + `)",
"CREATE UNIQUE INDEX ` + "`" + `idx_email_@TEST_RANDOM` + "`" + ` ON ` + "`" + `test123` + "`" + ` (` + "`" + `email` + "`" + `) WHERE ` + "`" + `email` + "`" + ` != ''"
],
"listRule": "@request.auth.id != '' && 1 != 2",
"name": "test123",
"oauth2": {
"enabled": false
},
"updateRule": "id = \"2\""
}, collection)
// add field
collection.fields.addAt(8, new Field({
"hidden": false,
"id": "f3_id",
"name": "f3_name",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
}))
// remove field
collection.fields.removeById("f4_id")
// update field
collection.fields.addAt(7, new Field({
"hidden": false,
"id": "f2_id",
"max": null,
"min": 10,
"name": "f2_name",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}))
return app.save(collection)
})
`,
},
{
migratecmd.TemplateLangGo,
`
package _test_migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("@TEST_RANDOM")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(` + "`" + `{
"createRule": "id = \"nil_update\"",
"deleteRule": null,
"fileToken": {
"duration": 10
},
"indexes": [
"create index test1 on test123_update (f1_name)",
"CREATE UNIQUE INDEX ` + "` + \"`\" + `" + `idx_tokenKey_@TEST_RANDOM` + "` + \"`\" + `" + ` ON ` + "` + \"`\" + `" + `test123_update` + "` + \"`\" + `" + ` (` + "` + \"`\" + `" + `tokenKey` + "` + \"`\" + `" + `)",
"CREATE UNIQUE INDEX ` + "` + \"`\" + `" + `idx_email_@TEST_RANDOM` + "` + \"`\" + `" + ` ON ` + "` + \"`\" + `" + `test123_update` + "` + \"`\" + `" + ` (` + "` + \"`\" + `" + `email` + "` + \"`\" + `" + `) WHERE ` + "` + \"`\" + `" + `email` + "` + \"`\" + `" + ` != ''"
],
"listRule": "@request.auth.id != ''",
"name": "test123_update",
"oauth2": {
"enabled": true
},
"updateRule": "id = \"2_update\""
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/plugins/migratecmd/automigrate.go | plugins/migratecmd/automigrate.go | package migratecmd
import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
)
// automigrateOnCollectionChange handles the automigration snapshot
// generation on collection change request event (create/update/delete).
func (p *plugin) automigrateOnCollectionChange(e *core.CollectionRequestEvent) error {
var err error
var old *core.Collection
if !e.Collection.IsNew() {
old, err = e.App.FindCollectionByNameOrId(e.Collection.Id)
if err != nil {
return err
}
}
err = e.Next()
if err != nil {
return err
}
new, err := p.app.FindCollectionByNameOrId(e.Collection.Id)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
// for now exclude OAuth2 configs from the migration
if old != nil && old.IsAuth() {
old.OAuth2.Providers = nil
}
if new != nil && new.IsAuth() {
new.OAuth2.Providers = nil
}
var template string
var templateErr error
if p.config.TemplateLang == TemplateLangJS {
template, templateErr = p.jsDiffTemplate(new, old)
} else {
template, templateErr = p.goDiffTemplate(new, old)
}
if templateErr != nil {
if errors.Is(templateErr, ErrEmptyTemplate) {
return nil // no changes
}
return fmt.Errorf("failed to resolve template: %w", templateErr)
}
var action string
switch {
case new == nil:
action = "deleted_" + normalizeCollectionName(old.Name)
case old == nil:
action = "created_" + normalizeCollectionName(new.Name)
default:
action = "updated_" + normalizeCollectionName(old.Name)
}
name := fmt.Sprintf("%d_%s.%s", time.Now().Unix(), action, p.config.TemplateLang)
filePath := filepath.Join(p.config.Dir, name)
return p.app.RunInTransaction(func(txApp core.App) error {
// insert the migration entry
_, err := txApp.DB().Insert(core.DefaultMigrationsTable, dbx.Params{
"file": name,
// use microseconds for more granular applied time in case
// multiple collection changes happens at the ~exact time
"applied": time.Now().UnixMicro(),
}).Execute()
if err != nil {
return err
}
// ensure that the local migrations dir exist
if err := os.MkdirAll(p.config.Dir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create migration dir: %w", err)
}
if err := os.WriteFile(filePath, []byte(template), 0644); err != nil {
return fmt.Errorf("failed to save automigrate file: %w", err)
}
return nil
})
}
func normalizeCollectionName(name string) string {
// adds an extra "_" suffix to the name in case the collection ends
// with "test" to prevent accidentally resulting in "_test.go"/"_test.js" files
if strings.HasSuffix(strings.ToLower(name), "test") {
name += "_"
}
return name
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1717233557_v0.23_migrate2.go | migrations/1717233557_v0.23_migrate2.go | package migrations
import (
"github.com/pocketbase/pocketbase/core"
)
// note: this migration will be deleted in future version
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
_, err := txApp.DB().NewQuery("CREATE INDEX IF NOT EXISTS idx__collections_type on {{_collections}} ([[type]]);").Execute()
if err != nil {
return err
}
// reset mfas and otps delete rule
collectionNames := []string{core.CollectionNameMFAs, core.CollectionNameOTPs}
for _, name := range collectionNames {
col, err := txApp.FindCollectionByNameOrId(name)
if err != nil {
return err
}
if col.DeleteRule != nil {
col.DeleteRule = nil
err = txApp.SaveNoValidate(col)
if err != nil {
return err
}
}
}
return nil
}, nil)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1717233558_v0.23_migrate3.go | migrations/1717233558_v0.23_migrate3.go | package migrations
import (
"hash/crc32"
"strconv"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
)
// note: this migration will be deleted in future version
func collectionIdChecksum(typ, name string) string {
return "pbc_" + strconv.FormatInt(int64(crc32.ChecksumIEEE([]byte(typ+name))), 10)
}
func fieldIdChecksum(typ, name string) string {
return typ + strconv.FormatInt(int64(crc32.ChecksumIEEE([]byte(name))), 10)
}
// normalize system collection and field ids
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
collections := []*core.Collection{}
err := txApp.CollectionQuery().
AndWhere(dbx.In(
"name",
core.CollectionNameMFAs,
core.CollectionNameOTPs,
core.CollectionNameExternalAuths,
core.CollectionNameAuthOrigins,
core.CollectionNameSuperusers,
)).
All(&collections)
if err != nil {
return err
}
for _, c := range collections {
var needUpdate bool
references, err := txApp.FindCollectionReferences(c, c.Id)
if err != nil {
return err
}
authOrigins, err := txApp.FindAllAuthOriginsByCollection(c)
if err != nil {
return err
}
mfas, err := txApp.FindAllMFAsByCollection(c)
if err != nil {
return err
}
otps, err := txApp.FindAllOTPsByCollection(c)
if err != nil {
return err
}
originalId := c.Id
// normalize collection id
if checksum := collectionIdChecksum(c.Type, c.Name); c.Id != checksum {
c.Id = checksum
needUpdate = true
}
// normalize system fields
for _, f := range c.Fields {
if !f.GetSystem() {
continue
}
if checksum := fieldIdChecksum(f.Type(), f.GetName()); f.GetId() != checksum {
f.SetId(checksum)
needUpdate = true
}
}
if !needUpdate {
continue
}
rawExport, err := c.DBExport(txApp)
if err != nil {
return err
}
_, err = txApp.DB().Update("_collections", rawExport, dbx.HashExp{"id": originalId}).Execute()
if err != nil {
return err
}
// make sure that the cached collection id is also updated
cached, err := txApp.FindCachedCollectionByNameOrId(c.Name)
if err != nil {
return err
}
cached.Id = c.Id
// update collection references
for refCollection, fields := range references {
for _, f := range fields {
relationField, ok := f.(*core.RelationField)
if !ok || relationField.CollectionId == originalId {
continue
}
relationField.CollectionId = c.Id
}
if err = txApp.SaveNoValidate(refCollection); err != nil {
return err
}
}
// update mfas references
for _, item := range mfas {
item.SetCollectionRef(c.Id)
if err = txApp.SaveNoValidate(item); err != nil {
return err
}
}
// update otps references
for _, item := range otps {
item.SetCollectionRef(c.Id)
if err = txApp.SaveNoValidate(item); err != nil {
return err
}
}
// update authOrigins references
for _, item := range authOrigins {
item.SetCollectionRef(c.Id)
if err = txApp.SaveNoValidate(item); err != nil {
return err
}
}
}
return nil
}, nil)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1717233556_v0.23_migrate.go | migrations/1717233556_v0.23_migrate.go | package migrations
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
"golang.org/x/crypto/bcrypt"
)
// note: this migration will be deleted in future version
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
// note: mfas and authOrigins tables are available only with v0.23
hasUpgraded := txApp.HasTable(core.CollectionNameMFAs) && txApp.HasTable(core.CollectionNameAuthOrigins)
if hasUpgraded {
return nil
}
oldSettings, err := loadOldSettings(txApp)
if err != nil {
return fmt.Errorf("failed to fetch old settings: %w", err)
}
if err = migrateOldCollections(txApp, oldSettings); err != nil {
return err
}
if err = migrateSuperusers(txApp, oldSettings); err != nil {
return fmt.Errorf("failed to migrate admins->superusers: %w", err)
}
if err = migrateSettings(txApp, oldSettings); err != nil {
return fmt.Errorf("failed to migrate settings: %w", err)
}
if err = migrateExternalAuths(txApp); err != nil {
return fmt.Errorf("failed to migrate externalAuths: %w", err)
}
if err = createMFAsCollection(txApp); err != nil {
return fmt.Errorf("failed to create mfas collection: %w", err)
}
if err = createOTPsCollection(txApp); err != nil {
return fmt.Errorf("failed to create otps collection: %w", err)
}
if err = createAuthOriginsCollection(txApp); err != nil {
return fmt.Errorf("failed to create authOrigins collection: %w", err)
}
err = os.Remove(filepath.Join(txApp.DataDir(), "logs.db"))
if err != nil && !errors.Is(err, os.ErrNotExist) {
txApp.Logger().Warn("Failed to delete old logs.db file", "error", err)
}
return nil
}, nil)
}
// -------------------------------------------------------------------
func migrateSuperusers(txApp core.App, oldSettings *oldSettingsModel) error {
// create new superusers collection and table
err := createSuperusersCollection(txApp)
if err != nil {
return err
}
// update with the token options from the old settings
superusersCollection, err := txApp.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
return err
}
superusersCollection.AuthToken.Secret = zeroFallback(
cast.ToString(getMapVal(oldSettings.Value, "adminAuthToken", "secret")),
superusersCollection.AuthToken.Secret,
)
superusersCollection.AuthToken.Duration = zeroFallback(
cast.ToInt64(getMapVal(oldSettings.Value, "adminAuthToken", "duration")),
superusersCollection.AuthToken.Duration,
)
superusersCollection.PasswordResetToken.Secret = zeroFallback(
cast.ToString(getMapVal(oldSettings.Value, "adminPasswordResetToken", "secret")),
superusersCollection.PasswordResetToken.Secret,
)
superusersCollection.PasswordResetToken.Duration = zeroFallback(
cast.ToInt64(getMapVal(oldSettings.Value, "adminPasswordResetToken", "duration")),
superusersCollection.PasswordResetToken.Duration,
)
superusersCollection.FileToken.Secret = zeroFallback(
cast.ToString(getMapVal(oldSettings.Value, "adminFileToken", "secret")),
superusersCollection.FileToken.Secret,
)
superusersCollection.FileToken.Duration = zeroFallback(
cast.ToInt64(getMapVal(oldSettings.Value, "adminFileToken", "duration")),
superusersCollection.FileToken.Duration,
)
if err = txApp.Save(superusersCollection); err != nil {
return fmt.Errorf("failed to migrate token configs: %w", err)
}
// copy old admins records into the new one
_, err = txApp.DB().NewQuery(`
INSERT INTO {{` + core.CollectionNameSuperusers + `}} ([[id]], [[verified]], [[email]], [[password]], [[tokenKey]], [[created]], [[updated]])
SELECT [[id]], true, [[email]], [[passwordHash]], [[tokenKey]], [[created]], [[updated]] FROM {{_admins}};
`).Execute()
if err != nil {
return err
}
// remove old admins table
_, err = txApp.DB().DropTable("_admins").Execute()
if err != nil {
return err
}
return nil
}
// -------------------------------------------------------------------
type oldSettingsModel struct {
Id string `db:"id" json:"id"`
Key string `db:"key" json:"key"`
RawValue types.JSONRaw `db:"value" json:"value"`
Value map[string]any `db:"-" json:"-"`
}
func loadOldSettings(txApp core.App) (*oldSettingsModel, error) {
oldSettings := &oldSettingsModel{Value: map[string]any{}}
err := txApp.DB().Select().From("_params").Where(dbx.HashExp{"key": "settings"}).One(oldSettings)
if err != nil {
return nil, err
}
// try without decrypt
plainDecodeErr := json.Unmarshal(oldSettings.RawValue, &oldSettings.Value)
// failed, try to decrypt
if plainDecodeErr != nil {
encryptionKey := os.Getenv(txApp.EncryptionEnv())
// load without decryption has failed and there is no encryption key to use for decrypt
if encryptionKey == "" {
return nil, fmt.Errorf("invalid settings db data or missing encryption key %q", txApp.EncryptionEnv())
}
// decrypt
decrypted, decryptErr := security.Decrypt(string(oldSettings.RawValue), encryptionKey)
if decryptErr != nil {
return nil, decryptErr
}
// decode again
decryptedDecodeErr := json.Unmarshal(decrypted, &oldSettings.Value)
if decryptedDecodeErr != nil {
return nil, decryptedDecodeErr
}
}
return oldSettings, nil
}
func migrateSettings(txApp core.App, oldSettings *oldSettingsModel) error {
// renamed old params collection
_, err := txApp.DB().RenameTable("_params", "_params_old").Execute()
if err != nil {
return err
}
// create new params table
err = createParamsTable(txApp)
if err != nil {
return err
}
// migrate old settings
newSettings := txApp.Settings()
// ---
newSettings.Meta.AppName = cast.ToString(getMapVal(oldSettings.Value, "meta", "appName"))
newSettings.Meta.AppURL = strings.TrimSuffix(cast.ToString(getMapVal(oldSettings.Value, "meta", "appUrl")), "/")
newSettings.Meta.HideControls = cast.ToBool(getMapVal(oldSettings.Value, "meta", "hideControls"))
newSettings.Meta.SenderName = cast.ToString(getMapVal(oldSettings.Value, "meta", "senderName"))
newSettings.Meta.SenderAddress = cast.ToString(getMapVal(oldSettings.Value, "meta", "senderAddress"))
// ---
newSettings.Logs.MaxDays = cast.ToInt(getMapVal(oldSettings.Value, "logs", "maxDays"))
newSettings.Logs.MinLevel = cast.ToInt(getMapVal(oldSettings.Value, "logs", "minLevel"))
newSettings.Logs.LogIP = cast.ToBool(getMapVal(oldSettings.Value, "logs", "logIp"))
// ---
newSettings.SMTP.Enabled = cast.ToBool(getMapVal(oldSettings.Value, "smtp", "enabled"))
newSettings.SMTP.Port = cast.ToInt(getMapVal(oldSettings.Value, "smtp", "port"))
newSettings.SMTP.Host = cast.ToString(getMapVal(oldSettings.Value, "smtp", "host"))
newSettings.SMTP.Username = cast.ToString(getMapVal(oldSettings.Value, "smtp", "username"))
newSettings.SMTP.Password = cast.ToString(getMapVal(oldSettings.Value, "smtp", "password"))
newSettings.SMTP.AuthMethod = cast.ToString(getMapVal(oldSettings.Value, "smtp", "authMethod"))
newSettings.SMTP.TLS = cast.ToBool(getMapVal(oldSettings.Value, "smtp", "tls"))
newSettings.SMTP.LocalName = cast.ToString(getMapVal(oldSettings.Value, "smtp", "localName"))
// ---
newSettings.Backups.Cron = cast.ToString(getMapVal(oldSettings.Value, "backups", "cron"))
newSettings.Backups.CronMaxKeep = cast.ToInt(getMapVal(oldSettings.Value, "backups", "cronMaxKeep"))
newSettings.Backups.S3 = core.S3Config{
Enabled: cast.ToBool(getMapVal(oldSettings.Value, "backups", "s3", "enabled")),
Bucket: cast.ToString(getMapVal(oldSettings.Value, "backups", "s3", "bucket")),
Region: cast.ToString(getMapVal(oldSettings.Value, "backups", "s3", "region")),
Endpoint: cast.ToString(getMapVal(oldSettings.Value, "backups", "s3", "endpoint")),
AccessKey: cast.ToString(getMapVal(oldSettings.Value, "backups", "s3", "accessKey")),
Secret: cast.ToString(getMapVal(oldSettings.Value, "backups", "s3", "secret")),
ForcePathStyle: cast.ToBool(getMapVal(oldSettings.Value, "backups", "s3", "forcePathStyle")),
}
// ---
newSettings.S3 = core.S3Config{
Enabled: cast.ToBool(getMapVal(oldSettings.Value, "s3", "enabled")),
Bucket: cast.ToString(getMapVal(oldSettings.Value, "s3", "bucket")),
Region: cast.ToString(getMapVal(oldSettings.Value, "s3", "region")),
Endpoint: cast.ToString(getMapVal(oldSettings.Value, "s3", "endpoint")),
AccessKey: cast.ToString(getMapVal(oldSettings.Value, "s3", "accessKey")),
Secret: cast.ToString(getMapVal(oldSettings.Value, "s3", "secret")),
ForcePathStyle: cast.ToBool(getMapVal(oldSettings.Value, "s3", "forcePathStyle")),
}
// ---
err = txApp.Save(newSettings)
if err != nil {
return err
}
// remove old params table
_, err = txApp.DB().DropTable("_params_old").Execute()
if err != nil {
return err
}
return nil
}
// -------------------------------------------------------------------
func migrateExternalAuths(txApp core.App) error {
// renamed old externalAuths table
_, err := txApp.DB().RenameTable("_externalAuths", "_externalAuths_old").Execute()
if err != nil {
return err
}
// create new externalAuths collection and table
err = createExternalAuthsCollection(txApp)
if err != nil {
return err
}
// copy old externalAuths records into the new one
_, err = txApp.DB().NewQuery(`
INSERT INTO {{` + core.CollectionNameExternalAuths + `}} ([[id]], [[collectionRef]], [[recordRef]], [[provider]], [[providerId]], [[created]], [[updated]])
SELECT [[id]], [[collectionId]], [[recordId]], [[provider]], [[providerId]], [[created]], [[updated]] FROM {{_externalAuths_old}};
`).Execute()
if err != nil {
return err
}
// remove old externalAuths table
_, err = txApp.DB().DropTable("_externalAuths_old").Execute()
if err != nil {
return err
}
return nil
}
// -------------------------------------------------------------------
func migrateOldCollections(txApp core.App, oldSettings *oldSettingsModel) error {
oldCollections := []*OldCollectionModel{}
err := txApp.DB().Select().From("_collections").All(&oldCollections)
if err != nil {
return err
}
for _, c := range oldCollections {
dummyAuthCollection := core.NewAuthCollection("test")
options := c.Options
c.Options = types.JSONMap[any]{} // reset
// update rules
// ---
c.ListRule = migrateRule(c.ListRule)
c.ViewRule = migrateRule(c.ViewRule)
c.CreateRule = migrateRule(c.CreateRule)
c.UpdateRule = migrateRule(c.UpdateRule)
c.DeleteRule = migrateRule(c.DeleteRule)
// migrate fields
// ---
for i, field := range c.Schema {
switch cast.ToString(field["type"]) {
case "bool":
field = toBoolField(field)
case "number":
field = toNumberField(field)
case "text":
field = toTextField(field)
case "url":
field = toURLField(field)
case "email":
field = toEmailField(field)
case "editor":
field = toEditorField(field)
case "date":
field = toDateField(field)
case "select":
field = toSelectField(field)
case "json":
field = toJSONField(field)
case "relation":
field = toRelationField(field)
case "file":
field = toFileField(field)
}
c.Schema[i] = field
}
// type specific changes
switch c.Type {
case "auth":
// token configs
// ---
c.Options["authToken"] = map[string]any{
"secret": zeroFallback(cast.ToString(getMapVal(oldSettings.Value, "recordAuthToken", "secret")), dummyAuthCollection.AuthToken.Secret),
"duration": zeroFallback(cast.ToInt64(getMapVal(oldSettings.Value, "recordAuthToken", "duration")), dummyAuthCollection.AuthToken.Duration),
}
c.Options["passwordResetToken"] = map[string]any{
"secret": zeroFallback(cast.ToString(getMapVal(oldSettings.Value, "recordPasswordResetToken", "secret")), dummyAuthCollection.PasswordResetToken.Secret),
"duration": zeroFallback(cast.ToInt64(getMapVal(oldSettings.Value, "recordPasswordResetToken", "duration")), dummyAuthCollection.PasswordResetToken.Duration),
}
c.Options["emailChangeToken"] = map[string]any{
"secret": zeroFallback(cast.ToString(getMapVal(oldSettings.Value, "recordEmailChangeToken", "secret")), dummyAuthCollection.EmailChangeToken.Secret),
"duration": zeroFallback(cast.ToInt64(getMapVal(oldSettings.Value, "recordEmailChangeToken", "duration")), dummyAuthCollection.EmailChangeToken.Duration),
}
c.Options["verificationToken"] = map[string]any{
"secret": zeroFallback(cast.ToString(getMapVal(oldSettings.Value, "recordVerificationToken", "secret")), dummyAuthCollection.VerificationToken.Secret),
"duration": zeroFallback(cast.ToInt64(getMapVal(oldSettings.Value, "recordVerificationToken", "duration")), dummyAuthCollection.VerificationToken.Duration),
}
c.Options["fileToken"] = map[string]any{
"secret": zeroFallback(cast.ToString(getMapVal(oldSettings.Value, "recordFileToken", "secret")), dummyAuthCollection.FileToken.Secret),
"duration": zeroFallback(cast.ToInt64(getMapVal(oldSettings.Value, "recordFileToken", "duration")), dummyAuthCollection.FileToken.Duration),
}
onlyVerified := cast.ToBool(options["onlyVerified"])
if onlyVerified {
c.Options["authRule"] = "verified=true"
} else {
c.Options["authRule"] = ""
}
c.Options["manageRule"] = nil
if options["manageRule"] != nil {
manageRule, err := cast.ToStringE(options["manageRule"])
if err == nil && manageRule != "" {
c.Options["manageRule"] = migrateRule(&manageRule)
}
}
// passwordAuth
identityFields := []string{}
if cast.ToBool(options["allowEmailAuth"]) {
identityFields = append(identityFields, "email")
}
if cast.ToBool(options["allowUsernameAuth"]) {
identityFields = append(identityFields, "username")
}
c.Options["passwordAuth"] = map[string]any{
"enabled": len(identityFields) > 0,
"identityFields": identityFields,
}
// oauth2
// ---
oauth2Providers := []map[string]any{}
providerNames := []string{
"googleAuth",
"facebookAuth",
"githubAuth",
"gitlabAuth",
"discordAuth",
"twitterAuth",
"microsoftAuth",
"spotifyAuth",
"kakaoAuth",
"twitchAuth",
"stravaAuth",
"giteeAuth",
"livechatAuth",
"giteaAuth",
"oidcAuth",
"oidc2Auth",
"oidc3Auth",
"appleAuth",
"instagramAuth",
"vkAuth",
"yandexAuth",
"patreonAuth",
"mailcowAuth",
"bitbucketAuth",
"planningcenterAuth",
}
for _, name := range providerNames {
if !cast.ToBool(getMapVal(oldSettings.Value, name, "enabled")) {
continue
}
oauth2Providers = append(oauth2Providers, map[string]any{
"name": strings.TrimSuffix(name, "Auth"),
"clientId": cast.ToString(getMapVal(oldSettings.Value, name, "clientId")),
"clientSecret": cast.ToString(getMapVal(oldSettings.Value, name, "clientSecret")),
"authURL": cast.ToString(getMapVal(oldSettings.Value, name, "authUrl")),
"tokenURL": cast.ToString(getMapVal(oldSettings.Value, name, "tokenUrl")),
"userInfoURL": cast.ToString(getMapVal(oldSettings.Value, name, "userApiUrl")),
"displayName": cast.ToString(getMapVal(oldSettings.Value, name, "displayName")),
"pkce": getMapVal(oldSettings.Value, name, "pkce"),
})
}
c.Options["oauth2"] = map[string]any{
"enabled": cast.ToBool(options["allowOAuth2Auth"]) && len(oauth2Providers) > 0,
"providers": oauth2Providers,
"mappedFields": map[string]string{
"username": "username",
},
}
// default email templates
// ---
emailTemplates := map[string]core.EmailTemplate{
"verificationTemplate": dummyAuthCollection.VerificationTemplate,
"resetPasswordTemplate": dummyAuthCollection.ResetPasswordTemplate,
"confirmEmailChangeTemplate": dummyAuthCollection.ConfirmEmailChangeTemplate,
}
for name, fallback := range emailTemplates {
c.Options[name] = map[string]any{
"subject": zeroFallback(
cast.ToString(getMapVal(oldSettings.Value, "meta", name, "subject")),
fallback.Subject,
),
"body": zeroFallback(
strings.ReplaceAll(
cast.ToString(getMapVal(oldSettings.Value, "meta", name, "body")),
"{ACTION_URL}",
cast.ToString(getMapVal(oldSettings.Value, "meta", name, "actionUrl")),
),
fallback.Body,
),
}
}
// mfa
// ---
c.Options["mfa"] = map[string]any{
"enabled": dummyAuthCollection.MFA.Enabled,
"duration": dummyAuthCollection.MFA.Duration,
"rule": dummyAuthCollection.MFA.Rule,
}
// otp
// ---
c.Options["otp"] = map[string]any{
"enabled": dummyAuthCollection.OTP.Enabled,
"duration": dummyAuthCollection.OTP.Duration,
"length": dummyAuthCollection.OTP.Length,
"emailTemplate": map[string]any{
"subject": dummyAuthCollection.OTP.EmailTemplate.Subject,
"body": dummyAuthCollection.OTP.EmailTemplate.Body,
},
}
// auth alerts
// ---
c.Options["authAlert"] = map[string]any{
"enabled": dummyAuthCollection.AuthAlert.Enabled,
"emailTemplate": map[string]any{
"subject": dummyAuthCollection.AuthAlert.EmailTemplate.Subject,
"body": dummyAuthCollection.AuthAlert.EmailTemplate.Body,
},
}
// add system field indexes
// ---
c.Indexes = append(types.JSONArray[string]{
fmt.Sprintf("CREATE UNIQUE INDEX `_%s_username_idx` ON `%s` (username COLLATE NOCASE)", c.Id, c.Name),
fmt.Sprintf("CREATE UNIQUE INDEX `_%s_email_idx` ON `%s` (`email`) WHERE `email` != ''", c.Id, c.Name),
fmt.Sprintf("CREATE UNIQUE INDEX `_%s_tokenKey_idx` ON `%s` (`tokenKey`)", c.Id, c.Name),
}, c.Indexes...)
// prepend the auth system fields
// ---
tokenKeyField := map[string]any{
"id": fieldIdChecksum("text", "tokenKey"),
"type": "text",
"name": "tokenKey",
"system": true,
"hidden": true,
"required": true,
"presentable": false,
"primaryKey": false,
"min": 30,
"max": 60,
"pattern": "",
"autogeneratePattern": "[a-zA-Z0-9_]{50}",
}
passwordField := map[string]any{
"id": fieldIdChecksum("password", "password"),
"type": "password",
"name": "password",
"presentable": false,
"system": true,
"hidden": true,
"required": true,
"pattern": "",
"min": cast.ToInt(options["minPasswordLength"]),
"cost": bcrypt.DefaultCost, // new default
}
emailField := map[string]any{
"id": fieldIdChecksum("email", "email"),
"type": "email",
"name": "email",
"system": true,
"hidden": false,
"presentable": false,
"required": cast.ToBool(options["requireEmail"]),
"exceptDomains": cast.ToStringSlice(options["exceptEmailDomains"]),
"onlyDomains": cast.ToStringSlice(options["onlyEmailDomains"]),
}
emailVisibilityField := map[string]any{
"id": fieldIdChecksum("bool", "emailVisibility"),
"type": "bool",
"name": "emailVisibility",
"system": true,
"hidden": false,
"presentable": false,
"required": false,
}
verifiedField := map[string]any{
"id": fieldIdChecksum("bool", "verified"),
"type": "bool",
"name": "verified",
"system": true,
"hidden": false,
"presentable": false,
"required": false,
}
usernameField := map[string]any{
"id": fieldIdChecksum("text", "username"),
"type": "text",
"name": "username",
"system": false,
"hidden": false,
"required": true,
"presentable": false,
"primaryKey": false,
"min": 3,
"max": 150,
"pattern": `^[\w][\w\.\-]*$`,
"autogeneratePattern": "users[0-9]{6}",
}
c.Schema = append(types.JSONArray[types.JSONMap[any]]{
passwordField,
tokenKeyField,
emailField,
emailVisibilityField,
verifiedField,
usernameField,
}, c.Schema...)
// rename passwordHash records rable column to password
// ---
_, err = txApp.DB().RenameColumn(c.Name, "passwordHash", "password").Execute()
if err != nil {
return err
}
// delete unnecessary auth columns
dropColumns := []string{"lastResetSentAt", "lastVerificationSentAt", "lastLoginAlertSentAt"}
for _, drop := range dropColumns {
// ignore errors in case the columns don't exist
_, _ = txApp.DB().DropColumn(c.Name, drop).Execute()
}
case "view":
c.Options["viewQuery"] = cast.ToString(options["query"])
}
// prepend the id field
idField := map[string]any{
"id": fieldIdChecksum("text", "id"),
"type": "text",
"name": "id",
"system": true,
"required": true,
"presentable": false,
"hidden": false,
"primaryKey": true,
"min": 15,
"max": 15,
"pattern": "^[a-z0-9]+$",
"autogeneratePattern": "[a-z0-9]{15}",
}
c.Schema = append(types.JSONArray[types.JSONMap[any]]{idField}, c.Schema...)
var addCreated, addUpdated bool
if c.Type == "view" {
// manually check if the view has created/updated columns
columns, _ := txApp.TableColumns(c.Name)
for _, c := range columns {
if strings.EqualFold(c, "created") {
addCreated = true
} else if strings.EqualFold(c, "updated") {
addUpdated = true
}
}
} else {
addCreated = true
addUpdated = true
}
if addCreated {
createdField := map[string]any{
"id": fieldIdChecksum("autodate", "created"),
"type": "autodate",
"name": "created",
"system": false,
"presentable": false,
"hidden": false,
"onCreate": true,
"onUpdate": false,
}
c.Schema = append(c.Schema, createdField)
}
if addUpdated {
updatedField := map[string]any{
"id": fieldIdChecksum("autodate", "updated"),
"type": "autodate",
"name": "updated",
"system": false,
"presentable": false,
"hidden": false,
"onCreate": true,
"onUpdate": true,
}
c.Schema = append(c.Schema, updatedField)
}
if err = txApp.DB().Model(c).Update(); err != nil {
return err
}
}
_, err = txApp.DB().RenameColumn("_collections", "schema", "fields").Execute()
if err != nil {
return err
}
// run collection validations
collections, err := txApp.FindAllCollections()
if err != nil {
return fmt.Errorf("failed to retrieve all collections: %w", err)
}
for _, c := range collections {
err = txApp.Validate(c)
if err != nil {
return fmt.Errorf("migrated collection %q validation failure: %w", c.Name, err)
}
}
return nil
}
type OldCollectionModel struct {
Id string `db:"id" json:"id"`
Created types.DateTime `db:"created" json:"created"`
Updated types.DateTime `db:"updated" json:"updated"`
Name string `db:"name" json:"name"`
Type string `db:"type" json:"type"`
System bool `db:"system" json:"system"`
Schema types.JSONArray[types.JSONMap[any]] `db:"schema" json:"schema"`
Indexes types.JSONArray[string] `db:"indexes" json:"indexes"`
ListRule *string `db:"listRule" json:"listRule"`
ViewRule *string `db:"viewRule" json:"viewRule"`
CreateRule *string `db:"createRule" json:"createRule"`
UpdateRule *string `db:"updateRule" json:"updateRule"`
DeleteRule *string `db:"deleteRule" json:"deleteRule"`
Options types.JSONMap[any] `db:"options" json:"options"`
}
func (c OldCollectionModel) TableName() string {
return "_collections"
}
func migrateRule(rule *string) *string {
if rule == nil {
return nil
}
str := strings.ReplaceAll(*rule, "@request.data", "@request.body")
return &str
}
func toBoolField(data map[string]any) map[string]any {
return map[string]any{
"type": "bool",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
}
}
func toNumberField(data map[string]any) map[string]any {
return map[string]any{
"type": "number",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"onlyInt": cast.ToBool(getMapVal(data, "options", "noDecimal")),
"min": getMapVal(data, "options", "min"),
"max": getMapVal(data, "options", "max"),
}
}
func toTextField(data map[string]any) map[string]any {
return map[string]any{
"type": "text",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"primaryKey": cast.ToBool(data["primaryKey"]),
"hidden": cast.ToBool(data["hidden"]),
"presentable": cast.ToBool(data["presentable"]),
"required": cast.ToBool(data["required"]),
"min": cast.ToInt(getMapVal(data, "options", "min")),
"max": cast.ToInt(getMapVal(data, "options", "max")),
"pattern": cast.ToString(getMapVal(data, "options", "pattern")),
"autogeneratePattern": cast.ToString(getMapVal(data, "options", "autogeneratePattern")),
}
}
func toEmailField(data map[string]any) map[string]any {
return map[string]any{
"type": "email",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"exceptDomains": cast.ToStringSlice(getMapVal(data, "options", "exceptDomains")),
"onlyDomains": cast.ToStringSlice(getMapVal(data, "options", "onlyDomains")),
}
}
func toURLField(data map[string]any) map[string]any {
return map[string]any{
"type": "url",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"exceptDomains": cast.ToStringSlice(getMapVal(data, "options", "exceptDomains")),
"onlyDomains": cast.ToStringSlice(getMapVal(data, "options", "onlyDomains")),
}
}
func toEditorField(data map[string]any) map[string]any {
return map[string]any{
"type": "editor",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"convertURLs": cast.ToBool(getMapVal(data, "options", "convertUrls")),
}
}
func toDateField(data map[string]any) map[string]any {
return map[string]any{
"type": "date",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"min": cast.ToString(getMapVal(data, "options", "min")),
"max": cast.ToString(getMapVal(data, "options", "max")),
}
}
func toJSONField(data map[string]any) map[string]any {
return map[string]any{
"type": "json",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"maxSize": cast.ToInt64(getMapVal(data, "options", "maxSize")),
}
}
func toSelectField(data map[string]any) map[string]any {
return map[string]any{
"type": "select",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"values": cast.ToStringSlice(getMapVal(data, "options", "values")),
"maxSelect": cast.ToInt(getMapVal(data, "options", "maxSelect")),
}
}
func toRelationField(data map[string]any) map[string]any {
maxSelect := cast.ToInt(getMapVal(data, "options", "maxSelect"))
if maxSelect <= 0 {
maxSelect = 2147483647
}
return map[string]any{
"type": "relation",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"collectionId": cast.ToString(getMapVal(data, "options", "collectionId")),
"cascadeDelete": cast.ToBool(getMapVal(data, "options", "cascadeDelete")),
"minSelect": cast.ToInt(getMapVal(data, "options", "minSelect")),
"maxSelect": maxSelect,
}
}
func toFileField(data map[string]any) map[string]any {
return map[string]any{
"type": "file",
"id": cast.ToString(data["id"]),
"name": cast.ToString(data["name"]),
"system": cast.ToBool(data["system"]),
"required": cast.ToBool(data["required"]),
"presentable": cast.ToBool(data["presentable"]),
"hidden": false,
"maxSelect": cast.ToInt(getMapVal(data, "options", "maxSelect")),
"maxSize": cast.ToInt64(getMapVal(data, "options", "maxSize")),
"thumbs": cast.ToStringSlice(getMapVal(data, "options", "thumbs")),
"mimeTypes": cast.ToStringSlice(getMapVal(data, "options", "mimeTypes")),
"protected": cast.ToBool(getMapVal(data, "options", "protected")),
}
}
func getMapVal(m map[string]any, keys ...string) any {
if len(keys) == 0 {
return nil
}
result, ok := m[keys[0]]
if !ok {
return nil
}
// end key reached
if len(keys) == 1 {
return result
}
if m, ok = result.(map[string]any); !ok {
return nil
}
return getMapVal(m, keys[1:]...)
}
func zeroFallback[T comparable](v T, fallback T) T {
var zero T
if v == zero {
return fallback
}
return v
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1640988000_init.go | migrations/1640988000_init.go | package migrations
import (
"fmt"
"path/filepath"
"runtime"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/types"
)
// Register is a short alias for `AppMigrations.Register()`
// that is usually used in external/user defined migrations.
func Register(
up func(app core.App) error,
down func(app core.App) error,
optFilename ...string,
) {
var optFiles []string
if len(optFilename) > 0 {
optFiles = optFilename
} else {
_, path, _, _ := runtime.Caller(1)
optFiles = append(optFiles, filepath.Base(path))
}
core.AppMigrations.Register(up, down, optFiles...)
}
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
if err := createParamsTable(txApp); err != nil {
return fmt.Errorf("_params exec error: %w", err)
}
// -----------------------------------------------------------
_, execerr := txApp.DB().NewQuery(`
CREATE TABLE {{_collections}} (
[[id]] TEXT PRIMARY KEY DEFAULT ('r'||lower(hex(randomblob(7)))) NOT NULL,
[[system]] BOOLEAN DEFAULT FALSE NOT NULL,
[[type]] TEXT DEFAULT "base" NOT NULL,
[[name]] TEXT UNIQUE NOT NULL,
[[fields]] JSON DEFAULT "[]" NOT NULL,
[[indexes]] JSON DEFAULT "[]" NOT NULL,
[[listRule]] TEXT DEFAULT NULL,
[[viewRule]] TEXT DEFAULT NULL,
[[createRule]] TEXT DEFAULT NULL,
[[updateRule]] TEXT DEFAULT NULL,
[[deleteRule]] TEXT DEFAULT NULL,
[[options]] JSON DEFAULT "{}" NOT NULL,
[[created]] TEXT DEFAULT (strftime('%Y-%m-%d %H:%M:%fZ')) NOT NULL,
[[updated]] TEXT DEFAULT (strftime('%Y-%m-%d %H:%M:%fZ')) NOT NULL
);
CREATE INDEX IF NOT EXISTS idx__collections_type on {{_collections}} ([[type]]);
`).Execute()
if execerr != nil {
return fmt.Errorf("_collections exec error: %w", execerr)
}
if err := createMFAsCollection(txApp); err != nil {
return fmt.Errorf("_mfas error: %w", err)
}
if err := createOTPsCollection(txApp); err != nil {
return fmt.Errorf("_otps error: %w", err)
}
if err := createExternalAuthsCollection(txApp); err != nil {
return fmt.Errorf("_externalAuths error: %w", err)
}
if err := createAuthOriginsCollection(txApp); err != nil {
return fmt.Errorf("_authOrigins error: %w", err)
}
if err := createSuperusersCollection(txApp); err != nil {
return fmt.Errorf("_superusers error: %w", err)
}
if err := createUsersCollection(txApp); err != nil {
return fmt.Errorf("users error: %w", err)
}
return nil
}, func(txApp core.App) error {
tables := []string{
"users",
core.CollectionNameSuperusers,
core.CollectionNameMFAs,
core.CollectionNameOTPs,
core.CollectionNameAuthOrigins,
"_params",
"_collections",
}
for _, name := range tables {
if _, err := txApp.DB().DropTable(name).Execute(); err != nil {
return err
}
}
return nil
})
}
func createParamsTable(txApp core.App) error {
_, execErr := txApp.DB().NewQuery(`
CREATE TABLE {{_params}} (
[[id]] TEXT PRIMARY KEY DEFAULT ('r'||lower(hex(randomblob(7)))) NOT NULL,
[[value]] JSON DEFAULT NULL,
[[created]] TEXT DEFAULT (strftime('%Y-%m-%d %H:%M:%fZ')) NOT NULL,
[[updated]] TEXT DEFAULT (strftime('%Y-%m-%d %H:%M:%fZ')) NOT NULL
);
`).Execute()
return execErr
}
func createMFAsCollection(txApp core.App) error {
col := core.NewBaseCollection(core.CollectionNameMFAs)
col.System = true
ownerRule := "@request.auth.id != '' && recordRef = @request.auth.id && collectionRef = @request.auth.collectionId"
col.ListRule = types.Pointer(ownerRule)
col.ViewRule = types.Pointer(ownerRule)
col.Fields.Add(&core.TextField{
Name: "collectionRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "recordRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "method",
System: true,
Required: true,
})
col.Fields.Add(&core.AutodateField{
Name: "created",
System: true,
OnCreate: true,
})
col.Fields.Add(&core.AutodateField{
Name: "updated",
System: true,
OnCreate: true,
OnUpdate: true,
})
col.AddIndex("idx_mfas_collectionRef_recordRef", false, "collectionRef,recordRef", "")
return txApp.Save(col)
}
func createOTPsCollection(txApp core.App) error {
col := core.NewBaseCollection(core.CollectionNameOTPs)
col.System = true
ownerRule := "@request.auth.id != '' && recordRef = @request.auth.id && collectionRef = @request.auth.collectionId"
col.ListRule = types.Pointer(ownerRule)
col.ViewRule = types.Pointer(ownerRule)
col.Fields.Add(&core.TextField{
Name: "collectionRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "recordRef",
System: true,
Required: true,
})
col.Fields.Add(&core.PasswordField{
Name: "password",
System: true,
Hidden: true,
Required: true,
Cost: 8, // low cost for better performance and because it is not critical
})
col.Fields.Add(&core.TextField{
Name: "sentTo",
System: true,
Hidden: true,
})
col.Fields.Add(&core.AutodateField{
Name: "created",
System: true,
OnCreate: true,
})
col.Fields.Add(&core.AutodateField{
Name: "updated",
System: true,
OnCreate: true,
OnUpdate: true,
})
col.AddIndex("idx_otps_collectionRef_recordRef", false, "collectionRef, recordRef", "")
return txApp.Save(col)
}
func createAuthOriginsCollection(txApp core.App) error {
col := core.NewBaseCollection(core.CollectionNameAuthOrigins)
col.System = true
ownerRule := "@request.auth.id != '' && recordRef = @request.auth.id && collectionRef = @request.auth.collectionId"
col.ListRule = types.Pointer(ownerRule)
col.ViewRule = types.Pointer(ownerRule)
col.DeleteRule = types.Pointer(ownerRule)
col.Fields.Add(&core.TextField{
Name: "collectionRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "recordRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "fingerprint",
System: true,
Required: true,
})
col.Fields.Add(&core.AutodateField{
Name: "created",
System: true,
OnCreate: true,
})
col.Fields.Add(&core.AutodateField{
Name: "updated",
System: true,
OnCreate: true,
OnUpdate: true,
})
col.AddIndex("idx_authOrigins_unique_pairs", true, "collectionRef, recordRef, fingerprint", "")
return txApp.Save(col)
}
func createExternalAuthsCollection(txApp core.App) error {
col := core.NewBaseCollection(core.CollectionNameExternalAuths)
col.System = true
ownerRule := "@request.auth.id != '' && recordRef = @request.auth.id && collectionRef = @request.auth.collectionId"
col.ListRule = types.Pointer(ownerRule)
col.ViewRule = types.Pointer(ownerRule)
col.DeleteRule = types.Pointer(ownerRule)
col.Fields.Add(&core.TextField{
Name: "collectionRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "recordRef",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "provider",
System: true,
Required: true,
})
col.Fields.Add(&core.TextField{
Name: "providerId",
System: true,
Required: true,
})
col.Fields.Add(&core.AutodateField{
Name: "created",
System: true,
OnCreate: true,
})
col.Fields.Add(&core.AutodateField{
Name: "updated",
System: true,
OnCreate: true,
OnUpdate: true,
})
col.AddIndex("idx_externalAuths_record_provider", true, "collectionRef, recordRef, provider", "")
col.AddIndex("idx_externalAuths_collection_provider", true, "collectionRef, provider, providerId", "")
return txApp.Save(col)
}
func createSuperusersCollection(txApp core.App) error {
superusers := core.NewAuthCollection(core.CollectionNameSuperusers)
superusers.System = true
superusers.Fields.Add(&core.EmailField{
Name: "email",
System: true,
Required: true,
})
superusers.Fields.Add(&core.AutodateField{
Name: "created",
System: true,
OnCreate: true,
})
superusers.Fields.Add(&core.AutodateField{
Name: "updated",
System: true,
OnCreate: true,
OnUpdate: true,
})
superusers.AuthToken.Duration = 86400 // 1 day
return txApp.Save(superusers)
}
func createUsersCollection(txApp core.App) error {
users := core.NewAuthCollection("users", "_pb_users_auth_")
ownerRule := "id = @request.auth.id"
users.ListRule = types.Pointer(ownerRule)
users.ViewRule = types.Pointer(ownerRule)
users.CreateRule = types.Pointer("")
users.UpdateRule = types.Pointer(ownerRule)
users.DeleteRule = types.Pointer(ownerRule)
users.Fields.Add(&core.TextField{
Name: "name",
Max: 255,
})
users.Fields.Add(&core.FileField{
Name: "avatar",
MaxSelect: 1,
MimeTypes: []string{"image/jpeg", "image/png", "image/svg+xml", "image/gif", "image/webp"},
})
users.Fields.Add(&core.AutodateField{
Name: "created",
OnCreate: true,
})
users.Fields.Add(&core.AutodateField{
Name: "updated",
OnCreate: true,
OnUpdate: true,
})
users.OAuth2.MappedFields.Name = "name"
users.OAuth2.MappedFields.AvatarURL = "avatar"
return txApp.Save(users)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1640988000_aux_init.go | migrations/1640988000_aux_init.go | package migrations
import (
"github.com/pocketbase/pocketbase/core"
)
func init() {
core.SystemMigrations.Add(&core.Migration{
Up: func(txApp core.App) error {
_, execErr := txApp.AuxDB().NewQuery(`
CREATE TABLE IF NOT EXISTS {{_logs}} (
[[id]] TEXT PRIMARY KEY DEFAULT ('r'||lower(hex(randomblob(7)))) NOT NULL,
[[level]] INTEGER DEFAULT 0 NOT NULL,
[[message]] TEXT DEFAULT "" NOT NULL,
[[data]] JSON DEFAULT "{}" NOT NULL,
[[created]] TEXT DEFAULT (strftime('%Y-%m-%d %H:%M:%fZ')) NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_logs_level on {{_logs}} ([[level]]);
CREATE INDEX IF NOT EXISTS idx_logs_message on {{_logs}} ([[message]]);
CREATE INDEX IF NOT EXISTS idx_logs_created_hour on {{_logs}} (strftime('%Y-%m-%d %H:00:00', [[created]]));
`).Execute()
return execErr
},
Down: func(txApp core.App) error {
_, err := txApp.AuxDB().DropTable("_logs").Execute()
return err
},
ReapplyCondition: func(txApp core.App, runner *core.MigrationsRunner, fileName string) (bool, error) {
// reapply only if the _logs table doesn't exist
exists := txApp.AuxHasTable("_logs")
return !exists, nil
},
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1717233559_v0.23_migrate4.go | migrations/1717233559_v0.23_migrate4.go | package migrations
import (
"github.com/pocketbase/pocketbase/core"
)
// note: this migration will be deleted in future version
// add new OTP sentTo text field (if not already)
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
otpCollection, err := txApp.FindCollectionByNameOrId(core.CollectionNameOTPs)
if err != nil {
return err
}
field := otpCollection.Fields.GetByName("sentTo")
if field != nil {
return nil // already exists
}
otpCollection.Fields.Add(&core.TextField{
Name: "sentTo",
System: true,
Hidden: true,
})
return txApp.Save(otpCollection)
}, nil)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/migrations/1763020353_update_default_auth_alert_templates.go | migrations/1763020353_update_default_auth_alert_templates.go | package migrations
import (
"github.com/pocketbase/pocketbase/core"
)
const oldAuthAlertTemplate = `<p>Hello,</p>
<p>We noticed a login to your {APP_NAME} account from a new location.</p>
<p>If this was you, you may disregard this email.</p>
<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>
<p>
Thanks,<br/>
{APP_NAME} team
</p>`
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
collections, err := txApp.FindAllCollections(core.CollectionTypeAuth)
if err != nil {
return err
}
newTemplate := core.NewAuthCollection("up").AuthAlert.EmailTemplate.Body
for _, c := range collections {
if c.AuthAlert.EmailTemplate.Body != oldAuthAlertTemplate {
continue
}
c.AuthAlert.EmailTemplate.Body = newTemplate
err = txApp.Save(c)
if err != nil {
return err
}
}
return nil
}, func(txApp core.App) error {
collections, err := txApp.FindAllCollections(core.CollectionTypeAuth)
if err != nil {
return err
}
newTemplate := core.NewAuthCollection("down").AuthAlert.EmailTemplate.Body
for _, c := range collections {
if c.AuthAlert.EmailTemplate.Body != newTemplate {
continue
}
c.AuthAlert.EmailTemplate.Body = oldAuthAlertTemplate
err = txApp.Save(c)
if err != nil {
return err
}
}
return nil
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/examples/base/main.go | examples/base/main.go | package main
import (
"log"
"net/http"
"os"
"path/filepath"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/plugins/ghupdate"
"github.com/pocketbase/pocketbase/plugins/jsvm"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/osutils"
)
func main() {
app := pocketbase.New()
// ---------------------------------------------------------------
// Optional plugin flags:
// ---------------------------------------------------------------
var hooksDir string
app.RootCmd.PersistentFlags().StringVar(
&hooksDir,
"hooksDir",
"",
"the directory with the JS app hooks",
)
var hooksWatch bool
app.RootCmd.PersistentFlags().BoolVar(
&hooksWatch,
"hooksWatch",
true,
"auto restart the app on pb_hooks file change; it has no effect on Windows",
)
var hooksPool int
app.RootCmd.PersistentFlags().IntVar(
&hooksPool,
"hooksPool",
15,
"the total prewarm goja.Runtime instances for the JS app hooks execution",
)
var migrationsDir string
app.RootCmd.PersistentFlags().StringVar(
&migrationsDir,
"migrationsDir",
"",
"the directory with the user defined migrations",
)
var automigrate bool
app.RootCmd.PersistentFlags().BoolVar(
&automigrate,
"automigrate",
true,
"enable/disable auto migrations",
)
var publicDir string
app.RootCmd.PersistentFlags().StringVar(
&publicDir,
"publicDir",
defaultPublicDir(),
"the directory to serve static files",
)
var indexFallback bool
app.RootCmd.PersistentFlags().BoolVar(
&indexFallback,
"indexFallback",
true,
"fallback the request to index.html on missing static path, e.g. when pretty urls are used with SPA",
)
app.RootCmd.ParseFlags(os.Args[1:])
// ---------------------------------------------------------------
// Plugins and hooks:
// ---------------------------------------------------------------
// load jsvm (pb_hooks and pb_migrations)
jsvm.MustRegister(app, jsvm.Config{
MigrationsDir: migrationsDir,
HooksDir: hooksDir,
HooksWatch: hooksWatch,
HooksPoolSize: hooksPool,
})
// migrate command (with js templates)
migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{
TemplateLang: migratecmd.TemplateLangJS,
Automigrate: automigrate,
Dir: migrationsDir,
})
// GitHub selfupdate
ghupdate.MustRegister(app, app.RootCmd, ghupdate.Config{})
// static route to serves files from the provided public dir
// (if publicDir exists and the route path is not already defined)
app.OnServe().Bind(&hook.Handler[*core.ServeEvent]{
Func: func(e *core.ServeEvent) error {
if !e.Router.HasRoute(http.MethodGet, "/{path...}") {
e.Router.GET("/{path...}", apis.Static(os.DirFS(publicDir), indexFallback))
}
return e.Next()
},
Priority: 999, // execute as latest as possible to allow users to provide their own route
})
if err := app.Start(); err != nil {
log.Fatal(err)
}
}
// the default pb_public dir location is relative to the executable
func defaultPublicDir() string {
if osutils.IsProbablyGoRun() {
return "./pb_public"
}
return filepath.Join(os.Args[0], "../pb_public")
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/migrations_list.go | core/migrations_list.go | package core
import (
"path/filepath"
"runtime"
"sort"
)
type Migration struct {
Up func(txApp App) error
Down func(txApp App) error
File string
ReapplyCondition func(txApp App, runner *MigrationsRunner, fileName string) (bool, error)
}
// MigrationsList defines a list with migration definitions
type MigrationsList struct {
list []*Migration
}
// Item returns a single migration from the list by its index.
func (l *MigrationsList) Item(index int) *Migration {
return l.list[index]
}
// Items returns the internal migrations list slice.
func (l *MigrationsList) Items() []*Migration {
return l.list
}
// Copy copies all provided list migrations into the current one.
func (l *MigrationsList) Copy(list MigrationsList) {
for _, item := range list.Items() {
l.Register(item.Up, item.Down, item.File)
}
}
// Add adds adds an existing migration definition to the list.
//
// If m.File is not provided, it will try to get the name from its .go file.
//
// The list will be sorted automatically based on the migrations file name.
func (l *MigrationsList) Add(m *Migration) {
if m.File == "" {
_, path, _, _ := runtime.Caller(1)
m.File = filepath.Base(path)
}
l.list = append(l.list, m)
sort.SliceStable(l.list, func(i int, j int) bool {
return l.list[i].File < l.list[j].File
})
}
// Register adds new migration definition to the list.
//
// If optFilename is not provided, it will try to get the name from its .go file.
//
// The list will be sorted automatically based on the migrations file name.
func (l *MigrationsList) Register(
up func(txApp App) error,
down func(txApp App) error,
optFilename ...string,
) {
var file string
if len(optFilename) > 0 {
file = optFilename[0]
} else {
_, path, _, _ := runtime.Caller(1)
file = filepath.Base(path)
}
l.list = append(l.list, &Migration{
File: file,
Up: up,
Down: down,
})
sort.SliceStable(l.list, func(i int, j int) bool {
return l.list[i].File < l.list[j].File
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_editor_test.go | core/field_editor_test.go | package core_test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestEditorFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeEditor)
}
func TestEditorFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.EditorField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestEditorFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.EditorField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"test", "test"},
{false, "false"},
{true, "true"},
{123.456, "123.456"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vStr, ok := v.(string)
if !ok {
t.Fatalf("Expected string instance, got %T", v)
}
if vStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, v)
}
})
}
}
func TestEditorFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.EditorField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.EditorField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (not required)",
&core.EditorField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
false,
},
{
"zero field value (required)",
&core.EditorField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"non-zero field value (required)",
&core.EditorField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc")
return record
},
false,
},
{
"> default MaxSize",
&core.EditorField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", strings.Repeat("a", 1+(5<<20)))
return record
},
true,
},
{
"> MaxSize",
&core.EditorField{Name: "test", Required: true, MaxSize: 5},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abcdef")
return record
},
true,
},
{
"<= MaxSize",
&core.EditorField{Name: "test", Required: true, MaxSize: 5},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abcde")
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestEditorFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeEditor)
testDefaultFieldNameValidation(t, core.FieldTypeEditor)
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() *core.EditorField
expectErrors []string
}{
{
"< 0 MaxSize",
func() *core.EditorField {
return &core.EditorField{
Id: "test",
Name: "test",
MaxSize: -1,
}
},
[]string{"maxSize"},
},
{
"= 0 MaxSize",
func() *core.EditorField {
return &core.EditorField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"> 0 MaxSize",
func() *core.EditorField {
return &core.EditorField{
Id: "test",
Name: "test",
MaxSize: 1,
}
},
[]string{},
},
{
"MaxSize > safe json int",
func() *core.EditorField {
return &core.EditorField{
Id: "test",
Name: "test",
MaxSize: 1 << 53,
}
},
[]string{"maxSize"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestEditorFieldCalculateMaxBodySize(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
scenarios := []struct {
field *core.EditorField
expected int64
}{
{&core.EditorField{}, core.DefaultEditorFieldMaxSize},
{&core.EditorField{MaxSize: 10}, 10},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d", i, s.field.MaxSize), func(t *testing.T) {
result := s.field.CalculateMaxBodySize()
if result != s.expected {
t.Fatalf("Expected %d, got %d", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_field_resolver_runner.go | core/record_field_resolver_runner.go | package core
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
// maxNestedRels defines the max allowed nested relations depth.
const maxNestedRels = 6
// list of auth filter fields that don't require join with the auth
// collection or any other extra checks to be resolved.
var plainRequestAuthFields = map[string]struct{}{
"@request.auth." + FieldNameId: {},
"@request.auth." + FieldNameCollectionId: {},
"@request.auth." + FieldNameCollectionName: {},
"@request.auth." + FieldNameEmail: {},
"@request.auth." + FieldNameEmailVisibility: {},
"@request.auth." + FieldNameVerified: {},
}
// parseAndRun starts a new one-off RecordFieldResolver.Resolve execution.
func parseAndRun(fieldName string, resolver *RecordFieldResolver) (*search.ResolverResult, error) {
r := &runner{
fieldName: fieldName,
resolver: resolver,
}
return r.run()
}
type runner struct {
used bool // indicates whether the runner was already executed
resolver *RecordFieldResolver // resolver is the shared expression fields resolver
fieldName string // the name of the single field expression the runner is responsible for
// shared processing state
// ---------------------------------------------------------------
activeProps []string // holds the active props that remains to be processed
activeCollectionName string // the last used collection name
activeTableAlias string // the last used table alias
nullifyMisingField bool // indicating whether to return null on missing field or return an error
withMultiMatch bool // indicates whether to attach a multiMatchSubquery condition to the ResolverResult
multiMatchActiveTableAlias string // the last used multi-match table alias
multiMatch *multiMatchSubquery // the multi-match subquery expression generated from the fieldName
}
func (r *runner) run() (*search.ResolverResult, error) {
if r.used {
return nil, errors.New("the runner was already used")
}
if len(r.resolver.allowedFields) > 0 && !list.ExistInSliceWithRegex(r.fieldName, r.resolver.allowedFields) {
return nil, fmt.Errorf("failed to resolve field %q", r.fieldName)
}
defer func() {
r.used = true
}()
r.prepare()
// check for @collection field (aka. non-relational join)
// must be in the format "@collection.COLLECTION_NAME.FIELD[.FIELD2....]"
if r.activeProps[0] == "@collection" {
return r.processCollectionField()
}
if r.activeProps[0] == "@request" {
// @todo consider returning an error instead?
if r.resolver.requestInfo == nil {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
if strings.HasPrefix(r.fieldName, "@request.auth.") {
return r.processRequestAuthField()
}
totalProps := len(r.activeProps)
if strings.HasPrefix(r.fieldName, "@request.body.") && totalProps > 2 {
name, modifier, err := splitModifier(r.activeProps[2])
if err != nil {
return nil, err
}
bodyField := r.resolver.baseCollection.Fields.GetByName(name)
if bodyField == nil {
return r.resolver.resolveStaticRequestField(r.activeProps[1:]...)
}
// check for body relation field
if bodyField.Type() == FieldTypeRelation && totalProps > 3 {
return r.processRequestBodyRelationField(bodyField)
}
if totalProps == 3 { // aka. last prop
switch modifier {
case eachModifier:
return r.processRequestBodyEachModifier(bodyField)
case lengthModifier:
return r.processRequestBodyLengthModifier(bodyField)
case lowerModifier:
return r.processRequestBodyLowerModifier(bodyField)
case changedModifier:
return r.processRequestBodyChangedModifier(bodyField)
}
}
}
// some other @request.* static field
return r.resolver.resolveStaticRequestField(r.activeProps[1:]...)
}
// regular field
return r.processActiveProps()
}
func (r *runner) prepare() {
r.activeProps = strings.Split(r.fieldName, ".")
r.activeCollectionName = r.resolver.baseCollection.Name
if r.resolver.baseCollectionAlias == "" {
r.activeTableAlias = inflector.Columnify(r.activeCollectionName)
} else {
r.activeTableAlias = r.resolver.baseCollectionAlias
}
// enable the ignore flag for missing @request.* fields for backward
// compatibility and consistency with all @request.* filter fields and types
r.nullifyMisingField = r.activeProps[0] == "@request"
// prepare a multi-match subquery
r.multiMatch = &multiMatchSubquery{
baseTableAlias: r.activeTableAlias,
params: dbx.Params{},
}
r.multiMatch.fromTableName = inflector.Columnify(r.activeCollectionName)
r.multiMatch.fromTableAlias = "__mm_" + r.activeTableAlias
r.multiMatchActiveTableAlias = r.multiMatch.fromTableAlias
r.withMultiMatch = false
}
func (r *runner) processCollectionField() (*search.ResolverResult, error) {
if len(r.activeProps) < 3 {
return nil, fmt.Errorf("invalid @collection field path in %q", r.fieldName)
}
// nameOrId or nameOrId:alias
collectionParts := strings.SplitN(r.activeProps[1], ":", 2)
collection, err := r.resolver.loadCollection(collectionParts[0])
if err != nil {
return nil, fmt.Errorf("failed to load collection %q from field path %q", r.activeProps[1], r.fieldName)
}
r.activeCollectionName = collection.Name
if len(collectionParts) == 2 && collectionParts[1] != "" {
r.activeTableAlias = inflector.Columnify("__collection_alias_"+collectionParts[1]) + r.resolver.joinAliasSuffix
} else {
r.activeTableAlias = inflector.Columnify("__collection_"+r.activeCollectionName) + r.resolver.joinAliasSuffix
}
r.withMultiMatch = true
// join the collection to the main query
err = r.resolver.registerJoin(inflector.Columnify(collection.Name), r.activeTableAlias, nil)
if err != nil {
return nil, err
}
// join the collection to the multi-match subquery
r.multiMatchActiveTableAlias = "__mm_" + r.activeTableAlias
r.multiMatch.joins = append(r.multiMatch.joins, &join{
tableName: inflector.Columnify(collection.Name),
tableAlias: r.multiMatchActiveTableAlias,
})
// leave only the collection fields
// aka. @collection.someCollection.fieldA.fieldB -> fieldA.fieldB
r.activeProps = r.activeProps[2:]
return r.processActiveProps()
}
func (r *runner) processRequestAuthField() (*search.ResolverResult, error) {
if r.resolver.requestInfo == nil || r.resolver.requestInfo.Auth == nil || r.resolver.requestInfo.Auth.Collection() == nil {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
// plain auth field
// ---
if _, ok := plainRequestAuthFields[r.fieldName]; ok {
return r.resolver.resolveStaticRequestField(r.activeProps[1:]...)
}
// resolve the auth collection field
// ---
collection := r.resolver.requestInfo.Auth.Collection()
r.activeCollectionName = collection.Name
r.activeTableAlias = "__auth_" + inflector.Columnify(r.activeCollectionName) + r.resolver.joinAliasSuffix
// join the auth collection to the main query
err := r.resolver.registerJoin(
inflector.Columnify(r.activeCollectionName),
r.activeTableAlias,
dbx.HashExp{
// aka. __auth_users.id = :userId
(r.activeTableAlias + ".id"): r.resolver.requestInfo.Auth.Id,
},
)
if err != nil {
return nil, err
}
// join the auth collection to the multi-match subquery
r.multiMatchActiveTableAlias = "__mm_" + r.activeTableAlias
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: inflector.Columnify(r.activeCollectionName),
tableAlias: r.multiMatchActiveTableAlias,
on: dbx.HashExp{
(r.multiMatchActiveTableAlias + ".id"): r.resolver.requestInfo.Auth.Id,
},
},
)
// leave only the auth relation fields
// aka. @request.auth.fieldA.fieldB -> fieldA.fieldB
r.activeProps = r.activeProps[2:]
return r.processActiveProps()
}
// note: nil value is returned as empty slice
func toSlice(value any) []any {
if value == nil {
return []any{}
}
rv := reflect.ValueOf(value)
kind := rv.Kind()
if kind != reflect.Slice && kind != reflect.Array {
return []any{value}
}
rvLen := rv.Len()
result := make([]interface{}, rvLen)
for i := 0; i < rvLen; i++ {
result[i] = rv.Index(i).Interface()
}
return result
}
func (r *runner) processRequestBodyChangedModifier(bodyField Field) (*search.ResolverResult, error) {
name := bodyField.GetName()
alias := search.FilterData(fmt.Sprintf("@request.body.%s:isset = true && @request.body.%s != %s", name, name, name))
aliasExpr, err := alias.BuildExpr(r.resolver)
if err != nil {
return nil, err
}
placeholder := "@changed@" + name + security.PseudorandomString(6)
result := &search.ResolverResult{
Identifier: placeholder,
NoCoalesce: true,
AfterBuild: func(expr dbx.Expression) dbx.Expression {
return &replaceWithExpression{
placeholder: placeholder,
old: expr,
new: aliasExpr,
}
},
}
return result, nil
}
func (r *runner) processRequestBodyLowerModifier(bodyField Field) (*search.ResolverResult, error) {
rawValue := cast.ToString(r.resolver.requestInfo.Body[bodyField.GetName()])
placeholder := "infoLower" + bodyField.GetName() + security.PseudorandomString(6)
result := &search.ResolverResult{
Identifier: "LOWER({:" + placeholder + "})",
Params: dbx.Params{placeholder: rawValue},
}
return result, nil
}
func (r *runner) processRequestBodyLengthModifier(bodyField Field) (*search.ResolverResult, error) {
if _, ok := bodyField.(MultiValuer); !ok {
return nil, fmt.Errorf("field %q doesn't support multivalue operations", bodyField.GetName())
}
bodyItems := toSlice(r.resolver.requestInfo.Body[bodyField.GetName()])
result := &search.ResolverResult{
Identifier: strconv.Itoa(len(bodyItems)),
}
return result, nil
}
func (r *runner) processRequestBodyEachModifier(bodyField Field) (*search.ResolverResult, error) {
multiValuer, ok := bodyField.(MultiValuer)
if !ok {
return nil, fmt.Errorf("field %q doesn't support multivalue operations", bodyField.GetName())
}
bodyItems := toSlice(r.resolver.requestInfo.Body[bodyField.GetName()])
bodyItemsRaw, err := json.Marshal(bodyItems)
if err != nil {
return nil, fmt.Errorf("cannot serialize the data for field %q", r.activeProps[2])
}
placeholder := "dataEach" + security.PseudorandomString(6)
cleanFieldName := inflector.Columnify(bodyField.GetName())
jeTable := fmt.Sprintf("json_each({:%s})", placeholder)
jeAlias := "__dataEach_je_" + cleanFieldName + r.resolver.joinAliasSuffix
err = r.resolver.registerJoin(jeTable, jeAlias, nil)
if err != nil {
return nil, err
}
result := &search.ResolverResult{
Identifier: fmt.Sprintf("[[%s.value]]", jeAlias),
Params: dbx.Params{placeholder: bodyItemsRaw},
}
if multiValuer.IsMultiple() {
r.withMultiMatch = true
}
if r.withMultiMatch {
placeholder2 := "mm" + placeholder
jeTable2 := fmt.Sprintf("json_each({:%s})", placeholder2)
jeAlias2 := "__mm_" + jeAlias
r.multiMatch.joins = append(r.multiMatch.joins, &join{
tableName: jeTable2,
tableAlias: jeAlias2,
})
r.multiMatch.params[placeholder2] = bodyItemsRaw
r.multiMatch.valueIdentifier = fmt.Sprintf("[[%s.value]]", jeAlias2)
result.MultiMatchSubQuery = r.multiMatch
}
return result, nil
}
func (r *runner) processRequestBodyRelationField(bodyField Field) (*search.ResolverResult, error) {
relField, ok := bodyField.(*RelationField)
if !ok {
return nil, fmt.Errorf("failed to initialize data relation field %q", bodyField.GetName())
}
dataRelCollection, err := r.resolver.loadCollection(relField.CollectionId)
if err != nil {
return nil, fmt.Errorf("failed to load collection %q from data field %q", relField.CollectionId, relField.Name)
}
var dataRelIds []string
if r.resolver.requestInfo != nil && len(r.resolver.requestInfo.Body) != 0 {
dataRelIds = list.ToUniqueStringSlice(r.resolver.requestInfo.Body[relField.Name])
}
if len(dataRelIds) == 0 {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
r.activeCollectionName = dataRelCollection.Name
r.activeTableAlias = inflector.Columnify("__data_"+dataRelCollection.Name+"_"+relField.Name) + r.resolver.joinAliasSuffix
// join the data rel collection to the main collection
err = r.resolver.registerJoin(
r.activeCollectionName,
r.activeTableAlias,
dbx.In(
fmt.Sprintf("[[%s.id]]", r.activeTableAlias),
list.ToInterfaceSlice(dataRelIds)...,
),
)
if err != nil {
return nil, err
}
if relField.IsMultiple() {
r.withMultiMatch = true
}
// join the data rel collection to the multi-match subquery
r.multiMatchActiveTableAlias = "__mm_" + r.activeTableAlias
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: r.activeCollectionName,
tableAlias: r.multiMatchActiveTableAlias,
on: dbx.In(
fmt.Sprintf("[[%s.id]]", r.multiMatchActiveTableAlias),
list.ToInterfaceSlice(dataRelIds)...,
),
},
)
// leave only the data relation fields
// aka. @request.body.someRel.fieldA.fieldB -> fieldA.fieldB
r.activeProps = r.activeProps[3:]
return r.processActiveProps()
}
var viaRegex = regexp.MustCompile(`^(\w+)_via_(\w+)$`)
// @todo refactor and abstract lastProp processing with the support of field plugins
func (r *runner) processActiveProps() (*search.ResolverResult, error) {
totalProps := len(r.activeProps)
for i, prop := range r.activeProps {
collection, err := r.resolver.loadCollection(r.activeCollectionName)
if err != nil {
return nil, fmt.Errorf("failed to resolve field %q", prop)
}
// last prop
if i == totalProps-1 {
return r.finalizeActivePropsProcessing(collection, prop, i)
}
field := collection.Fields.GetByName(prop)
if field != nil && field.GetHidden() && !r.resolver.allowHiddenFields {
return nil, fmt.Errorf("non-filterable field %q", prop)
}
// @todo consider moving to the finalizer and converting to "JSONExtractable" interface with optional extra validation for the remaining props?
// json or geoPoint field -> treat the rest of the props as json path
if field != nil && (field.Type() == FieldTypeJSON || field.Type() == FieldTypeGeoPoint) {
var jsonPath strings.Builder
for j, p := range r.activeProps[i+1:] {
if _, err := strconv.Atoi(p); err == nil {
jsonPath.WriteString("[")
jsonPath.WriteString(inflector.Columnify(p))
jsonPath.WriteString("]")
} else {
if j > 0 {
jsonPath.WriteString(".")
}
jsonPath.WriteString(inflector.Columnify(p))
}
}
jsonPathStr := jsonPath.String()
result := &search.ResolverResult{
NoCoalesce: true,
Identifier: dbutils.JSONExtract(r.activeTableAlias+"."+inflector.Columnify(prop), jsonPathStr),
}
if r.withMultiMatch {
r.multiMatch.valueIdentifier = dbutils.JSONExtract(r.multiMatchActiveTableAlias+"."+inflector.Columnify(prop), jsonPathStr)
result.MultiMatchSubQuery = r.multiMatch
}
return result, nil
}
if i >= maxNestedRels {
return nil, fmt.Errorf("max nested relations reached for field %q", prop)
}
// check for back relation (eg. yourCollection_via_yourRelField)
// -----------------------------------------------------------
if field == nil {
parts := viaRegex.FindStringSubmatch(prop)
if len(parts) != 3 {
if r.nullifyMisingField {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
return nil, fmt.Errorf("failed to resolve field %q", prop)
}
backCollection, err := r.resolver.loadCollection(parts[1])
if err != nil {
if r.nullifyMisingField {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
return nil, fmt.Errorf("failed to load back relation field %q collection", prop)
}
backField := backCollection.Fields.GetByName(parts[2])
if backField == nil {
if r.nullifyMisingField {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
return nil, fmt.Errorf("missing back relation field %q", parts[2])
}
if backField.Type() != FieldTypeRelation {
if r.nullifyMisingField {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
return nil, fmt.Errorf("invalid back relation field %q", parts[2])
}
if backField.GetHidden() && !r.resolver.allowHiddenFields {
return nil, fmt.Errorf("non-filterable back relation field %q", backField.GetName())
}
backRelField, ok := backField.(*RelationField)
if !ok {
return nil, fmt.Errorf("failed to initialize back relation field %q", backField.GetName())
}
if backRelField.CollectionId != collection.Id {
// https://github.com/pocketbase/pocketbase/discussions/6590#discussioncomment-12496581
if r.nullifyMisingField {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
return nil, fmt.Errorf("invalid collection reference of a back relation field %q", backField.GetName())
}
// join the back relation to the main query
// ---
cleanProp := inflector.Columnify(prop)
cleanBackFieldName := inflector.Columnify(backRelField.Name)
newTableAlias := r.activeTableAlias + "_" + cleanProp + r.resolver.joinAliasSuffix
newCollectionName := inflector.Columnify(backCollection.Name)
isBackRelMultiple := backRelField.IsMultiple()
if !isBackRelMultiple {
// additionally check if the rel field has a single column unique index
_, hasUniqueIndex := dbutils.FindSingleColumnUniqueIndex(backCollection.Indexes, backRelField.Name)
isBackRelMultiple = !hasUniqueIndex
}
if !isBackRelMultiple {
err := r.resolver.registerJoin(
newCollectionName,
newTableAlias,
dbx.NewExp(fmt.Sprintf("[[%s.%s]] = [[%s.id]]", newTableAlias, cleanBackFieldName, r.activeTableAlias)),
)
if err != nil {
return nil, err
}
} else {
jeAlias := "__je_" + newTableAlias
err := r.resolver.registerJoin(
newCollectionName,
newTableAlias,
dbx.NewExp(fmt.Sprintf(
"[[%s.id]] IN (SELECT [[%s.value]] FROM %s {{%s}})",
r.activeTableAlias,
jeAlias,
dbutils.JSONEach(newTableAlias+"."+cleanBackFieldName),
jeAlias,
)),
)
if err != nil {
return nil, err
}
}
r.activeCollectionName = newCollectionName
r.activeTableAlias = newTableAlias
// ---
// join the back relation to the multi-match subquery
// ---
if isBackRelMultiple {
r.withMultiMatch = true // enable multimatch if not already
}
newTableAlias2 := r.multiMatchActiveTableAlias + "_" + cleanProp + r.resolver.joinAliasSuffix
if !isBackRelMultiple {
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: newCollectionName,
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf("[[%s.%s]] = [[%s.id]]", newTableAlias2, cleanBackFieldName, r.multiMatchActiveTableAlias)),
},
)
} else {
jeAlias2 := "__je_" + newTableAlias2
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: newCollectionName,
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf(
"[[%s.id]] IN (SELECT [[%s.value]] FROM %s {{%s}})",
r.multiMatchActiveTableAlias,
jeAlias2,
dbutils.JSONEach(newTableAlias2+"."+cleanBackFieldName),
jeAlias2,
)),
},
)
}
r.multiMatchActiveTableAlias = newTableAlias2
// ---
continue
}
// -----------------------------------------------------------
// check for direct relation
if field.Type() != FieldTypeRelation {
return nil, fmt.Errorf("field %q is not a valid relation", prop)
}
// join the relation to the main query
// ---
relField, ok := field.(*RelationField)
if !ok {
return nil, fmt.Errorf("failed to initialize relation field %q", prop)
}
relCollection, relErr := r.resolver.loadCollection(relField.CollectionId)
if relErr != nil {
return nil, fmt.Errorf("failed to load field %q collection", prop)
}
// "id" lookups optimization for single relations to avoid unnecessary joins,
// aka. "user.id" and "user" should produce the same query identifier
if !relField.IsMultiple() &&
// the penultimate prop is "id"
i == totalProps-2 && r.activeProps[i+1] == FieldNameId {
return r.finalizeActivePropsProcessing(collection, relField.Name, i)
}
cleanFieldName := inflector.Columnify(relField.Name)
prefixedFieldName := r.activeTableAlias + "." + cleanFieldName
newTableAlias := r.activeTableAlias + "_" + cleanFieldName + r.resolver.joinAliasSuffix
newCollectionName := relCollection.Name
if !relField.IsMultiple() {
err := r.resolver.registerJoin(
inflector.Columnify(newCollectionName),
newTableAlias,
dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s]]", newTableAlias, prefixedFieldName)),
)
if err != nil {
return nil, err
}
} else {
jeAlias := "__je_" + newTableAlias
err := r.resolver.registerJoin(dbutils.JSONEach(prefixedFieldName), jeAlias, nil)
if err != nil {
return nil, err
}
err = r.resolver.registerJoin(
inflector.Columnify(newCollectionName),
newTableAlias,
dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s.value]]", newTableAlias, jeAlias)),
)
if err != nil {
return nil, err
}
}
r.activeCollectionName = newCollectionName
r.activeTableAlias = newTableAlias
// ---
// join the relation to the multi-match subquery
// ---
if relField.IsMultiple() {
r.withMultiMatch = true // enable multimatch if not already
}
newTableAlias2 := r.multiMatchActiveTableAlias + "_" + cleanFieldName
prefixedFieldName2 := r.multiMatchActiveTableAlias + "." + cleanFieldName
if !relField.IsMultiple() {
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: inflector.Columnify(newCollectionName),
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s]]", newTableAlias2, prefixedFieldName2)),
},
)
} else {
jeAlias2 := r.multiMatchActiveTableAlias + "_" + cleanFieldName + "_je"
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: dbutils.JSONEach(prefixedFieldName2),
tableAlias: jeAlias2,
},
&join{
tableName: inflector.Columnify(newCollectionName),
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s.value]]", newTableAlias2, jeAlias2)),
},
)
}
r.multiMatchActiveTableAlias = newTableAlias2
// ---
}
return nil, fmt.Errorf("failed to resolve field %q", r.fieldName)
}
func (r *runner) finalizeActivePropsProcessing(collection *Collection, prop string, propDepth int) (*search.ResolverResult, error) {
name, modifier, err := splitModifier(prop)
if err != nil {
return nil, err
}
field := collection.Fields.GetByName(name)
if field == nil {
if r.nullifyMisingField {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
return nil, fmt.Errorf("unknown field %q", name)
}
if field.GetHidden() && !r.resolver.allowHiddenFields {
return nil, fmt.Errorf("non-filterable field %q", name)
}
multvaluer, isMultivaluer := field.(MultiValuer)
cleanFieldName := inflector.Columnify(field.GetName())
// arrayable fields with ":length" modifier
// -------------------------------------------------------
if modifier == lengthModifier && isMultivaluer {
jePair := r.activeTableAlias + "." + cleanFieldName
result := &search.ResolverResult{
Identifier: dbutils.JSONArrayLength(jePair),
}
if r.withMultiMatch {
jePair2 := r.multiMatchActiveTableAlias + "." + cleanFieldName
r.multiMatch.valueIdentifier = dbutils.JSONArrayLength(jePair2)
result.MultiMatchSubQuery = r.multiMatch
}
return result, nil
}
// arrayable fields with ":each" modifier
// -------------------------------------------------------
if modifier == eachModifier && isMultivaluer {
jePair := r.activeTableAlias + "." + cleanFieldName
jeAlias := "__je_" + r.activeTableAlias + "_" + cleanFieldName + r.resolver.joinAliasSuffix
err := r.resolver.registerJoin(dbutils.JSONEach(jePair), jeAlias, nil)
if err != nil {
return nil, err
}
result := &search.ResolverResult{
Identifier: fmt.Sprintf("[[%s.value]]", jeAlias),
}
if multvaluer.IsMultiple() {
r.withMultiMatch = true
}
if r.withMultiMatch {
jePair2 := r.multiMatchActiveTableAlias + "." + cleanFieldName
jeAlias2 := "__je_" + r.multiMatchActiveTableAlias + "_" + cleanFieldName + r.resolver.joinAliasSuffix
r.multiMatch.joins = append(r.multiMatch.joins, &join{
tableName: dbutils.JSONEach(jePair2),
tableAlias: jeAlias2,
})
r.multiMatch.valueIdentifier = fmt.Sprintf("[[%s.value]]", jeAlias2)
result.MultiMatchSubQuery = r.multiMatch
}
return result, nil
}
// default
// -------------------------------------------------------
result := &search.ResolverResult{
Identifier: "[[" + r.activeTableAlias + "." + cleanFieldName + "]]",
}
if r.withMultiMatch {
r.multiMatch.valueIdentifier = "[[" + r.multiMatchActiveTableAlias + "." + cleanFieldName + "]]"
result.MultiMatchSubQuery = r.multiMatch
}
// allow querying only auth records with emails marked as public
if field.GetName() == FieldNameEmail && !r.resolver.allowHiddenFields && collection.IsAuth() {
result.AfterBuild = func(expr dbx.Expression) dbx.Expression {
return dbx.Enclose(dbx.And(expr, dbx.NewExp(fmt.Sprintf(
"[[%s.%s]] = TRUE",
r.activeTableAlias,
FieldNameEmailVisibility,
))))
}
}
// wrap in json_extract to ensure that top-level primitives
// stored as json work correctly when compared to their SQL equivalent
// (https://github.com/pocketbase/pocketbase/issues/4068)
if field.Type() == FieldTypeJSON {
result.NoCoalesce = true
result.Identifier = dbutils.JSONExtract(r.activeTableAlias+"."+cleanFieldName, "")
if r.withMultiMatch {
r.multiMatch.valueIdentifier = dbutils.JSONExtract(r.multiMatchActiveTableAlias+"."+cleanFieldName, "")
}
}
// account for the ":lower" modifier
if modifier == lowerModifier {
result.Identifier = "LOWER(" + result.Identifier + ")"
if r.withMultiMatch {
r.multiMatch.valueIdentifier = "LOWER(" + r.multiMatch.valueIdentifier + ")"
}
}
return result, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_table.go | core/db_table.go | package core
import (
"database/sql"
"fmt"
"github.com/pocketbase/dbx"
)
// TableColumns returns all column names of a single table by its name.
func (app *BaseApp) TableColumns(tableName string) ([]string, error) {
columns := []string{}
err := app.ConcurrentDB().NewQuery("SELECT name FROM PRAGMA_TABLE_INFO({:tableName})").
Bind(dbx.Params{"tableName": tableName}).
Column(&columns)
return columns, err
}
type TableInfoRow struct {
// the `db:"pk"` tag has special semantic so we cannot rename
// the original field without specifying a custom mapper
PK int
Index int `db:"cid"`
Name string `db:"name"`
Type string `db:"type"`
NotNull bool `db:"notnull"`
DefaultValue sql.NullString `db:"dflt_value"`
}
// TableInfo returns the "table_info" pragma result for the specified table.
func (app *BaseApp) TableInfo(tableName string) ([]*TableInfoRow, error) {
info := []*TableInfoRow{}
err := app.ConcurrentDB().NewQuery("SELECT * FROM PRAGMA_TABLE_INFO({:tableName})").
Bind(dbx.Params{"tableName": tableName}).
All(&info)
if err != nil {
return nil, err
}
// mattn/go-sqlite3 doesn't throw an error on invalid or missing table
// so we additionally have to check whether the loaded info result is nonempty
if len(info) == 0 {
return nil, fmt.Errorf("empty table info probably due to invalid or missing table %s", tableName)
}
return info, nil
}
// TableIndexes returns a name grouped map with all non empty index of the specified table.
//
// Note: This method doesn't return an error on nonexisting table.
func (app *BaseApp) TableIndexes(tableName string) (map[string]string, error) {
indexes := []struct {
Name string
Sql string
}{}
err := app.ConcurrentDB().Select("name", "sql").
From("sqlite_master").
AndWhere(dbx.NewExp("sql is not null")).
AndWhere(dbx.HashExp{
"type": "index",
"tbl_name": tableName,
}).
All(&indexes)
if err != nil {
return nil, err
}
result := make(map[string]string, len(indexes))
for _, idx := range indexes {
result[idx.Name] = idx.Sql
}
return result, nil
}
// DeleteTable drops the specified table.
//
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "tableName" argument must come only from trusted input!
func (app *BaseApp) DeleteTable(tableName string) error {
_, err := app.NonconcurrentDB().NewQuery(fmt.Sprintf(
"DROP TABLE IF EXISTS {{%s}}",
tableName,
)).Execute()
return err
}
// HasTable checks if a table (or view) with the provided name exists (case insensitive).
// in the data.db.
func (app *BaseApp) HasTable(tableName string) bool {
return app.hasTable(app.ConcurrentDB(), tableName)
}
// AuxHasTable checks if a table (or view) with the provided name exists (case insensitive)
// in the auixiliary.db.
func (app *BaseApp) AuxHasTable(tableName string) bool {
return app.hasTable(app.AuxConcurrentDB(), tableName)
}
func (app *BaseApp) hasTable(db dbx.Builder, tableName string) bool {
var exists int
err := db.Select("(1)").
From("sqlite_schema").
AndWhere(dbx.HashExp{"type": []any{"table", "view"}}).
AndWhere(dbx.NewExp("LOWER([[name]])=LOWER({:tableName})", dbx.Params{"tableName": tableName})).
Limit(1).
Row(&exists)
return err == nil && exists > 0
}
// Vacuum executes VACUUM on the data.db in order to reclaim unused data db disk space.
func (app *BaseApp) Vacuum() error {
return app.vacuum(app.NonconcurrentDB())
}
// AuxVacuum executes VACUUM on the auxiliary.db in order to reclaim unused auxiliary db disk space.
func (app *BaseApp) AuxVacuum() error {
return app.vacuum(app.AuxNonconcurrentDB())
}
func (app *BaseApp) vacuum(db dbx.Builder) error {
_, err := db.NewQuery("VACUUM").Execute()
return err
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_model_test.go | core/record_model_test.go | package core_test
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"regexp"
"slices"
"strconv"
"strings"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
)
func TestNewRecord(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
collection.Fields.Add(&core.BoolField{Name: "status"})
m := core.NewRecord(collection)
rawData, err := json.Marshal(m.FieldsData()) // should be initialized with the defaults
if err != nil {
t.Fatal(err)
}
expected := `{"id":"","status":false}`
if str := string(rawData); str != expected {
t.Fatalf("Expected schema data\n%v\ngot\n%v", expected, str)
}
}
func TestRecordCollection(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
m := core.NewRecord(collection)
if m.Collection().Name != collection.Name {
t.Fatalf("Expected collection with name %q, got %q", collection.Name, m.Collection().Name)
}
}
func TestRecordTableName(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
m := core.NewRecord(collection)
if m.TableName() != collection.Name {
t.Fatalf("Expected table %q, got %q", collection.Name, m.TableName())
}
}
func TestRecordPostScan(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(&core.TextField{Name: "test"})
m := core.NewRecord(collection)
// calling PostScan without id
err := m.PostScan()
if err == nil {
t.Fatal("Expected PostScan id error, got nil")
}
m.Id = "test_id"
m.Set("test", "abc")
if v := m.IsNew(); v != true {
t.Fatalf("[before PostScan] Expected IsNew %v, got %v", true, v)
}
if v := m.Original().PK(); v != "" {
t.Fatalf("[before PostScan] Expected the original PK to be empty string, got %v", v)
}
if v := m.Original().Get("test"); v != "" {
t.Fatalf("[before PostScan] Expected the original 'test' field to be empty string, got %v", v)
}
err = m.PostScan()
if err != nil {
t.Fatalf("Expected PostScan nil error, got %v", err)
}
if v := m.IsNew(); v != false {
t.Fatalf("[after PostScan] Expected IsNew %v, got %v", false, v)
}
if v := m.Original().PK(); v != "test_id" {
t.Fatalf("[after PostScan] Expected the original PK to be %q, got %v", "test_id", v)
}
if v := m.Original().Get("test"); v != "abc" {
t.Fatalf("[after PostScan] Expected the original 'test' field to be %q, got %v", "abc", v)
}
}
func TestRecordHookTags(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
m := core.NewRecord(collection)
tags := m.HookTags()
expectedTags := []string{collection.Id, collection.Name}
if len(tags) != len(expectedTags) {
t.Fatalf("Expected tags\n%v\ngot\n%v", expectedTags, tags)
}
for _, tag := range tags {
if !slices.Contains(expectedTags, tag) {
t.Errorf("Missing expected tag %q", tag)
}
}
}
func TestRecordBaseFilesPath(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
m := core.NewRecord(collection)
m.Id = "abc"
result := m.BaseFilesPath()
expected := collection.BaseFilesPath() + "/" + m.Id
if result != expected {
t.Fatalf("Expected %q, got %q", expected, result)
}
}
func TestRecordOriginal(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
record, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
originalId := record.Id
originalName := record.GetString("name")
extraFieldsCheck := []string{`"email":`, `"custom":`}
// change the fields
record.Id = "changed"
record.Set("name", "name_new")
record.Set("custom", "test_custom")
record.SetExpand(map[string]any{"test": 123})
record.IgnoreEmailVisibility(true)
record.IgnoreUnchangedFields(true)
record.WithCustomData(true)
record.Unhide(record.Collection().Fields.FieldNames()...)
// ensure that the email visibility and the custom data toggles are active
raw, err := record.MarshalJSON()
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
for _, f := range extraFieldsCheck {
if !strings.Contains(rawStr, f) {
t.Fatalf("Expected %s in\n%s", f, rawStr)
}
}
// check changes
if v := record.GetString("name"); v != "name_new" {
t.Fatalf("Expected name to be %q, got %q", "name_new", v)
}
if v := record.GetString("custom"); v != "test_custom" {
t.Fatalf("Expected custom to be %q, got %q", "test_custom", v)
}
// check original
if v := record.Original().PK(); v != originalId {
t.Fatalf("Expected the original PK to be %q, got %q", originalId, v)
}
if v := record.Original().Id; v != originalId {
t.Fatalf("Expected the original id to be %q, got %q", originalId, v)
}
if v := record.Original().GetString("name"); v != originalName {
t.Fatalf("Expected the original name to be %q, got %q", originalName, v)
}
if v := record.Original().GetString("custom"); v != "" {
t.Fatalf("Expected the original custom to be %q, got %q", "", v)
}
if v := record.Original().Expand(); len(v) != 0 {
t.Fatalf("Expected empty original expand, got\n%v", v)
}
// ensure that the email visibility and the custom flag toggles weren't copied
originalRaw, err := record.Original().MarshalJSON()
if err != nil {
t.Fatal(err)
}
originalRawStr := string(originalRaw)
for _, f := range extraFieldsCheck {
if strings.Contains(originalRawStr, f) {
t.Fatalf("Didn't expected %s in original\n%s", f, originalRawStr)
}
}
// loading new data shouldn't affect the original state
record.Load(map[string]any{"name": "name_new2"})
if v := record.GetString("name"); v != "name_new2" {
t.Fatalf("Expected name to be %q, got %q", "name_new2", v)
}
if v := record.Original().GetString("name"); v != originalName {
t.Fatalf("Expected the original name still to be %q, got %q", originalName, v)
}
}
func TestRecordFresh(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
record, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
originalId := record.Id
extraFieldsCheck := []string{`"email":`, `"custom":`}
autodateTest := types.NowDateTime()
// change the fields
record.Id = "changed"
record.Set("name", "name_new")
record.Set("custom", "test_custom")
record.SetRaw("created", autodateTest)
record.SetExpand(map[string]any{"test": 123})
record.IgnoreEmailVisibility(true)
record.IgnoreUnchangedFields(true)
record.WithCustomData(true)
record.Unhide(record.Collection().Fields.FieldNames()...)
// ensure that the email visibility and the custom data toggles are active
raw, err := record.MarshalJSON()
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
for _, f := range extraFieldsCheck {
if !strings.Contains(rawStr, f) {
t.Fatalf("Expected %s in\n%s", f, rawStr)
}
}
// check changes
if v := record.GetString("name"); v != "name_new" {
t.Fatalf("Expected name to be %q, got %q", "name_new", v)
}
if v := record.GetDateTime("created").String(); v != autodateTest.String() {
t.Fatalf("Expected created to be %q, got %q", autodateTest.String(), v)
}
if v := record.GetString("custom"); v != "test_custom" {
t.Fatalf("Expected custom to be %q, got %q", "test_custom", v)
}
// check fresh
if v := record.Fresh().LastSavedPK(); v != originalId {
t.Fatalf("Expected the fresh LastSavedPK to be %q, got %q", originalId, v)
}
if v := record.Fresh().PK(); v != record.Id {
t.Fatalf("Expected the fresh PK to be %q, got %q", record.Id, v)
}
if v := record.Fresh().Id; v != record.Id {
t.Fatalf("Expected the fresh id to be %q, got %q", record.Id, v)
}
if v := record.Fresh().GetString("name"); v != record.GetString("name") {
t.Fatalf("Expected the fresh name to be %q, got %q", record.GetString("name"), v)
}
if v := record.Fresh().GetDateTime("created").String(); v != autodateTest.String() {
t.Fatalf("Expected the fresh created to be %q, got %q", autodateTest.String(), v)
}
if v := record.Fresh().GetDateTime("updated").String(); v != record.GetDateTime("updated").String() {
t.Fatalf("Expected the fresh updated to be %q, got %q", record.GetDateTime("updated").String(), v)
}
if v := record.Fresh().GetString("custom"); v != "" {
t.Fatalf("Expected the fresh custom to be %q, got %q", "", v)
}
if v := record.Fresh().Expand(); len(v) != 0 {
t.Fatalf("Expected empty fresh expand, got\n%v", v)
}
// ensure that the email visibility and the custom flag toggles weren't copied
freshRaw, err := record.Fresh().MarshalJSON()
if err != nil {
t.Fatal(err)
}
freshRawStr := string(freshRaw)
for _, f := range extraFieldsCheck {
if strings.Contains(freshRawStr, f) {
t.Fatalf("Didn't expected %s in fresh\n%s", f, freshRawStr)
}
}
}
func TestRecordClone(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
record, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
originalId := record.Id
extraFieldsCheck := []string{`"email":`, `"custom":`}
autodateTest := types.NowDateTime()
// change the fields
record.Id = "changed"
record.Set("name", "name_new")
record.Set("custom", "test_custom")
record.SetRaw("created", autodateTest)
record.SetExpand(map[string]any{"test": 123})
record.IgnoreEmailVisibility(true)
record.WithCustomData(true)
record.Unhide(record.Collection().Fields.FieldNames()...)
// ensure that the email visibility and the custom data toggles are active
raw, err := record.MarshalJSON()
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
for _, f := range extraFieldsCheck {
if !strings.Contains(rawStr, f) {
t.Fatalf("Expected %s in\n%s", f, rawStr)
}
}
// check changes
if v := record.GetString("name"); v != "name_new" {
t.Fatalf("Expected name to be %q, got %q", "name_new", v)
}
if v := record.GetDateTime("created").String(); v != autodateTest.String() {
t.Fatalf("Expected created to be %q, got %q", autodateTest.String(), v)
}
if v := record.GetString("custom"); v != "test_custom" {
t.Fatalf("Expected custom to be %q, got %q", "test_custom", v)
}
// check clone
if v := record.Clone().LastSavedPK(); v != originalId {
t.Fatalf("Expected the clone LastSavedPK to be %q, got %q", originalId, v)
}
if v := record.Clone().PK(); v != record.Id {
t.Fatalf("Expected the clone PK to be %q, got %q", record.Id, v)
}
if v := record.Clone().Id; v != record.Id {
t.Fatalf("Expected the clone id to be %q, got %q", record.Id, v)
}
if v := record.Clone().GetString("name"); v != record.GetString("name") {
t.Fatalf("Expected the clone name to be %q, got %q", record.GetString("name"), v)
}
if v := record.Clone().GetDateTime("created").String(); v != autodateTest.String() {
t.Fatalf("Expected the clone created to be %q, got %q", autodateTest.String(), v)
}
if v := record.Clone().GetDateTime("updated").String(); v != record.GetDateTime("updated").String() {
t.Fatalf("Expected the clone updated to be %q, got %q", record.GetDateTime("updated").String(), v)
}
if v := record.Clone().GetString("custom"); v != "test_custom" {
t.Fatalf("Expected the clone custom to be %q, got %q", "test_custom", v)
}
if _, ok := record.Clone().Expand()["test"]; !ok {
t.Fatalf("Expected non-empty clone expand")
}
// ensure that the email visibility and the custom data toggles state were copied
cloneRaw, err := record.Clone().MarshalJSON()
if err != nil {
t.Fatal(err)
}
cloneRawStr := string(cloneRaw)
for _, f := range extraFieldsCheck {
if !strings.Contains(cloneRawStr, f) {
t.Fatalf("Expected %s in clone\n%s", f, cloneRawStr)
}
}
}
func TestRecordExpand(t *testing.T) {
t.Parallel()
record := core.NewRecord(core.NewBaseCollection("test"))
expand := record.Expand()
if expand == nil || len(expand) != 0 {
t.Fatalf("Expected empty map expand, got %v", expand)
}
data1 := map[string]any{"a": 123, "b": 456}
data2 := map[string]any{"c": 123}
record.SetExpand(data1)
record.SetExpand(data2) // should overwrite the previous call
// modify the expand map to check for shallow copy
data2["d"] = 456
expand = record.Expand()
if len(expand) != 1 {
t.Fatalf("Expected empty map expand, got %v", expand)
}
if v := expand["c"]; v != 123 {
t.Fatalf("Expected to find expand.c %v, got %v", 123, v)
}
}
func TestRecordMergeExpand(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
collection.Id = "_pbc_123"
m := core.NewRecord(collection)
m.Id = "m"
// a
a := core.NewRecord(collection)
a.Id = "a"
a1 := core.NewRecord(collection)
a1.Id = "a1"
a2 := core.NewRecord(collection)
a2.Id = "a2"
a3 := core.NewRecord(collection)
a3.Id = "a3"
a31 := core.NewRecord(collection)
a31.Id = "a31"
a32 := core.NewRecord(collection)
a32.Id = "a32"
a.SetExpand(map[string]any{
"a1": a1,
"a23": []*core.Record{a2, a3},
})
a3.SetExpand(map[string]any{
"a31": a31,
"a32": []*core.Record{a32},
})
// b
b := core.NewRecord(collection)
b.Id = "b"
b1 := core.NewRecord(collection)
b1.Id = "b1"
b.SetExpand(map[string]any{
"b1": b1,
})
// c
c := core.NewRecord(collection)
c.Id = "c"
// load initial expand
m.SetExpand(map[string]any{
"a": a,
"b": b,
"c": []*core.Record{c},
})
// a (new)
aNew := core.NewRecord(collection)
aNew.Id = a.Id
a3New := core.NewRecord(collection)
a3New.Id = a3.Id
a32New := core.NewRecord(collection)
a32New.Id = "a32New"
a33New := core.NewRecord(collection)
a33New.Id = "a33New"
a3New.SetExpand(map[string]any{
"a32": []*core.Record{a32New},
"a33New": a33New,
})
aNew.SetExpand(map[string]any{
"a23": []*core.Record{a2, a3New},
})
// b (new)
bNew := core.NewRecord(collection)
bNew.Id = "bNew"
dNew := core.NewRecord(collection)
dNew.Id = "dNew"
// merge expands
m.MergeExpand(map[string]any{
"a": aNew,
"b": []*core.Record{bNew},
"dNew": dNew,
})
result := m.Expand()
raw, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
expected := `{"a":{"collectionId":"_pbc_123","collectionName":"test","expand":{"a1":{"collectionId":"_pbc_123","collectionName":"test","id":"a1"},"a23":[{"collectionId":"_pbc_123","collectionName":"test","id":"a2"},{"collectionId":"_pbc_123","collectionName":"test","expand":{"a31":{"collectionId":"_pbc_123","collectionName":"test","id":"a31"},"a32":[{"collectionId":"_pbc_123","collectionName":"test","id":"a32"},{"collectionId":"_pbc_123","collectionName":"test","id":"a32New"}],"a33New":{"collectionId":"_pbc_123","collectionName":"test","id":"a33New"}},"id":"a3"}]},"id":"a"},"b":[{"collectionId":"_pbc_123","collectionName":"test","expand":{"b1":{"collectionId":"_pbc_123","collectionName":"test","id":"b1"}},"id":"b"},{"collectionId":"_pbc_123","collectionName":"test","id":"bNew"}],"c":[{"collectionId":"_pbc_123","collectionName":"test","id":"c"}],"dNew":{"collectionId":"_pbc_123","collectionName":"test","id":"dNew"}}`
if expected != rawStr {
t.Fatalf("Expected \n%v, \ngot \n%v", expected, rawStr)
}
}
func TestRecordMergeExpandNilCheck(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
collection.Id = "_pbc_123"
scenarios := []struct {
name string
expand map[string]any
expected string
}{
{
"nil expand",
nil,
`{"collectionId":"_pbc_123","collectionName":"test","id":""}`,
},
{
"empty expand",
map[string]any{},
`{"collectionId":"_pbc_123","collectionName":"test","id":""}`,
},
{
"non-empty expand",
map[string]any{"test": core.NewRecord(collection)},
`{"collectionId":"_pbc_123","collectionName":"test","expand":{"test":{"collectionId":"_pbc_123","collectionName":"test","id":""}},"id":""}`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
m := core.NewRecord(collection)
m.MergeExpand(s.expand)
raw, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected \n%v, \ngot \n%v", s.expected, rawStr)
}
})
}
}
func TestRecordExpandedOne(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
main := core.NewRecord(collection)
single := core.NewRecord(collection)
single.Id = "single"
multiple1 := core.NewRecord(collection)
multiple1.Id = "multiple1"
multiple2 := core.NewRecord(collection)
multiple2.Id = "multiple2"
main.SetExpand(map[string]any{
"single": single,
"multiple": []*core.Record{multiple1, multiple2},
})
if v := main.ExpandedOne("missing"); v != nil {
t.Fatalf("Expected nil, got %v", v)
}
if v := main.ExpandedOne("single"); v == nil || v.Id != "single" {
t.Fatalf("Expected record with id %q, got %v", "single", v)
}
if v := main.ExpandedOne("multiple"); v == nil || v.Id != "multiple1" {
t.Fatalf("Expected record with id %q, got %v", "multiple1", v)
}
}
func TestRecordExpandedAll(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
main := core.NewRecord(collection)
single := core.NewRecord(collection)
single.Id = "single"
multiple1 := core.NewRecord(collection)
multiple1.Id = "multiple1"
multiple2 := core.NewRecord(collection)
multiple2.Id = "multiple2"
main.SetExpand(map[string]any{
"single": single,
"multiple": []*core.Record{multiple1, multiple2},
})
if v := main.ExpandedAll("missing"); v != nil {
t.Fatalf("Expected nil, got %v", v)
}
if v := main.ExpandedAll("single"); len(v) != 1 || v[0].Id != "single" {
t.Fatalf("Expected [single] slice, got %v", v)
}
if v := main.ExpandedAll("multiple"); len(v) != 2 || v[0].Id != "multiple1" || v[1].Id != "multiple2" {
t.Fatalf("Expected [multiple1, multiple2] slice, got %v", v)
}
}
func TestRecordFieldsData(t *testing.T) {
t.Parallel()
collection := core.NewAuthCollection("test")
collection.Fields.Add(&core.TextField{Name: "field1"})
collection.Fields.Add(&core.TextField{Name: "field2"})
m := core.NewRecord(collection)
m.Id = "test_id" // direct id assignment
m.Set("email", "test@example.com")
m.Set("password", "123") // hidden fields should be also returned
m.Set("tokenKey", "789")
m.Set("field1", 123)
m.Set("field2", 456)
m.Set("unknown", 789)
raw, err := json.Marshal(m.FieldsData())
if err != nil {
t.Fatal(err)
}
expected := `{"email":"test@example.com","emailVisibility":false,"field1":"123","field2":"456","id":"test_id","password":"123","tokenKey":"789","verified":false}`
if v := string(raw); v != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, v)
}
}
func TestRecordCustomData(t *testing.T) {
t.Parallel()
collection := core.NewAuthCollection("test")
collection.Fields.Add(&core.TextField{Name: "field1"})
collection.Fields.Add(&core.TextField{Name: "field2"})
m := core.NewRecord(collection)
m.Id = "test_id" // direct id assignment
m.Set("email", "test@example.com")
m.Set("password", "123") // hidden fields should be also returned
m.Set("tokenKey", "789")
m.Set("field1", 123)
m.Set("field2", 456)
m.Set("unknown", 789)
raw, err := json.Marshal(m.CustomData())
if err != nil {
t.Fatal(err)
}
expected := `{"unknown":789}`
if v := string(raw); v != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, v)
}
}
func TestRecordSetGet(t *testing.T) {
t.Parallel()
f1 := &mockField{}
f1.Name = "mock1"
f2 := &mockField{}
f2.Name = "mock2"
f3 := &mockField{}
f3.Name = "mock3"
collection := core.NewBaseCollection("test")
collection.Fields.Add(&core.TextField{Name: "text1"})
collection.Fields.Add(&core.TextField{Name: "text2"})
collection.Fields.Add(f1)
collection.Fields.Add(f2)
collection.Fields.Add(f3)
record := core.NewRecord(collection)
record.Set("text1", 123) // should be converted to string using the ScanValue fallback
record.SetRaw("text2", 456)
record.Set("mock1", 1) // should be converted to string using the setter
record.SetRaw("mock2", 1)
record.Set("mock3:test", "abc")
record.Set("unknown", 789)
t.Run("GetRaw", func(t *testing.T) {
expected := map[string]any{
"text1": "123",
"text2": 456,
"mock1": "1",
"mock2": 1,
"mock3": "modifier_set",
"mock3:test": nil,
"unknown": 789,
}
for k, v := range expected {
raw := record.GetRaw(k)
if raw != v {
t.Errorf("Expected %q to be %v, got %v", k, v, raw)
}
}
})
t.Run("Get", func(t *testing.T) {
expected := map[string]any{
"text1": "123",
"text2": 456,
"mock1": "1",
"mock2": 1,
"mock3": "modifier_set",
"mock3:test": "modifier_get",
"unknown": 789,
}
for k, v := range expected {
get := record.Get(k)
if get != v {
t.Errorf("Expected %q to be %v, got %v", k, v, get)
}
}
})
}
func TestRecordLoad(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
collection.Fields.Add(&core.TextField{Name: "text"})
record := core.NewRecord(collection)
record.Load(map[string]any{
"text": 123,
"custom": 456,
})
expected := map[string]any{
"text": "123",
"custom": 456,
}
for k, v := range expected {
get := record.Get(k)
if get != v {
t.Errorf("Expected %q to be %#v, got %#v", k, v, get)
}
}
}
func TestRecordGetBool(t *testing.T) {
t.Parallel()
scenarios := []struct {
value any
expected bool
}{
{nil, false},
{"", false},
{0, false},
{1, true},
{[]string{"true"}, false},
{time.Now(), false},
{"test", false},
{"false", false},
{"true", true},
{false, false},
{true, true},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
result := record.GetBool("test")
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestRecordGetString(t *testing.T) {
t.Parallel()
scenarios := []struct {
value any
expected string
}{
{nil, ""},
{"", ""},
{0, "0"},
{1.4, "1.4"},
{[]string{"true"}, ""},
{map[string]int{"test": 1}, ""},
{[]byte("abc"), "abc"},
{"test", "test"},
{false, "false"},
{true, "true"},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
result := record.GetString("test")
if result != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, result)
}
})
}
}
func TestRecordGetInt(t *testing.T) {
t.Parallel()
scenarios := []struct {
value any
expected int
}{
{nil, 0},
{"", 0},
{[]string{"true"}, 0},
{map[string]int{"test": 1}, 0},
{time.Now(), 0},
{"test", 0},
{123, 123},
{2.4, 2},
{"123", 123},
{"123.5", 123},
{false, 0},
{true, 1},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
result := record.GetInt("test")
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestRecordGetFloat(t *testing.T) {
t.Parallel()
scenarios := []struct {
value any
expected float64
}{
{nil, 0},
{"", 0},
{[]string{"true"}, 0},
{map[string]int{"test": 1}, 0},
{time.Now(), 0},
{"test", 0},
{123, 123},
{2.4, 2.4},
{"123", 123},
{"123.5", 123.5},
{false, 0},
{true, 1},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
result := record.GetFloat("test")
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestRecordGetDateTime(t *testing.T) {
t.Parallel()
nowTime := time.Now()
testTime, _ := time.Parse(types.DefaultDateLayout, "2022-01-01 08:00:40.000Z")
scenarios := []struct {
value any
expected time.Time
}{
{nil, time.Time{}},
{"", time.Time{}},
{false, time.Time{}},
{true, time.Time{}},
{"test", time.Time{}},
{[]string{"true"}, time.Time{}},
{map[string]int{"test": 1}, time.Time{}},
{1641024040, testTime},
{"2022-01-01 08:00:40.000", testTime},
{nowTime, nowTime},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
result := record.GetDateTime("test")
if !result.Time().Equal(s.expected) {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestRecordGetStringSlice(t *testing.T) {
t.Parallel()
nowTime := time.Now()
scenarios := []struct {
value any
expected []string
}{
{nil, []string{}},
{"", []string{}},
{false, []string{"false"}},
{true, []string{"true"}},
{nowTime, []string{}},
{123, []string{"123"}},
{"test", []string{"test"}},
{map[string]int{"test": 1}, []string{}},
{`["test1", "test2"]`, []string{"test1", "test2"}},
{[]int{123, 123, 456}, []string{"123", "456"}},
{[]string{"test", "test", "123"}, []string{"test", "123"}},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
result := record.GetStringSlice("test")
if len(result) != len(s.expected) {
t.Fatalf("Expected %d elements, got %d: %v", len(s.expected), len(result), result)
}
for _, v := range result {
if !slices.Contains(s.expected, v) {
t.Fatalf("Cannot find %v in %v", v, s.expected)
}
}
})
}
}
func TestRecordGetGeoPoint(t *testing.T) {
t.Parallel()
scenarios := []struct {
value any
expected string
}{
{nil, `{"lon":0,"lat":0}`},
{"", `{"lon":0,"lat":0}`},
{0, `{"lon":0,"lat":0}`},
{false, `{"lon":0,"lat":0}`},
{"{}", `{"lon":0,"lat":0}`},
{"[]", `{"lon":0,"lat":0}`},
{[]int{1, 2}, `{"lon":0,"lat":0}`},
{map[string]any{"lon": 1, "lat": 2}, `{"lon":1,"lat":2}`},
{[]byte(`{"lon":1,"lat":2}`), `{"lon":1,"lat":2}`},
{`{"lon":1,"lat":2}`, `{"lon":1,"lat":2}`},
{types.GeoPoint{Lon: 1, Lat: 2}, `{"lon":1,"lat":2}`},
{&types.GeoPoint{Lon: 1, Lat: 2}, `{"lon":1,"lat":2}`},
}
collection := core.NewBaseCollection("test")
record := core.NewRecord(collection)
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("test", s.value)
pointStr := record.GetGeoPoint("test").String()
if pointStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, pointStr)
}
})
}
}
func TestRecordGetUnsavedFiles(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
f1, err := filesystem.NewFileFromBytes([]byte("test"), "f1")
if err != nil {
t.Fatal(err)
}
f1.Name = "f1"
f2, err := filesystem.NewFileFromBytes([]byte("test"), "f2")
if err != nil {
t.Fatal(err)
}
f2.Name = "f2"
record, err := app.FindRecordById("demo3", "lcl9d87w22ml6jy")
if err != nil {
t.Fatal(err)
}
record.Set("files+", []any{f1, f2})
scenarios := []struct {
key string
expected string
}{
{
"",
"null",
},
{
"title",
"null",
},
{
"files",
`[{"name":"f1","originalName":"f1","size":4},{"name":"f2","originalName":"f2","size":4}]`,
},
{
"files:unsaved",
`[{"name":"f1","originalName":"f1","size":4},{"name":"f2","originalName":"f2","size":4}]`,
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.key), func(t *testing.T) {
v := record.GetUnsavedFiles(s.key)
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected\n%s\ngot\n%s", s.expected, rawStr)
}
})
}
}
func TestRecordUnmarshalJSONField(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
collection.Fields.Add(&core.JSONField{Name: "field"})
record := core.NewRecord(collection)
var testPointer *string
var testStr string
var testInt int
var testBool bool
var testSlice []int
var testMap map[string]any
scenarios := []struct {
value any
destination any
expectError bool
expectedJSON string
}{
{nil, testPointer, false, `null`},
{nil, testStr, false, `""`},
{"", testStr, false, `""`},
{1, testInt, false, `1`},
{true, testBool, false, `true`},
{[]int{1, 2, 3}, testSlice, false, `[1,2,3]`},
{map[string]any{"test": 123}, testMap, false, `{"test":123}`},
// json encoded values
{`null`, testPointer, false, `null`},
{`true`, testBool, false, `true`},
{`456`, testInt, false, `456`},
{`"test"`, testStr, false, `"test"`},
{`[4,5,6]`, testSlice, false, `[4,5,6]`},
{`{"test":456}`, testMap, false, `{"test":456}`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.value), func(t *testing.T) {
record.Set("field", s.value)
err := record.UnmarshalJSONField("field", &s.destination)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v", s.expectError, hasErr)
}
raw, _ := json.Marshal(s.destination)
if v := string(raw); v != s.expectedJSON {
t.Fatalf("Expected %q, got %q", s.expectedJSON, v)
}
})
}
}
func TestRecordFindFileFieldByFile(t *testing.T) {
t.Parallel()
collection := core.NewBaseCollection("test")
collection.Fields.Add(
&core.TextField{Name: "field1"},
&core.FileField{Name: "field2", MaxSelect: 1, MaxSize: 1},
&core.FileField{Name: "field3", MaxSelect: 2, MaxSize: 1},
)
m := core.NewRecord(collection)
m.Set("field1", "test")
m.Set("field2", "test.png")
m.Set("field3", []string{"test1.png", "test2.png"})
scenarios := []struct {
filename string
expectField string
}{
{"", ""},
{"test", ""},
{"test2", ""},
{"test.png", "field2"},
{"test2.png", "field3"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.filename), func(t *testing.T) {
result := m.FindFileFieldByFile(s.filename)
var fieldName string
if result != nil {
fieldName = result.Name
}
if s.expectField != fieldName {
t.Fatalf("Expected field %v, got %v", s.expectField, result)
}
})
}
}
func TestRecordDBExport(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
f1 := &core.TextField{Name: "field1"}
f2 := &core.FileField{Name: "field2", MaxSelect: 1, MaxSize: 1}
f3 := &core.SelectField{Name: "field3", MaxSelect: 2, Values: []string{"test1", "test2", "test3"}}
f4 := &core.RelationField{Name: "field4", MaxSelect: 2}
colBase := core.NewBaseCollection("test_base")
colBase.Fields.Add(f1, f2, f3, f4)
colAuth := core.NewAuthCollection("test_auth")
colAuth.Fields.Add(f1, f2, f3, f4)
scenarios := []struct {
collection *core.Collection
expected string
}{
{
colBase,
`{"field1":"test","field2":"test.png","field3":["test1","test2"],"field4":["test11","test12"],"id":"test_id"}`,
},
{
colAuth,
`{"email":"test_email","emailVisibility":true,"field1":"test","field2":"test.png","field3":["test1","test2"],"field4":["test11","test12"],"id":"test_id","password":"_TEST_","tokenKey":"test_tokenKey","verified":false}`,
},
}
data := map[string]any{
"id": "test_id",
"field1": "test",
"field2": "test.png",
"field3": []string{"test1", "test2"},
"field4": []string{"test11", "test12", "test11"}, // strip duplicate,
"unknown": "test_unknown",
"password": "test_passwordHash",
"username": "test_username",
"emailVisibility": true,
"email": "test_email",
"verified": "invalid", // should be casted
"tokenKey": "test_tokenKey",
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.collection.Type, s.collection.Name), func(t *testing.T) {
record := core.NewRecord(s.collection)
record.Load(data)
result, err := record.DBExport(app)
if err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
// replace _TEST_ placeholder with .+ regex pattern
pattern := regexp.MustCompile(strings.ReplaceAll(
"^"+regexp.QuoteMeta(s.expected)+"$",
"_TEST_",
`.+`,
))
if !pattern.MatchString(rawStr) {
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/log_query.go | core/log_query.go | package core
import (
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/types"
)
// LogQuery returns a new Log select query.
func (app *BaseApp) LogQuery() *dbx.SelectQuery {
return app.AuxModelQuery(&Log{})
}
// FindLogById finds a single Log entry by its id.
func (app *BaseApp) FindLogById(id string) (*Log, error) {
model := &Log{}
err := app.LogQuery().
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
One(model)
if err != nil {
return nil, err
}
return model, nil
}
// LogsStatsItem defines the total number of logs for a specific time period.
type LogsStatsItem struct {
Date types.DateTime `db:"date" json:"date"`
Total int `db:"total" json:"total"`
}
// LogsStats returns hourly grouped logs statistics.
func (app *BaseApp) LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error) {
result := []*LogsStatsItem{}
query := app.LogQuery().
Select("count(id) as total", "strftime('%Y-%m-%d %H:00:00', created) as date").
GroupBy("date")
if expr != nil {
query.AndWhere(expr)
}
err := query.All(&result)
return result, err
}
// DeleteOldLogs delete all logs that are created before createdBefore.
//
// For better performance the logs delete is executed as plain SQL statement,
// aka. no delete model hook events will be fired.
func (app *BaseApp) DeleteOldLogs(createdBefore time.Time) error {
formattedDate := createdBefore.UTC().Format(types.DefaultDateLayout)
expr := dbx.NewExp("[[created]] <= {:date}", dbx.Params{"date": formattedDate})
_, err := app.auxNonconcurrentDB.Delete((&Log{}).TableName(), expr).Execute()
return err
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_proxy.go | core/record_proxy.go | package core
// RecordProxy defines an interface for a Record proxy/project model,
// aka. custom model struct that acts on behalve the proxied Record to
// allow for example typed getter/setters for the Record fields.
//
// To implement the interface it is usually enough to embed the [BaseRecordProxy] struct.
type RecordProxy interface {
// ProxyRecord returns the proxied Record model.
ProxyRecord() *Record
// SetProxyRecord loads the specified record model into the current proxy.
SetProxyRecord(record *Record)
}
var _ RecordProxy = (*BaseRecordProxy)(nil)
// BaseRecordProxy implements the [RecordProxy] interface and it is intended
// to be used as embed to custom user provided Record proxy structs.
type BaseRecordProxy struct {
*Record
}
// ProxyRecord returns the proxied Record model.
func (m *BaseRecordProxy) ProxyRecord() *Record {
return m.Record
}
// SetProxyRecord loads the specified record model into the current proxy.
func (m *BaseRecordProxy) SetProxyRecord(record *Record) {
m.Record = record
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/auth_origin_model.go | core/auth_origin_model.go | package core
import (
"context"
"errors"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
)
const CollectionNameAuthOrigins = "_authOrigins"
var (
_ Model = (*AuthOrigin)(nil)
_ PreValidator = (*AuthOrigin)(nil)
_ RecordProxy = (*AuthOrigin)(nil)
)
// AuthOrigin defines a Record proxy for working with the authOrigins collection.
type AuthOrigin struct {
*Record
}
// NewAuthOrigin instantiates and returns a new blank *AuthOrigin model.
//
// Example usage:
//
// origin := core.NewOrigin(app)
// origin.SetRecordRef(user.Id)
// origin.SetCollectionRef(user.Collection().Id)
// origin.SetFingerprint("...")
// app.Save(origin)
func NewAuthOrigin(app App) *AuthOrigin {
m := &AuthOrigin{}
c, err := app.FindCachedCollectionByNameOrId(CollectionNameAuthOrigins)
if err != nil {
// this is just to make tests easier since authOrigins is a system collection and it is expected to be always accessible
// (note: the loaded record is further checked on AuthOrigin.PreValidate())
c = NewBaseCollection("@___invalid___")
}
m.Record = NewRecord(c)
return m
}
// PreValidate implements the [PreValidator] interface and checks
// whether the proxy is properly loaded.
func (m *AuthOrigin) PreValidate(ctx context.Context, app App) error {
if m.Record == nil || m.Record.Collection().Name != CollectionNameAuthOrigins {
return errors.New("missing or invalid AuthOrigin ProxyRecord")
}
return nil
}
// ProxyRecord returns the proxied Record model.
func (m *AuthOrigin) ProxyRecord() *Record {
return m.Record
}
// SetProxyRecord loads the specified record model into the current proxy.
func (m *AuthOrigin) SetProxyRecord(record *Record) {
m.Record = record
}
// CollectionRef returns the "collectionRef" field value.
func (m *AuthOrigin) CollectionRef() string {
return m.GetString("collectionRef")
}
// SetCollectionRef updates the "collectionRef" record field value.
func (m *AuthOrigin) SetCollectionRef(collectionId string) {
m.Set("collectionRef", collectionId)
}
// RecordRef returns the "recordRef" record field value.
func (m *AuthOrigin) RecordRef() string {
return m.GetString("recordRef")
}
// SetRecordRef updates the "recordRef" record field value.
func (m *AuthOrigin) SetRecordRef(recordId string) {
m.Set("recordRef", recordId)
}
// Fingerprint returns the "fingerprint" record field value.
func (m *AuthOrigin) Fingerprint() string {
return m.GetString("fingerprint")
}
// SetFingerprint updates the "fingerprint" record field value.
func (m *AuthOrigin) SetFingerprint(fingerprint string) {
m.Set("fingerprint", fingerprint)
}
// Created returns the "created" record field value.
func (m *AuthOrigin) Created() types.DateTime {
return m.GetDateTime("created")
}
// Updated returns the "updated" record field value.
func (m *AuthOrigin) Updated() types.DateTime {
return m.GetDateTime("updated")
}
func (app *BaseApp) registerAuthOriginHooks() {
recordRefHooks[*AuthOrigin](app, CollectionNameAuthOrigins, CollectionTypeAuth)
// delete existing auth origins on password change
app.OnRecordUpdate().Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
err := e.Next()
if err != nil || !e.Record.Collection().IsAuth() {
return err
}
old := e.Record.Original().GetString(FieldNamePassword + ":hash")
new := e.Record.GetString(FieldNamePassword + ":hash")
if old != new {
err = e.App.DeleteAllAuthOriginsByRecord(e.Record)
if err != nil {
e.App.Logger().Warn(
"Failed to delete all previous auth origin fingerprints",
"error", err,
"recordId", e.Record.Id,
"collectionId", e.Record.Collection().Id,
)
}
}
return nil
},
Priority: 99,
})
}
// -------------------------------------------------------------------
// recordRefHooks registers common hooks that are usually used with record proxies
// that have polymorphic record relations (aka. "collectionRef" and "recordRef" fields).
func recordRefHooks[T RecordProxy](app App, collectionName string, optCollectionTypes ...string) {
app.OnRecordValidate(collectionName).Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
collectionId := e.Record.GetString("collectionRef")
err := validation.Validate(collectionId, validation.Required, validation.By(validateCollectionId(e.App, optCollectionTypes...)))
if err != nil {
return validation.Errors{"collectionRef": err}
}
recordId := e.Record.GetString("recordRef")
err = validation.Validate(recordId, validation.Required, validation.By(validateRecordId(e.App, collectionId)))
if err != nil {
return validation.Errors{"recordRef": err}
}
return e.Next()
},
Priority: 99,
})
// delete on collection ref delete
app.OnCollectionDeleteExecute().Bind(&hook.Handler[*CollectionEvent]{
Func: func(e *CollectionEvent) error {
if e.Collection.Name == collectionName || (len(optCollectionTypes) > 0 && !slices.Contains(optCollectionTypes, e.Collection.Type)) {
return e.Next()
}
originalApp := e.App
txErr := e.App.RunInTransaction(func(txApp App) error {
e.App = txApp
if err := e.Next(); err != nil {
return err
}
rels, err := txApp.FindAllRecords(collectionName, dbx.HashExp{"collectionRef": e.Collection.Id})
if err != nil {
return err
}
for _, mfa := range rels {
if err := txApp.Delete(mfa); err != nil {
return err
}
}
return nil
})
e.App = originalApp
return txErr
},
Priority: 99,
})
// delete on record ref delete
app.OnRecordDeleteExecute().Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
if e.Record.Collection().Name == collectionName ||
(len(optCollectionTypes) > 0 && !slices.Contains(optCollectionTypes, e.Record.Collection().Type)) {
return e.Next()
}
originalApp := e.App
txErr := e.App.RunInTransaction(func(txApp App) error {
e.App = txApp
if err := e.Next(); err != nil {
return err
}
rels, err := txApp.FindAllRecords(collectionName, dbx.HashExp{
"collectionRef": e.Record.Collection().Id,
"recordRef": e.Record.Id,
})
if err != nil {
return err
}
for _, rel := range rels {
if err := txApp.Delete(rel); err != nil {
return err
}
}
return nil
})
e.App = originalApp
return txErr
},
Priority: 99,
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_model_test.go | core/db_model_test.go | package core_test
import (
"testing"
"github.com/pocketbase/pocketbase/core"
)
func TestBaseModel(t *testing.T) {
id := "test_id"
m := core.BaseModel{Id: id}
if m.PK() != id {
t.Fatalf("[before PostScan] Expected PK %q, got %q", "", m.PK())
}
if m.LastSavedPK() != "" {
t.Fatalf("[before PostScan] Expected LastSavedPK %q, got %q", "", m.LastSavedPK())
}
if !m.IsNew() {
t.Fatalf("[before PostScan] Expected IsNew %v, got %v", true, m.IsNew())
}
if err := m.PostScan(); err != nil {
t.Fatal(err)
}
if m.PK() != id {
t.Fatalf("[after PostScan] Expected PK %q, got %q", "", m.PK())
}
if m.LastSavedPK() != id {
t.Fatalf("[after PostScan] Expected LastSavedPK %q, got %q", id, m.LastSavedPK())
}
if m.IsNew() {
t.Fatalf("[after PostScan] Expected IsNew %v, got %v", false, m.IsNew())
}
m.MarkAsNew()
if m.PK() != id {
t.Fatalf("[after MarkAsNew] Expected PK %q, got %q", id, m.PK())
}
if m.LastSavedPK() != "" {
t.Fatalf("[after MarkAsNew] Expected LastSavedPK %q, got %q", "", m.LastSavedPK())
}
if !m.IsNew() {
t.Fatalf("[after MarkAsNew] Expected IsNew %v, got %v", true, m.IsNew())
}
// mark as not new without id
m.MarkAsNotNew()
if m.PK() != id {
t.Fatalf("[after MarkAsNotNew] Expected PK %q, got %q", id, m.PK())
}
if m.LastSavedPK() != id {
t.Fatalf("[after MarkAsNotNew] Expected LastSavedPK %q, got %q", id, m.LastSavedPK())
}
if m.IsNew() {
t.Fatalf("[after MarkAsNotNew] Expected IsNew %v, got %v", false, m.IsNew())
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_model_superusers.go | core/record_model_superusers.go | package core
import (
"database/sql"
"errors"
"fmt"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/router"
)
const CollectionNameSuperusers = "_superusers"
// DefaultInstallerEmail is the default superuser email address
// for the initial autogenerated superuser account.
const DefaultInstallerEmail = "__pbinstaller@example.com"
func (app *BaseApp) registerSuperuserHooks() {
app.OnRecordDelete(CollectionNameSuperusers).Bind(&hook.Handler[*RecordEvent]{
Id: "pbSuperusersRecordDelete",
Func: func(e *RecordEvent) error {
originalApp := e.App
txErr := e.App.RunInTransaction(func(txApp App) error {
e.App = txApp
total, err := e.App.CountRecords(CollectionNameSuperusers)
if err != nil {
return fmt.Errorf("failed to fetch total superusers count: %w", err)
}
if total == 1 {
return router.NewBadRequestError("You can't delete the only existing superuser", nil)
}
return e.Next()
})
e.App = originalApp
return txErr
},
Priority: -99,
})
recordSaveHandler := &hook.Handler[*RecordEvent]{
Id: "pbSuperusersRecordSaveExec",
Func: func(e *RecordEvent) error {
e.Record.SetVerified(true) // always mark superusers as verified
if err := e.Next(); err != nil {
return err
}
// ensure that the installer superuser is deleted
if e.Type == ModelEventTypeCreate && e.Record.Email() != DefaultInstallerEmail {
record, err := app.FindAuthRecordByEmail(CollectionNameSuperusers, DefaultInstallerEmail)
if errors.Is(err, sql.ErrNoRows) {
// already deleted
} else if err != nil {
e.App.Logger().Warn("Failed to fetch installer superuser", "error", err)
} else {
err = e.App.Delete(record)
if err != nil {
e.App.Logger().Warn("Failed to delete installer superuser", "error", err)
}
}
}
return nil
},
Priority: -99,
}
app.OnRecordCreateExecute(CollectionNameSuperusers).Bind(recordSaveHandler)
app.OnRecordUpdateExecute(CollectionNameSuperusers).Bind(recordSaveHandler)
// prevent sending password reset emails to the installer address
app.OnMailerRecordPasswordResetSend(CollectionNameSuperusers).Bind(&hook.Handler[*MailerRecordEvent]{
Id: "pbSuperusersInstallerPasswordReset",
Func: func(e *MailerRecordEvent) error {
if e.Record.Email() == DefaultInstallerEmail {
return errors.New("cannot reset the password for the installer superuser")
}
return e.Next()
},
})
collectionSaveHandler := &hook.Handler[*CollectionEvent]{
Id: "pbSuperusersCollectionSaveExec",
Func: func(e *CollectionEvent) error {
// don't allow name change even if executed with SaveNoValidate
e.Collection.Name = CollectionNameSuperusers
// for now don't allow superusers OAuth2 since we don't want
// to accidentally create a new superuser by just OAuth2 signin
e.Collection.OAuth2.Enabled = false
e.Collection.OAuth2.Providers = nil
// force password auth
e.Collection.PasswordAuth.Enabled = true
// for superusers we don't allow for now standalone OTP auth and always require to be combined with MFA
if e.Collection.OTP.Enabled {
e.Collection.MFA.Enabled = true
}
return e.Next()
},
Priority: 99,
}
app.OnCollectionCreateExecute(CollectionNameSuperusers).Bind(collectionSaveHandler)
app.OnCollectionUpdateExecute(CollectionNameSuperusers).Bind(collectionSaveHandler)
}
// IsSuperuser returns whether the current record is a superuser, aka.
// whether the record is from the _superusers collection.
func (m *Record) IsSuperuser() bool {
return m.Collection().Name == CollectionNameSuperusers
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_tokens.go | core/record_tokens.go | package core
import (
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/pocketbase/tools/security"
)
// Supported record token types
const (
TokenTypeAuth = "auth"
TokenTypeFile = "file"
TokenTypeVerification = "verification"
TokenTypePasswordReset = "passwordReset"
TokenTypeEmailChange = "emailChange"
)
// List with commonly used record token claims
const (
TokenClaimId = "id"
TokenClaimType = "type"
TokenClaimCollectionId = "collectionId"
TokenClaimEmail = "email"
TokenClaimNewEmail = "newEmail"
TokenClaimRefreshable = "refreshable"
)
// Common token related errors
var (
ErrNotAuthRecord = errors.New("not an auth collection record")
ErrMissingSigningKey = errors.New("missing or invalid signing key")
)
// NewStaticAuthToken generates and returns a new static record authentication token.
//
// Static auth tokens are similar to the regular auth tokens, but are
// non-refreshable and support custom duration.
//
// Zero or negative duration will fallback to the duration from the auth collection settings.
func (m *Record) NewStaticAuthToken(duration time.Duration) (string, error) {
return m.newAuthToken(duration, false)
}
// NewAuthToken generates and returns a new record authentication token.
func (m *Record) NewAuthToken() (string, error) {
return m.newAuthToken(0, true)
}
func (m *Record) newAuthToken(duration time.Duration, refreshable bool) (string, error) {
if !m.Collection().IsAuth() {
return "", ErrNotAuthRecord
}
key := (m.TokenKey() + m.Collection().AuthToken.Secret)
if key == "" {
return "", ErrMissingSigningKey
}
claims := jwt.MapClaims{
TokenClaimType: TokenTypeAuth,
TokenClaimId: m.Id,
TokenClaimCollectionId: m.Collection().Id,
TokenClaimRefreshable: refreshable,
}
if duration <= 0 {
duration = m.Collection().AuthToken.DurationTime()
}
return security.NewJWT(claims, key, duration)
}
// NewVerificationToken generates and returns a new record verification token.
func (m *Record) NewVerificationToken() (string, error) {
if !m.Collection().IsAuth() {
return "", ErrNotAuthRecord
}
key := (m.TokenKey() + m.Collection().VerificationToken.Secret)
if key == "" {
return "", ErrMissingSigningKey
}
return security.NewJWT(
jwt.MapClaims{
TokenClaimType: TokenTypeVerification,
TokenClaimId: m.Id,
TokenClaimCollectionId: m.Collection().Id,
TokenClaimEmail: m.Email(),
},
key,
m.Collection().VerificationToken.DurationTime(),
)
}
// NewPasswordResetToken generates and returns a new auth record password reset request token.
func (m *Record) NewPasswordResetToken() (string, error) {
if !m.Collection().IsAuth() {
return "", ErrNotAuthRecord
}
key := (m.TokenKey() + m.Collection().PasswordResetToken.Secret)
if key == "" {
return "", ErrMissingSigningKey
}
return security.NewJWT(
jwt.MapClaims{
TokenClaimType: TokenTypePasswordReset,
TokenClaimId: m.Id,
TokenClaimCollectionId: m.Collection().Id,
TokenClaimEmail: m.Email(),
},
key,
m.Collection().PasswordResetToken.DurationTime(),
)
}
// NewEmailChangeToken generates and returns a new auth record change email request token.
func (m *Record) NewEmailChangeToken(newEmail string) (string, error) {
if !m.Collection().IsAuth() {
return "", ErrNotAuthRecord
}
key := (m.TokenKey() + m.Collection().EmailChangeToken.Secret)
if key == "" {
return "", ErrMissingSigningKey
}
return security.NewJWT(
jwt.MapClaims{
TokenClaimType: TokenTypeEmailChange,
TokenClaimId: m.Id,
TokenClaimCollectionId: m.Collection().Id,
TokenClaimEmail: m.Email(),
TokenClaimNewEmail: newEmail,
},
key,
m.Collection().EmailChangeToken.DurationTime(),
)
}
// NewFileToken generates and returns a new record private file access token.
func (m *Record) NewFileToken() (string, error) {
if !m.Collection().IsAuth() {
return "", ErrNotAuthRecord
}
key := (m.TokenKey() + m.Collection().FileToken.Secret)
if key == "" {
return "", ErrMissingSigningKey
}
return security.NewJWT(
jwt.MapClaims{
TokenClaimType: TokenTypeFile,
TokenClaimId: m.Id,
TokenClaimCollectionId: m.Collection().Id,
},
key,
m.Collection().FileToken.DurationTime(),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/view.go | core/view.go | package core
import (
"errors"
"fmt"
"io"
"regexp"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/tokenizer"
)
// DeleteView drops the specified view name.
//
// This method is a no-op if a view with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "name" argument must come only from trusted input!
func (app *BaseApp) DeleteView(name string) error {
_, err := app.DB().NewQuery(fmt.Sprintf(
"DROP VIEW IF EXISTS {{%s}}",
name,
)).Execute()
return err
}
// SaveView creates (or updates already existing) persistent SQL view.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "selectQuery" argument must come only from trusted input!
func (app *BaseApp) SaveView(name string, selectQuery string) error {
return app.RunInTransaction(func(txApp App) error {
// delete old view (if exists)
if err := txApp.DeleteView(name); err != nil {
return err
}
selectQuery = strings.Trim(strings.TrimSpace(selectQuery), ";")
// try to loosely detect multiple inline statements
tk := tokenizer.NewFromString(selectQuery)
tk.Separators(';')
if queryParts, _ := tk.ScanAll(); len(queryParts) > 1 {
return errors.New("multiple statements are not supported")
}
// (re)create the view
//
// note: the query is wrapped in a secondary SELECT as a rudimentary
// measure to discourage multiple inline sql statements execution
viewQuery := fmt.Sprintf("CREATE VIEW {{%s}} AS SELECT * FROM (%s)", name, selectQuery)
if _, err := txApp.DB().NewQuery(viewQuery).Execute(); err != nil {
return err
}
// fetch the view table info to ensure that the view was created
// because missing tables or columns won't return an error
if _, err := txApp.TableInfo(name); err != nil {
// manually cleanup previously created view in case the func
// is called in a nested transaction and the error is discarded
txApp.DeleteView(name)
return err
}
return nil
})
}
// CreateViewFields creates a new FieldsList from the provided select query.
//
// There are some caveats:
// - The select query must have an "id" column.
// - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
func (app *BaseApp) CreateViewFields(selectQuery string) (FieldsList, error) {
result := NewFieldsList()
suggestedFields, err := parseQueryToFields(app, selectQuery)
if err != nil {
return result, err
}
// note wrap in a transaction in case the selectQuery contains
// multiple statements allowing us to rollback on any error
txErr := app.RunInTransaction(func(txApp App) error {
info, err := getQueryTableInfo(txApp, selectQuery)
if err != nil {
return err
}
var hasId bool
for _, row := range info {
if row.Name == FieldNameId {
hasId = true
}
var field Field
if f, ok := suggestedFields[row.Name]; ok {
field = f.field
} else {
field = defaultViewField(row.Name)
}
result.Add(field)
}
if !hasId {
return errors.New("missing required id column (you can use `(ROW_NUMBER() OVER()) as id` if you don't have one)")
}
return nil
})
return result, txErr
}
// FindRecordByViewFile returns the original Record of the provided view collection file.
func (app *BaseApp) FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error) {
view, err := getCollectionByModelOrIdentifier(app, viewCollectionModelOrIdentifier)
if err != nil {
return nil, err
}
if !view.IsView() {
return nil, errors.New("not a view collection")
}
var findFirstNonViewQueryFileField func(int) (*queryField, error)
findFirstNonViewQueryFileField = func(level int) (*queryField, error) {
// check the level depth to prevent infinite circular recursion
// (the limit is arbitrary and may change in the future)
if level > 5 {
return nil, errors.New("reached the max recursion level of view collection file field queries")
}
queryFields, err := parseQueryToFields(app, view.ViewQuery)
if err != nil {
return nil, err
}
for _, item := range queryFields {
if item.collection == nil ||
item.original == nil ||
item.field.GetName() != fileFieldName {
continue
}
if item.collection.IsView() {
view = item.collection
fileFieldName = item.original.GetName()
return findFirstNonViewQueryFileField(level + 1)
}
return item, nil
}
return nil, errors.New("no query file field found")
}
qf, err := findFirstNonViewQueryFileField(1)
if err != nil {
return nil, err
}
cleanFieldName := inflector.Columnify(qf.original.GetName())
record := &Record{}
query := app.RecordQuery(qf.collection).Limit(1)
if opt, ok := qf.original.(MultiValuer); !ok || !opt.IsMultiple() {
query.AndWhere(dbx.HashExp{cleanFieldName: filename})
} else {
query.InnerJoin(
fmt.Sprintf(`%s as {{_je_file}}`, dbutils.JSONEach(cleanFieldName)),
dbx.HashExp{"_je_file.value": filename},
)
}
if err := query.One(record); err != nil {
return nil, err
}
return record, nil
}
// -------------------------------------------------------------------
// Raw query to schema helpers
// -------------------------------------------------------------------
type queryField struct {
// field is the final resolved field.
field Field
// collection refers to the original field's collection model.
// It could be nil if the found query field is not from a collection
collection *Collection
// original is the original found collection field.
// It could be nil if the found query field is not from a collection
original Field
}
func defaultViewField(name string) Field {
return &JSONField{
Name: name,
MaxSize: 1, // unused for views
}
}
var castRegex = regexp.MustCompile(`(?is)^cast\s*\(.*\s+as\s+(\w+)\s*\)$`)
func parseQueryToFields(app App, selectQuery string) (map[string]*queryField, error) {
p := new(identifiersParser)
if err := p.parse(selectQuery); err != nil {
return nil, err
}
collections, err := findCollectionsByIdentifiers(app, p.tables)
if err != nil {
return nil, err
}
result := make(map[string]*queryField, len(p.columns))
var mainTable identifier
if len(p.tables) > 0 {
mainTable = p.tables[0]
}
for _, col := range p.columns {
colLower := strings.ToLower(col.original)
// pk (always assume text field for now)
if col.alias == FieldNameId {
result[col.alias] = &queryField{
field: &TextField{
Name: col.alias,
System: true,
Required: true,
PrimaryKey: true,
Pattern: `^[a-z0-9]+$`,
},
}
continue
}
// numeric aggregations
if strings.HasPrefix(colLower, "count(") || strings.HasPrefix(colLower, "total(") {
result[col.alias] = &queryField{
field: &NumberField{
Name: col.alias,
},
}
continue
}
castMatch := castRegex.FindStringSubmatch(colLower)
// numeric casts
if len(castMatch) == 2 {
switch castMatch[1] {
case "real", "integer", "int", "decimal", "numeric":
result[col.alias] = &queryField{
field: &NumberField{
Name: col.alias,
},
}
continue
case "text":
result[col.alias] = &queryField{
field: &TextField{
Name: col.alias,
},
}
continue
case "boolean", "bool":
result[col.alias] = &queryField{
field: &BoolField{
Name: col.alias,
},
}
continue
}
}
parts := strings.Split(col.original, ".")
var fieldName string
var collection *Collection
if len(parts) == 2 {
fieldName = parts[1]
collection = collections[parts[0]]
} else {
fieldName = parts[0]
collection = collections[mainTable.alias]
}
// fallback to the default field
if collection == nil {
result[col.alias] = &queryField{
field: defaultViewField(col.alias),
}
continue
}
if fieldName == "*" {
return nil, errors.New("dynamic column names are not supported")
}
// find the first field by name (case insensitive)
var field Field
for _, f := range collection.Fields {
if strings.EqualFold(f.GetName(), fieldName) {
field = f
break
}
}
// fallback to the default field
if field == nil {
result[col.alias] = &queryField{
field: defaultViewField(col.alias),
collection: collection,
}
continue
}
// convert to relation since it is an id reference
if strings.EqualFold(fieldName, FieldNameId) {
result[col.alias] = &queryField{
field: &RelationField{
Name: col.alias,
MaxSelect: 1,
CollectionId: collection.Id,
},
collection: collection,
}
continue
}
// we fetch a brand new collection object to avoid using reflection
// or having a dedicated Clone method for each field type
tempCollection, err := app.FindCollectionByNameOrId(collection.Id)
if err != nil {
return nil, err
}
clone := tempCollection.Fields.GetById(field.GetId())
if clone == nil {
return nil, fmt.Errorf("missing expected field %q (%q) in collection %q", field.GetName(), field.GetId(), tempCollection.Name)
}
// set new random id to prevent duplications if the same field is aliased multiple times
clone.SetId("_clone_" + security.PseudorandomString(4))
clone.SetName(col.alias)
result[col.alias] = &queryField{
original: field,
field: clone,
collection: collection,
}
}
return result, nil
}
func findCollectionsByIdentifiers(app App, tables []identifier) (map[string]*Collection, error) {
names := make([]any, 0, len(tables))
for _, table := range tables {
if strings.Contains(table.alias, "(") {
continue // skip expressions
}
names = append(names, table.original)
}
if len(names) == 0 {
return nil, nil
}
result := make(map[string]*Collection, len(names))
collections := make([]*Collection, 0, len(names))
err := app.CollectionQuery().
AndWhere(dbx.In("name", names...)).
All(&collections)
if err != nil {
return nil, err
}
for _, table := range tables {
for _, collection := range collections {
if collection.Name == table.original {
result[table.alias] = collection
}
}
}
return result, nil
}
func getQueryTableInfo(app App, selectQuery string) ([]*TableInfoRow, error) {
tempView := "_temp_" + security.PseudorandomString(6)
var info []*TableInfoRow
txErr := app.RunInTransaction(func(txApp App) error {
// create a temp view with the provided query
err := txApp.SaveView(tempView, selectQuery)
if err != nil {
return err
}
// extract the generated view table info
info, err = txApp.TableInfo(tempView)
return errors.Join(err, txApp.DeleteView(tempView))
})
if txErr != nil {
return nil, txErr
}
return info, nil
}
// -------------------------------------------------------------------
// Raw query identifiers parser
// -------------------------------------------------------------------
var (
joinReplaceRegex = regexp.MustCompile(`(?im)\s+(full\s+outer\s+join|left\s+outer\s+join|right\s+outer\s+join|full\s+join|cross\s+join|inner\s+join|outer\s+join|left\s+join|right\s+join|join)\s+?`)
discardReplaceRegex = regexp.MustCompile(`(?im)\s+(where|group\s+by|having|order|limit|with)\s+?`)
commentsReplaceRegex = regexp.MustCompile(`(?m)(\/\*[\s\S]*?\*\/)|(--.+$)`)
)
type identifier struct {
original string
alias string
}
type identifiersParser struct {
columns []identifier
tables []identifier
}
func (p *identifiersParser) parse(selectQuery string) error {
str := strings.Trim(strings.TrimSpace(selectQuery), ";")
str = commentsReplaceRegex.ReplaceAllString(str, " ")
str = joinReplaceRegex.ReplaceAllString(str, " __pb_join__ ")
str = discardReplaceRegex.ReplaceAllString(str, " __pb_discard__ ")
tk := tokenizer.NewFromString(str)
tk.Separators(',', ' ', '\n', '\t')
tk.KeepSeparator(true)
var skip bool
var partType string
var activeBuilder *strings.Builder
var selectParts strings.Builder
var fromParts strings.Builder
var joinParts strings.Builder
for {
token, err := tk.Scan()
if err != nil {
if err != io.EOF {
return err
}
break
}
trimmed := strings.ToLower(strings.TrimSpace(token))
switch trimmed {
case "select":
skip = false
partType = "select"
activeBuilder = &selectParts
case "distinct":
continue // ignore as it is not important for the identifiers parsing
case "from":
skip = false
partType = "from"
activeBuilder = &fromParts
case "__pb_join__":
skip = false
// the previous part was also a join
if partType == "join" {
joinParts.WriteString(",")
}
partType = "join"
activeBuilder = &joinParts
case "__pb_discard__":
// skip following tokens
skip = true
default:
isJoin := partType == "join"
if isJoin && trimmed == "on" {
skip = true
}
if !skip && activeBuilder != nil {
activeBuilder.WriteString(" ")
activeBuilder.WriteString(token)
}
}
}
selects, err := extractIdentifiers(selectParts.String())
if err != nil {
return err
}
froms, err := extractIdentifiers(fromParts.String())
if err != nil {
return err
}
joins, err := extractIdentifiers(joinParts.String())
if err != nil {
return err
}
p.columns = selects
p.tables = froms
p.tables = append(p.tables, joins...)
return nil
}
func extractIdentifiers(rawExpression string) ([]identifier, error) {
rawTk := tokenizer.NewFromString(rawExpression)
rawTk.Separators(',')
rawIdentifiers, err := rawTk.ScanAll()
if err != nil {
return nil, err
}
result := make([]identifier, 0, len(rawIdentifiers))
for _, rawIdentifier := range rawIdentifiers {
tk := tokenizer.NewFromString(rawIdentifier)
tk.Separators(' ', '\n', '\t')
parts, err := tk.ScanAll()
if err != nil {
return nil, err
}
resolved, err := identifierFromParts(parts)
if err != nil {
return nil, err
}
result = append(result, resolved)
}
return result, nil
}
func identifierFromParts(parts []string) (identifier, error) {
var result identifier
switch len(parts) {
case 3:
if !strings.EqualFold(parts[1], "as") {
return result, fmt.Errorf(`invalid identifier part - expected "as", got %v`, parts[1])
}
result.original = parts[0]
result.alias = parts[2]
case 2:
result.original = parts[0]
result.alias = parts[1]
case 1:
subParts := strings.Split(parts[0], ".")
result.original = parts[0]
result.alias = subParts[len(subParts)-1]
default:
return result, fmt.Errorf(`invalid identifier parts %v`, parts)
}
result.original = trimRawIdentifier(result.original)
// we trim the single quote even though it is not a valid column quote character
// because SQLite allows it if the context expects an identifier and not string literal
// (https://www.sqlite.org/lang_keywords.html)
result.alias = trimRawIdentifier(result.alias, "'")
return result, nil
}
func trimRawIdentifier(rawIdentifier string, extraTrimChars ...string) string {
trimChars := "`\"[];"
if len(extraTrimChars) > 0 {
trimChars += strings.Join(extraTrimChars, "")
}
parts := strings.Split(rawIdentifier, ".")
for i := range parts {
parts[i] = strings.Trim(parts[i], trimChars)
}
return strings.Join(parts, ".")
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_tx.go | core/db_tx.go | package core
import (
"errors"
"fmt"
"sync"
"github.com/pocketbase/dbx"
)
// RunInTransaction wraps fn into a transaction for the regular app database.
//
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
func (app *BaseApp) RunInTransaction(fn func(txApp App) error) error {
return app.runInTransaction(app.NonconcurrentDB(), fn, false)
}
// AuxRunInTransaction wraps fn into a transaction for the auxiliary app database.
//
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
func (app *BaseApp) AuxRunInTransaction(fn func(txApp App) error) error {
return app.runInTransaction(app.AuxNonconcurrentDB(), fn, true)
}
func (app *BaseApp) runInTransaction(db dbx.Builder, fn func(txApp App) error, isForAuxDB bool) error {
switch txOrDB := db.(type) {
case *dbx.Tx:
// run as part of the already existing transaction
return fn(app)
case *dbx.DB:
var txApp *BaseApp
txErr := txOrDB.Transactional(func(tx *dbx.Tx) error {
txApp = app.createTxApp(tx, isForAuxDB)
return fn(txApp)
})
// execute all after event calls on transaction complete
if txApp != nil && txApp.txInfo != nil {
afterFuncErr := txApp.txInfo.runAfterFuncs(txErr)
if afterFuncErr != nil {
return errors.Join(txErr, afterFuncErr)
}
}
return txErr
default:
return errors.New("failed to start transaction (unknown db type)")
}
}
// createTxApp shallow clones the current app and assigns a new tx state.
func (app *BaseApp) createTxApp(tx *dbx.Tx, isForAuxDB bool) *BaseApp {
clone := *app
if isForAuxDB {
clone.auxConcurrentDB = tx
clone.auxNonconcurrentDB = tx
} else {
clone.concurrentDB = tx
clone.nonconcurrentDB = tx
}
clone.txInfo = &TxAppInfo{
parent: app,
isForAuxDB: isForAuxDB,
}
return &clone
}
// TxAppInfo represents an active transaction context associated to an existing app instance.
type TxAppInfo struct {
parent *BaseApp
afterFuncs []func(txErr error) error
mu sync.Mutex
isForAuxDB bool
}
// OnComplete registers the provided callback that will be invoked
// once the related transaction ends (either completes successfully or rollbacked with an error).
//
// The callback receives the transaction error (if any) as its argument.
// Any additional errors returned by the OnComplete callbacks will be
// joined together with txErr when returning the final transaction result.
func (a *TxAppInfo) OnComplete(fn func(txErr error) error) {
a.mu.Lock()
defer a.mu.Unlock()
a.afterFuncs = append(a.afterFuncs, fn)
}
// note: can be called only once because TxAppInfo is cleared
func (a *TxAppInfo) runAfterFuncs(txErr error) error {
a.mu.Lock()
defer a.mu.Unlock()
var errs []error
for _, call := range a.afterFuncs {
if err := call(txErr); err != nil {
errs = append(errs, err)
}
}
a.afterFuncs = nil
if len(errs) > 0 {
return fmt.Errorf("transaction afterFunc errors: %w", errors.Join(errs...))
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_email_test.go | core/field_email_test.go | package core_test
import (
"context"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestEmailFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeEmail)
}
func TestEmailFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.EmailField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestEmailFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.EmailField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"test", "test"},
{false, "false"},
{true, "true"},
{123.456, "123.456"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vStr, ok := v.(string)
if !ok {
t.Fatalf("Expected string instance, got %T", v)
}
if vStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, v)
}
})
}
}
func TestEmailFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.EmailField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.EmailField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (not required)",
&core.EmailField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
false,
},
{
"zero field value (required)",
&core.EmailField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"non-zero field value (required)",
&core.EmailField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "test@example.com")
return record
},
false,
},
{
"invalid email",
&core.EmailField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "invalid")
return record
},
true,
},
{
"failed onlyDomains",
&core.EmailField{Name: "test", OnlyDomains: []string{"example.org", "example.net"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "test@example.com")
return record
},
true,
},
{
"success onlyDomains",
&core.EmailField{Name: "test", OnlyDomains: []string{"example.org", "example.com"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "test@example.com")
return record
},
false,
},
{
"failed exceptDomains",
&core.EmailField{Name: "test", ExceptDomains: []string{"example.org", "example.com"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "test@example.com")
return record
},
true,
},
{
"success exceptDomains",
&core.EmailField{Name: "test", ExceptDomains: []string{"example.org", "example.net"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "test@example.com")
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestEmailFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeEmail)
testDefaultFieldNameValidation(t, core.FieldTypeEmail)
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() *core.EmailField
expectErrors []string
}{
{
"zero minimal",
func() *core.EmailField {
return &core.EmailField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"both onlyDomains and exceptDomains",
func() *core.EmailField {
return &core.EmailField{
Id: "test",
Name: "test",
OnlyDomains: []string{"example.com"},
ExceptDomains: []string{"example.org"},
}
},
[]string{"onlyDomains", "exceptDomains"},
},
{
"invalid onlyDomains",
func() *core.EmailField {
return &core.EmailField{
Id: "test",
Name: "test",
OnlyDomains: []string{"example.com", "invalid"},
}
},
[]string{"onlyDomains"},
},
{
"valid onlyDomains",
func() *core.EmailField {
return &core.EmailField{
Id: "test",
Name: "test",
OnlyDomains: []string{"example.com", "example.org"},
}
},
[]string{},
},
{
"invalid exceptDomains",
func() *core.EmailField {
return &core.EmailField{
Id: "test",
Name: "test",
ExceptDomains: []string{"example.com", "invalid"},
}
},
[]string{"exceptDomains"},
},
{
"valid exceptDomains",
func() *core.EmailField {
return &core.EmailField{
Id: "test",
Name: "test",
ExceptDomains: []string{"example.com", "example.org"},
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/base.go | core/base.go | package core
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/fatih/color"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/cron"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/logger"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/routine"
"github.com/pocketbase/pocketbase/tools/store"
"github.com/pocketbase/pocketbase/tools/subscriptions"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
"golang.org/x/sync/semaphore"
)
const (
DefaultDataMaxOpenConns int = 120
DefaultDataMaxIdleConns int = 15
DefaultAuxMaxOpenConns int = 20
DefaultAuxMaxIdleConns int = 3
DefaultQueryTimeout time.Duration = 30 * time.Second
LocalStorageDirName string = "storage"
LocalBackupsDirName string = "backups"
LocalTempDirName string = ".pb_temp_to_delete" // temp pb_data sub directory that will be deleted on each app.Bootstrap()
LocalAutocertCacheDirName string = ".autocert_cache"
// @todo consider removing after backups refactoring
lostFoundDirName string = "lost+found"
)
// FilesManager defines an interface with common methods that files manager models should implement.
type FilesManager interface {
// BaseFilesPath returns the storage dir path used by the interface instance.
BaseFilesPath() string
}
// DBConnectFunc defines a database connection initialization function.
type DBConnectFunc func(dbPath string) (*dbx.DB, error)
// BaseAppConfig defines a BaseApp configuration option
type BaseAppConfig struct {
DBConnect DBConnectFunc
DataDir string
EncryptionEnv string
QueryTimeout time.Duration
DataMaxOpenConns int
DataMaxIdleConns int
AuxMaxOpenConns int
AuxMaxIdleConns int
IsDev bool
}
// ensures that the BaseApp implements the App interface.
var _ App = (*BaseApp)(nil)
// BaseApp implements core.App and defines the base PocketBase app structure.
type BaseApp struct {
config *BaseAppConfig
txInfo *TxAppInfo
store *store.Store[string, any]
cron *cron.Cron
settings *Settings
subscriptionsBroker *subscriptions.Broker
logger *slog.Logger
concurrentDB dbx.Builder
nonconcurrentDB dbx.Builder
auxConcurrentDB dbx.Builder
auxNonconcurrentDB dbx.Builder
// app event hooks
onBootstrap *hook.Hook[*BootstrapEvent]
onServe *hook.Hook[*ServeEvent]
onTerminate *hook.Hook[*TerminateEvent]
onBackupCreate *hook.Hook[*BackupEvent]
onBackupRestore *hook.Hook[*BackupEvent]
// db model hooks
onModelValidate *hook.Hook[*ModelEvent]
onModelCreate *hook.Hook[*ModelEvent]
onModelCreateExecute *hook.Hook[*ModelEvent]
onModelAfterCreateSuccess *hook.Hook[*ModelEvent]
onModelAfterCreateError *hook.Hook[*ModelErrorEvent]
onModelUpdate *hook.Hook[*ModelEvent]
onModelUpdateWrite *hook.Hook[*ModelEvent]
onModelAfterUpdateSuccess *hook.Hook[*ModelEvent]
onModelAfterUpdateError *hook.Hook[*ModelErrorEvent]
onModelDelete *hook.Hook[*ModelEvent]
onModelDeleteExecute *hook.Hook[*ModelEvent]
onModelAfterDeleteSuccess *hook.Hook[*ModelEvent]
onModelAfterDeleteError *hook.Hook[*ModelErrorEvent]
// db record hooks
onRecordEnrich *hook.Hook[*RecordEnrichEvent]
onRecordValidate *hook.Hook[*RecordEvent]
onRecordCreate *hook.Hook[*RecordEvent]
onRecordCreateExecute *hook.Hook[*RecordEvent]
onRecordAfterCreateSuccess *hook.Hook[*RecordEvent]
onRecordAfterCreateError *hook.Hook[*RecordErrorEvent]
onRecordUpdate *hook.Hook[*RecordEvent]
onRecordUpdateExecute *hook.Hook[*RecordEvent]
onRecordAfterUpdateSuccess *hook.Hook[*RecordEvent]
onRecordAfterUpdateError *hook.Hook[*RecordErrorEvent]
onRecordDelete *hook.Hook[*RecordEvent]
onRecordDeleteExecute *hook.Hook[*RecordEvent]
onRecordAfterDeleteSuccess *hook.Hook[*RecordEvent]
onRecordAfterDeleteError *hook.Hook[*RecordErrorEvent]
// db collection hooks
onCollectionValidate *hook.Hook[*CollectionEvent]
onCollectionCreate *hook.Hook[*CollectionEvent]
onCollectionCreateExecute *hook.Hook[*CollectionEvent]
onCollectionAfterCreateSuccess *hook.Hook[*CollectionEvent]
onCollectionAfterCreateError *hook.Hook[*CollectionErrorEvent]
onCollectionUpdate *hook.Hook[*CollectionEvent]
onCollectionUpdateExecute *hook.Hook[*CollectionEvent]
onCollectionAfterUpdateSuccess *hook.Hook[*CollectionEvent]
onCollectionAfterUpdateError *hook.Hook[*CollectionErrorEvent]
onCollectionDelete *hook.Hook[*CollectionEvent]
onCollectionDeleteExecute *hook.Hook[*CollectionEvent]
onCollectionAfterDeleteSuccess *hook.Hook[*CollectionEvent]
onCollectionAfterDeleteError *hook.Hook[*CollectionErrorEvent]
// mailer event hooks
onMailerSend *hook.Hook[*MailerEvent]
onMailerRecordPasswordResetSend *hook.Hook[*MailerRecordEvent]
onMailerRecordVerificationSend *hook.Hook[*MailerRecordEvent]
onMailerRecordEmailChangeSend *hook.Hook[*MailerRecordEvent]
onMailerRecordOTPSend *hook.Hook[*MailerRecordEvent]
onMailerRecordAuthAlertSend *hook.Hook[*MailerRecordEvent]
// realtime api event hooks
onRealtimeConnectRequest *hook.Hook[*RealtimeConnectRequestEvent]
onRealtimeMessageSend *hook.Hook[*RealtimeMessageEvent]
onRealtimeSubscribeRequest *hook.Hook[*RealtimeSubscribeRequestEvent]
// settings event hooks
onSettingsListRequest *hook.Hook[*SettingsListRequestEvent]
onSettingsUpdateRequest *hook.Hook[*SettingsUpdateRequestEvent]
onSettingsReload *hook.Hook[*SettingsReloadEvent]
// file api event hooks
onFileDownloadRequest *hook.Hook[*FileDownloadRequestEvent]
onFileTokenRequest *hook.Hook[*FileTokenRequestEvent]
// record auth API event hooks
onRecordAuthRequest *hook.Hook[*RecordAuthRequestEvent]
onRecordAuthWithPasswordRequest *hook.Hook[*RecordAuthWithPasswordRequestEvent]
onRecordAuthWithOAuth2Request *hook.Hook[*RecordAuthWithOAuth2RequestEvent]
onRecordAuthRefreshRequest *hook.Hook[*RecordAuthRefreshRequestEvent]
onRecordRequestPasswordResetRequest *hook.Hook[*RecordRequestPasswordResetRequestEvent]
onRecordConfirmPasswordResetRequest *hook.Hook[*RecordConfirmPasswordResetRequestEvent]
onRecordRequestVerificationRequest *hook.Hook[*RecordRequestVerificationRequestEvent]
onRecordConfirmVerificationRequest *hook.Hook[*RecordConfirmVerificationRequestEvent]
onRecordRequestEmailChangeRequest *hook.Hook[*RecordRequestEmailChangeRequestEvent]
onRecordConfirmEmailChangeRequest *hook.Hook[*RecordConfirmEmailChangeRequestEvent]
onRecordRequestOTPRequest *hook.Hook[*RecordCreateOTPRequestEvent]
onRecordAuthWithOTPRequest *hook.Hook[*RecordAuthWithOTPRequestEvent]
// record crud API event hooks
onRecordsListRequest *hook.Hook[*RecordsListRequestEvent]
onRecordViewRequest *hook.Hook[*RecordRequestEvent]
onRecordCreateRequest *hook.Hook[*RecordRequestEvent]
onRecordUpdateRequest *hook.Hook[*RecordRequestEvent]
onRecordDeleteRequest *hook.Hook[*RecordRequestEvent]
// collection API event hooks
onCollectionsListRequest *hook.Hook[*CollectionsListRequestEvent]
onCollectionViewRequest *hook.Hook[*CollectionRequestEvent]
onCollectionCreateRequest *hook.Hook[*CollectionRequestEvent]
onCollectionUpdateRequest *hook.Hook[*CollectionRequestEvent]
onCollectionDeleteRequest *hook.Hook[*CollectionRequestEvent]
onCollectionsImportRequest *hook.Hook[*CollectionsImportRequestEvent]
onBatchRequest *hook.Hook[*BatchRequestEvent]
}
// NewBaseApp creates and returns a new BaseApp instance
// configured with the provided arguments.
//
// To initialize the app, you need to call `app.Bootstrap()`.
func NewBaseApp(config BaseAppConfig) *BaseApp {
app := &BaseApp{
settings: newDefaultSettings(),
store: store.New[string, any](nil),
cron: cron.New(),
subscriptionsBroker: subscriptions.NewBroker(),
config: &config,
}
// apply config defaults
if app.config.DBConnect == nil {
app.config.DBConnect = DefaultDBConnect
}
if app.config.DataMaxOpenConns <= 0 {
app.config.DataMaxOpenConns = DefaultDataMaxOpenConns
}
if app.config.DataMaxIdleConns <= 0 {
app.config.DataMaxIdleConns = DefaultDataMaxIdleConns
}
if app.config.AuxMaxOpenConns <= 0 {
app.config.AuxMaxOpenConns = DefaultAuxMaxOpenConns
}
if app.config.AuxMaxIdleConns <= 0 {
app.config.AuxMaxIdleConns = DefaultAuxMaxIdleConns
}
if app.config.QueryTimeout <= 0 {
app.config.QueryTimeout = DefaultQueryTimeout
}
app.initHooks()
app.registerBaseHooks()
return app
}
// initHooks initializes all app hook handlers.
func (app *BaseApp) initHooks() {
// app event hooks
app.onBootstrap = &hook.Hook[*BootstrapEvent]{}
app.onServe = &hook.Hook[*ServeEvent]{}
app.onTerminate = &hook.Hook[*TerminateEvent]{}
app.onBackupCreate = &hook.Hook[*BackupEvent]{}
app.onBackupRestore = &hook.Hook[*BackupEvent]{}
// db model hooks
app.onModelValidate = &hook.Hook[*ModelEvent]{}
app.onModelCreate = &hook.Hook[*ModelEvent]{}
app.onModelCreateExecute = &hook.Hook[*ModelEvent]{}
app.onModelAfterCreateSuccess = &hook.Hook[*ModelEvent]{}
app.onModelAfterCreateError = &hook.Hook[*ModelErrorEvent]{}
app.onModelUpdate = &hook.Hook[*ModelEvent]{}
app.onModelUpdateWrite = &hook.Hook[*ModelEvent]{}
app.onModelAfterUpdateSuccess = &hook.Hook[*ModelEvent]{}
app.onModelAfterUpdateError = &hook.Hook[*ModelErrorEvent]{}
app.onModelDelete = &hook.Hook[*ModelEvent]{}
app.onModelDeleteExecute = &hook.Hook[*ModelEvent]{}
app.onModelAfterDeleteSuccess = &hook.Hook[*ModelEvent]{}
app.onModelAfterDeleteError = &hook.Hook[*ModelErrorEvent]{}
// db record hooks
app.onRecordEnrich = &hook.Hook[*RecordEnrichEvent]{}
app.onRecordValidate = &hook.Hook[*RecordEvent]{}
app.onRecordCreate = &hook.Hook[*RecordEvent]{}
app.onRecordCreateExecute = &hook.Hook[*RecordEvent]{}
app.onRecordAfterCreateSuccess = &hook.Hook[*RecordEvent]{}
app.onRecordAfterCreateError = &hook.Hook[*RecordErrorEvent]{}
app.onRecordUpdate = &hook.Hook[*RecordEvent]{}
app.onRecordUpdateExecute = &hook.Hook[*RecordEvent]{}
app.onRecordAfterUpdateSuccess = &hook.Hook[*RecordEvent]{}
app.onRecordAfterUpdateError = &hook.Hook[*RecordErrorEvent]{}
app.onRecordDelete = &hook.Hook[*RecordEvent]{}
app.onRecordDeleteExecute = &hook.Hook[*RecordEvent]{}
app.onRecordAfterDeleteSuccess = &hook.Hook[*RecordEvent]{}
app.onRecordAfterDeleteError = &hook.Hook[*RecordErrorEvent]{}
// db collection hooks
app.onCollectionValidate = &hook.Hook[*CollectionEvent]{}
app.onCollectionCreate = &hook.Hook[*CollectionEvent]{}
app.onCollectionCreateExecute = &hook.Hook[*CollectionEvent]{}
app.onCollectionAfterCreateSuccess = &hook.Hook[*CollectionEvent]{}
app.onCollectionAfterCreateError = &hook.Hook[*CollectionErrorEvent]{}
app.onCollectionUpdate = &hook.Hook[*CollectionEvent]{}
app.onCollectionUpdateExecute = &hook.Hook[*CollectionEvent]{}
app.onCollectionAfterUpdateSuccess = &hook.Hook[*CollectionEvent]{}
app.onCollectionAfterUpdateError = &hook.Hook[*CollectionErrorEvent]{}
app.onCollectionDelete = &hook.Hook[*CollectionEvent]{}
app.onCollectionAfterDeleteSuccess = &hook.Hook[*CollectionEvent]{}
app.onCollectionDeleteExecute = &hook.Hook[*CollectionEvent]{}
app.onCollectionAfterDeleteError = &hook.Hook[*CollectionErrorEvent]{}
// mailer event hooks
app.onMailerSend = &hook.Hook[*MailerEvent]{}
app.onMailerRecordPasswordResetSend = &hook.Hook[*MailerRecordEvent]{}
app.onMailerRecordVerificationSend = &hook.Hook[*MailerRecordEvent]{}
app.onMailerRecordEmailChangeSend = &hook.Hook[*MailerRecordEvent]{}
app.onMailerRecordOTPSend = &hook.Hook[*MailerRecordEvent]{}
app.onMailerRecordAuthAlertSend = &hook.Hook[*MailerRecordEvent]{}
// realtime API event hooks
app.onRealtimeConnectRequest = &hook.Hook[*RealtimeConnectRequestEvent]{}
app.onRealtimeMessageSend = &hook.Hook[*RealtimeMessageEvent]{}
app.onRealtimeSubscribeRequest = &hook.Hook[*RealtimeSubscribeRequestEvent]{}
// settings event hooks
app.onSettingsListRequest = &hook.Hook[*SettingsListRequestEvent]{}
app.onSettingsUpdateRequest = &hook.Hook[*SettingsUpdateRequestEvent]{}
app.onSettingsReload = &hook.Hook[*SettingsReloadEvent]{}
// file API event hooks
app.onFileDownloadRequest = &hook.Hook[*FileDownloadRequestEvent]{}
app.onFileTokenRequest = &hook.Hook[*FileTokenRequestEvent]{}
// record auth API event hooks
app.onRecordAuthRequest = &hook.Hook[*RecordAuthRequestEvent]{}
app.onRecordAuthWithPasswordRequest = &hook.Hook[*RecordAuthWithPasswordRequestEvent]{}
app.onRecordAuthWithOAuth2Request = &hook.Hook[*RecordAuthWithOAuth2RequestEvent]{}
app.onRecordAuthRefreshRequest = &hook.Hook[*RecordAuthRefreshRequestEvent]{}
app.onRecordRequestPasswordResetRequest = &hook.Hook[*RecordRequestPasswordResetRequestEvent]{}
app.onRecordConfirmPasswordResetRequest = &hook.Hook[*RecordConfirmPasswordResetRequestEvent]{}
app.onRecordRequestVerificationRequest = &hook.Hook[*RecordRequestVerificationRequestEvent]{}
app.onRecordConfirmVerificationRequest = &hook.Hook[*RecordConfirmVerificationRequestEvent]{}
app.onRecordRequestEmailChangeRequest = &hook.Hook[*RecordRequestEmailChangeRequestEvent]{}
app.onRecordConfirmEmailChangeRequest = &hook.Hook[*RecordConfirmEmailChangeRequestEvent]{}
app.onRecordRequestOTPRequest = &hook.Hook[*RecordCreateOTPRequestEvent]{}
app.onRecordAuthWithOTPRequest = &hook.Hook[*RecordAuthWithOTPRequestEvent]{}
// record crud API event hooks
app.onRecordsListRequest = &hook.Hook[*RecordsListRequestEvent]{}
app.onRecordViewRequest = &hook.Hook[*RecordRequestEvent]{}
app.onRecordCreateRequest = &hook.Hook[*RecordRequestEvent]{}
app.onRecordUpdateRequest = &hook.Hook[*RecordRequestEvent]{}
app.onRecordDeleteRequest = &hook.Hook[*RecordRequestEvent]{}
// collection API event hooks
app.onCollectionsListRequest = &hook.Hook[*CollectionsListRequestEvent]{}
app.onCollectionViewRequest = &hook.Hook[*CollectionRequestEvent]{}
app.onCollectionCreateRequest = &hook.Hook[*CollectionRequestEvent]{}
app.onCollectionUpdateRequest = &hook.Hook[*CollectionRequestEvent]{}
app.onCollectionDeleteRequest = &hook.Hook[*CollectionRequestEvent]{}
app.onCollectionsImportRequest = &hook.Hook[*CollectionsImportRequestEvent]{}
app.onBatchRequest = &hook.Hook[*BatchRequestEvent]{}
}
// UnsafeWithoutHooks returns a shallow copy of the current app WITHOUT any registered hooks.
//
// NB! Note that using the returned app instance may cause data integrity errors
// since the Record validations and data normalizations (including files uploads)
// rely on the app hooks to work.
func (app *BaseApp) UnsafeWithoutHooks() App {
clone := *app
// reset all hook handlers
clone.initHooks()
return &clone
}
// Logger returns the default app logger.
//
// If the application is not bootstrapped yet, fallbacks to slog.Default().
func (app *BaseApp) Logger() *slog.Logger {
if app.logger == nil {
return slog.Default()
}
return app.logger
}
// TxInfo returns the transaction associated with the current app instance (if any).
//
// Could be used if you want to execute indirectly a function after
// the related app transaction completes using `app.TxInfo().OnAfterFunc(callback)`.
func (app *BaseApp) TxInfo() *TxAppInfo {
return app.txInfo
}
// IsTransactional checks if the current app instance is part of a transaction.
func (app *BaseApp) IsTransactional() bool {
return app.TxInfo() != nil
}
// IsBootstrapped checks if the application was initialized
// (aka. whether Bootstrap() was called).
func (app *BaseApp) IsBootstrapped() bool {
return app.concurrentDB != nil && app.auxConcurrentDB != nil
}
// Bootstrap initializes the application
// (aka. create data dir, open db connections, load settings, etc.).
//
// It will call ResetBootstrapState() if the application was already bootstrapped.
func (app *BaseApp) Bootstrap() error {
event := &BootstrapEvent{}
event.App = app
err := app.OnBootstrap().Trigger(event, func(e *BootstrapEvent) error {
// clear resources of previous core state (if any)
if err := app.ResetBootstrapState(); err != nil {
return err
}
// ensure that data dir exist
if err := os.MkdirAll(app.DataDir(), os.ModePerm); err != nil {
return err
}
if err := app.initDataDB(); err != nil {
return err
}
if err := app.initAuxDB(); err != nil {
return err
}
if err := app.initLogger(); err != nil {
return err
}
if err := app.RunSystemMigrations(); err != nil {
return err
}
if err := app.ReloadCachedCollections(); err != nil {
return err
}
if err := app.ReloadSettings(); err != nil {
return err
}
// try to cleanup the pb_data temp directory (if any)
_ = os.RemoveAll(filepath.Join(app.DataDir(), LocalTempDirName))
return nil
})
// add a more user friendly message in case users forgot to call
// e.Next() as part of their bootstrap hook
if err == nil && !app.IsBootstrapped() {
app.Logger().Warn("OnBootstrap hook didn't fail but the app is still not bootstrapped - maybe missing e.Next()?")
}
return err
}
type closer interface {
Close() error
}
// ResetBootstrapState releases the initialized core app resources
// (closing db connections, stopping cron ticker, etc.).
func (app *BaseApp) ResetBootstrapState() error {
app.Cron().Stop()
var errs []error
dbs := []*dbx.Builder{
&app.concurrentDB,
&app.nonconcurrentDB,
&app.auxConcurrentDB,
&app.auxNonconcurrentDB,
}
for _, db := range dbs {
if db == nil {
continue
}
if v, ok := (*db).(closer); ok {
if err := v.Close(); err != nil {
errs = append(errs, err)
}
}
*db = nil
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// DB returns the default app data.db builder instance.
//
// To minimize SQLITE_BUSY errors, it automatically routes the
// SELECT queries to the underlying concurrent db pool and everything
// else to the nonconcurrent one.
//
// For more finer control over the used connections pools you can
// call directly ConcurrentDB() or NonconcurrentDB().
func (app *BaseApp) DB() dbx.Builder {
// transactional or both are nil
if app.concurrentDB == app.nonconcurrentDB {
return app.concurrentDB
}
return &dualDBBuilder{
concurrentDB: app.concurrentDB,
nonconcurrentDB: app.nonconcurrentDB,
}
}
// ConcurrentDB returns the concurrent app data.db builder instance.
//
// This method is used mainly internally for executing db read
// operations in a concurrent/non-blocking manner.
//
// Most users should use simply DB() as it will automatically
// route the query execution to ConcurrentDB() or NonconcurrentDB().
//
// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
func (app *BaseApp) ConcurrentDB() dbx.Builder {
return app.concurrentDB
}
// NonconcurrentDB returns the nonconcurrent app data.db builder instance.
//
// The returned db instance is limited only to a single open connection,
// meaning that it can process only 1 db operation at a time (other queries queue up).
//
// This method is used mainly internally and in the tests to execute write
// (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
//
// Most users should use simply DB() as it will automatically
// route the query execution to ConcurrentDB() or NonconcurrentDB().
//
// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
func (app *BaseApp) NonconcurrentDB() dbx.Builder {
return app.nonconcurrentDB
}
// AuxDB returns the app auxiliary.db builder instance.
//
// To minimize SQLITE_BUSY errors, it automatically routes the
// SELECT queries to the underlying concurrent db pool and everything
// else to the nonconcurrent one.
//
// For more finer control over the used connections pools you can
// call directly AuxConcurrentDB() or AuxNonconcurrentDB().
func (app *BaseApp) AuxDB() dbx.Builder {
// transactional or both are nil
if app.auxConcurrentDB == app.auxNonconcurrentDB {
return app.auxConcurrentDB
}
return &dualDBBuilder{
concurrentDB: app.auxConcurrentDB,
nonconcurrentDB: app.auxNonconcurrentDB,
}
}
// AuxConcurrentDB returns the concurrent app auxiliary.db builder instance.
//
// This method is used mainly internally for executing db read
// operations in a concurrent/non-blocking manner.
//
// Most users should use simply AuxDB() as it will automatically
// route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
//
// In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
func (app *BaseApp) AuxConcurrentDB() dbx.Builder {
return app.auxConcurrentDB
}
// AuxNonconcurrentDB returns the nonconcurrent app auxiliary.db builder instance.
//
// The returned db instance is limited only to a single open connection,
// meaning that it can process only 1 db operation at a time (other queries queue up).
//
// This method is used mainly internally and in the tests to execute write
// (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
//
// Most users should use simply AuxDB() as it will automatically
// route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
//
// In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
func (app *BaseApp) AuxNonconcurrentDB() dbx.Builder {
return app.auxNonconcurrentDB
}
// DataDir returns the app data directory path.
func (app *BaseApp) DataDir() string {
return app.config.DataDir
}
// EncryptionEnv returns the name of the app secret env key
// (currently used primarily for optional settings encryption but this may change in the future).
func (app *BaseApp) EncryptionEnv() string {
return app.config.EncryptionEnv
}
// IsDev returns whether the app is in dev mode.
//
// When enabled logs, executed sql statements, etc. are printed to the stderr.
func (app *BaseApp) IsDev() bool {
return app.config.IsDev
}
// Settings returns the loaded app settings.
func (app *BaseApp) Settings() *Settings {
return app.settings
}
// Store returns the app runtime store.
func (app *BaseApp) Store() *store.Store[string, any] {
return app.store
}
// Cron returns the app cron instance.
func (app *BaseApp) Cron() *cron.Cron {
return app.cron
}
// SubscriptionsBroker returns the app realtime subscriptions broker instance.
func (app *BaseApp) SubscriptionsBroker() *subscriptions.Broker {
return app.subscriptionsBroker
}
// NewMailClient creates and returns a new SMTP or Sendmail client
// based on the current app settings.
func (app *BaseApp) NewMailClient() mailer.Mailer {
var client mailer.Mailer
// init mailer client
if app.Settings().SMTP.Enabled {
client = &mailer.SMTPClient{
Host: app.Settings().SMTP.Host,
Port: app.Settings().SMTP.Port,
Username: app.Settings().SMTP.Username,
Password: app.Settings().SMTP.Password,
TLS: app.Settings().SMTP.TLS,
AuthMethod: app.Settings().SMTP.AuthMethod,
LocalName: app.Settings().SMTP.LocalName,
}
} else {
client = &mailer.Sendmail{}
}
// register the app level hook
if h, ok := client.(mailer.SendInterceptor); ok {
h.OnSend().Bind(&hook.Handler[*mailer.SendEvent]{
Id: "__pbMailerOnSend__",
Func: func(e *mailer.SendEvent) error {
appEvent := new(MailerEvent)
appEvent.App = app
appEvent.Mailer = client
appEvent.Message = e.Message
return app.OnMailerSend().Trigger(appEvent, func(ae *MailerEvent) error {
e.Message = ae.Message
// print the mail in the console to assist with the debugging
if app.IsDev() {
logDate := new(strings.Builder)
log.New(logDate, "", log.LstdFlags).Print()
mailLog := new(strings.Builder)
mailLog.WriteString(strings.TrimSpace(logDate.String()))
mailLog.WriteString(" Mail sent\n")
fmt.Fprintf(mailLog, "├─ From: %v\n", ae.Message.From)
fmt.Fprintf(mailLog, "├─ To: %v\n", ae.Message.To)
fmt.Fprintf(mailLog, "├─ Cc: %v\n", ae.Message.Cc)
fmt.Fprintf(mailLog, "├─ Bcc: %v\n", ae.Message.Bcc)
fmt.Fprintf(mailLog, "├─ Subject: %v\n", ae.Message.Subject)
if len(ae.Message.Attachments) > 0 {
attachmentKeys := make([]string, 0, len(ae.Message.Attachments))
for k := range ae.Message.Attachments {
attachmentKeys = append(attachmentKeys, k)
}
fmt.Fprintf(mailLog, "├─ Attachments: %v\n", attachmentKeys)
}
if len(ae.Message.InlineAttachments) > 0 {
attachmentKeys := make([]string, 0, len(ae.Message.InlineAttachments))
for k := range ae.Message.InlineAttachments {
attachmentKeys = append(attachmentKeys, k)
}
fmt.Fprintf(mailLog, "├─ InlineAttachments: %v\n", attachmentKeys)
}
const indentation = " "
if ae.Message.Text != "" {
textParts := strings.Split(strings.TrimSpace(ae.Message.Text), "\n")
textIndented := indentation + strings.Join(textParts, "\n"+indentation)
fmt.Fprintf(mailLog, "└─ Text:\n%s", textIndented)
} else {
htmlParts := strings.Split(strings.TrimSpace(ae.Message.HTML), "\n")
htmlIndented := indentation + strings.Join(htmlParts, "\n"+indentation)
fmt.Fprintf(mailLog, "└─ HTML:\n%s", htmlIndented)
}
color.HiBlack("%s", mailLog.String())
}
// send the email with the new mailer in case it was replaced
if client != ae.Mailer {
return ae.Mailer.Send(e.Message)
}
return e.Next()
})
},
})
}
return client
}
// NewFilesystem creates a new local or S3 filesystem instance
// for managing regular app files (ex. record uploads)
// based on the current app settings.
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
func (app *BaseApp) NewFilesystem() (*filesystem.System, error) {
if app.settings != nil && app.settings.S3.Enabled {
return filesystem.NewS3(
app.settings.S3.Bucket,
app.settings.S3.Region,
app.settings.S3.Endpoint,
app.settings.S3.AccessKey,
app.settings.S3.Secret,
app.settings.S3.ForcePathStyle,
)
}
// fallback to local filesystem
return filesystem.NewLocal(filepath.Join(app.DataDir(), LocalStorageDirName))
}
// NewBackupsFilesystem creates a new local or S3 filesystem instance
// for managing app backups based on the current app settings.
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
func (app *BaseApp) NewBackupsFilesystem() (*filesystem.System, error) {
if app.settings != nil && app.settings.Backups.S3.Enabled {
return filesystem.NewS3(
app.settings.Backups.S3.Bucket,
app.settings.Backups.S3.Region,
app.settings.Backups.S3.Endpoint,
app.settings.Backups.S3.AccessKey,
app.settings.Backups.S3.Secret,
app.settings.Backups.S3.ForcePathStyle,
)
}
// fallback to local filesystem
return filesystem.NewLocal(filepath.Join(app.DataDir(), LocalBackupsDirName))
}
// Restart restarts (aka. replaces) the current running application process.
//
// NB! It relies on execve which is supported only on UNIX based systems.
func (app *BaseApp) Restart() error {
if runtime.GOOS == "windows" {
return errors.New("restart is not supported on windows")
}
execPath, err := os.Executable()
if err != nil {
return err
}
event := &TerminateEvent{}
event.App = app
event.IsRestart = true
return app.OnTerminate().Trigger(event, func(e *TerminateEvent) error {
_ = e.App.ResetBootstrapState()
// attempt to restart the bootstrap process in case execve returns an error for some reason
defer func() {
if err := e.App.Bootstrap(); err != nil {
app.Logger().Error("Failed to rebootstrap the application after failed app.Restart()", "error", err)
}
}()
return execve(execPath, os.Args, os.Environ())
})
}
// RunSystemMigrations applies all new migrations registered in the [core.SystemMigrations] list.
func (app *BaseApp) RunSystemMigrations() error {
_, err := NewMigrationsRunner(app, SystemMigrations).Up()
return err
}
// RunAppMigrations applies all new migrations registered in the [core.AppMigrations] list.
func (app *BaseApp) RunAppMigrations() error {
_, err := NewMigrationsRunner(app, AppMigrations).Up()
return err
}
// RunAllMigrations applies all system and app migrations
// (aka. from both [core.SystemMigrations] and [core.AppMigrations]).
func (app *BaseApp) RunAllMigrations() error {
list := MigrationsList{}
list.Copy(SystemMigrations)
list.Copy(AppMigrations)
_, err := NewMigrationsRunner(app, list).Up()
return err
}
// -------------------------------------------------------------------
// App event hooks
// -------------------------------------------------------------------
func (app *BaseApp) OnBootstrap() *hook.Hook[*BootstrapEvent] {
return app.onBootstrap
}
func (app *BaseApp) OnServe() *hook.Hook[*ServeEvent] {
return app.onServe
}
func (app *BaseApp) OnTerminate() *hook.Hook[*TerminateEvent] {
return app.onTerminate
}
func (app *BaseApp) OnBackupCreate() *hook.Hook[*BackupEvent] {
return app.onBackupCreate
}
func (app *BaseApp) OnBackupRestore() *hook.Hook[*BackupEvent] {
return app.onBackupRestore
}
// ---------------------------------------------------------------
func (app *BaseApp) OnModelCreate(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelCreate, tags...)
}
func (app *BaseApp) OnModelCreateExecute(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelCreateExecute, tags...)
}
func (app *BaseApp) OnModelAfterCreateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelAfterCreateSuccess, tags...)
}
func (app *BaseApp) OnModelAfterCreateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent] {
return hook.NewTaggedHook(app.onModelAfterCreateError, tags...)
}
func (app *BaseApp) OnModelUpdate(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelUpdate, tags...)
}
func (app *BaseApp) OnModelUpdateExecute(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelUpdateWrite, tags...)
}
func (app *BaseApp) OnModelAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelAfterUpdateSuccess, tags...)
}
func (app *BaseApp) OnModelAfterUpdateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent] {
return hook.NewTaggedHook(app.onModelAfterUpdateError, tags...)
}
func (app *BaseApp) OnModelValidate(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelValidate, tags...)
}
func (app *BaseApp) OnModelDelete(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelDelete, tags...)
}
func (app *BaseApp) OnModelDeleteExecute(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelDeleteExecute, tags...)
}
func (app *BaseApp) OnModelAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*ModelEvent] {
return hook.NewTaggedHook(app.onModelAfterDeleteSuccess, tags...)
}
func (app *BaseApp) OnModelAfterDeleteError(tags ...string) *hook.TaggedHook[*ModelErrorEvent] {
return hook.NewTaggedHook(app.onModelAfterDeleteError, tags...)
}
func (app *BaseApp) OnRecordEnrich(tags ...string) *hook.TaggedHook[*RecordEnrichEvent] {
return hook.NewTaggedHook(app.onRecordEnrich, tags...)
}
func (app *BaseApp) OnRecordValidate(tags ...string) *hook.TaggedHook[*RecordEvent] {
return hook.NewTaggedHook(app.onRecordValidate, tags...)
}
func (app *BaseApp) OnRecordCreate(tags ...string) *hook.TaggedHook[*RecordEvent] {
return hook.NewTaggedHook(app.onRecordCreate, tags...)
}
func (app *BaseApp) OnRecordCreateExecute(tags ...string) *hook.TaggedHook[*RecordEvent] {
return hook.NewTaggedHook(app.onRecordCreateExecute, tags...)
}
func (app *BaseApp) OnRecordAfterCreateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent] {
return hook.NewTaggedHook(app.onRecordAfterCreateSuccess, tags...)
}
func (app *BaseApp) OnRecordAfterCreateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent] {
return hook.NewTaggedHook(app.onRecordAfterCreateError, tags...)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/mfa_query_test.go | core/mfa_query_test.go | package core_test
import (
"fmt"
"slices"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestFindAllMFAsByRecord(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubMFARecords(app); err != nil {
t.Fatal(err)
}
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
superuser4, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test4@example.com")
if err != nil {
t.Fatal(err)
}
user1, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
expected []string
}{
{demo1, nil},
{superuser2, []string{"superuser2_0", "superuser2_3", "superuser2_2", "superuser2_1", "superuser2_4"}},
{superuser4, nil},
{user1, []string{"user1_0"}},
}
for _, s := range scenarios {
t.Run(s.record.Collection().Name+"_"+s.record.Id, func(t *testing.T) {
result, err := app.FindAllMFAsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total mfas %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindAllMFAsByCollection(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubMFARecords(app); err != nil {
t.Fatal(err)
}
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
clients, err := app.FindCollectionByNameOrId("clients")
if err != nil {
t.Fatal(err)
}
users, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
collection *core.Collection
expected []string
}{
{demo1, nil},
{superusers, []string{
"superuser2_0",
"superuser2_3",
"superuser3_0",
"superuser2_2",
"superuser3_1",
"superuser2_1",
"superuser2_4",
}},
{clients, nil},
{users, []string{"user1_0"}},
}
for _, s := range scenarios {
t.Run(s.collection.Name, func(t *testing.T) {
result, err := app.FindAllMFAsByCollection(s.collection)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total mfas %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindMFAById(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubMFARecords(app); err != nil {
t.Fatal(err)
}
scenarios := []struct {
id string
expectError bool
}{
{"", true},
{"84nmscqy84lsi1t", true}, // non-mfa id
{"superuser2_0", false},
{"superuser2_4", false}, // expired
{"user1_0", false},
}
for _, s := range scenarios {
t.Run(s.id, func(t *testing.T) {
result, err := app.FindMFAById(s.id)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if result.Id != s.id {
t.Fatalf("Expected record with id %q, got %q", s.id, result.Id)
}
})
}
}
func TestDeleteAllMFAsByRecord(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1, err := testApp.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
superuser4, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test4@example.com")
if err != nil {
t.Fatal(err)
}
user1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
deletedIds []string
}{
{demo1, nil}, // non-auth record
{superuser2, []string{"superuser2_0", "superuser2_1", "superuser2_3", "superuser2_2", "superuser2_4"}},
{superuser4, nil},
{user1, []string{"user1_0"}},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.record.Collection().Name, s.record.Id), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubMFARecords(app); err != nil {
t.Fatal(err)
}
deletedIds := []string{}
app.OnRecordAfterDeleteSuccess().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
err := app.DeleteAllMFAsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(s.deletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", s.deletedIds, deletedIds)
}
for _, id := range s.deletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
})
}
}
func TestDeleteExpiredMFAs(t *testing.T) {
t.Parallel()
checkDeletedIds := func(app core.App, t *testing.T, expectedDeletedIds []string) {
if err := tests.StubMFARecords(app); err != nil {
t.Fatal(err)
}
deletedIds := []string{}
app.OnRecordDelete().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
if err := app.DeleteExpiredMFAs(); err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(expectedDeletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", expectedDeletedIds, deletedIds)
}
for _, id := range expectedDeletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
}
t.Run("default test collections", func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
checkDeletedIds(app, t, []string{
"user1_0",
"superuser2_1",
"superuser2_4",
})
})
t.Run("mfa collection duration mock", func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
superusers.MFA.Duration = 60
if err := app.Save(superusers); err != nil {
t.Fatalf("Failed to mock superusers mfa duration: %v", err)
}
checkDeletedIds(app, t, []string{
"user1_0",
"superuser2_1",
"superuser2_2",
"superuser2_4",
"superuser3_1",
})
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_select.go | core/field_select.go | package core
import (
"context"
"database/sql/driver"
"slices"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
Fields[FieldTypeSelect] = func() Field {
return &SelectField{}
}
}
const FieldTypeSelect = "select"
var (
_ Field = (*SelectField)(nil)
_ MultiValuer = (*SelectField)(nil)
_ DriverValuer = (*SelectField)(nil)
_ SetterFinder = (*SelectField)(nil)
)
// SelectField defines "select" type field for storing single or
// multiple string values from a predefined list.
//
// Requires the Values option to be set.
//
// If MaxSelect is not set or <= 1, then the field value is expected to be a single Values element.
//
// If MaxSelect is > 1, then the field value is expected to be a subset of Values slice.
//
// The respective zero record field value is either empty string (single) or empty string slice (multiple).
//
// ---
//
// The following additional setter keys are available:
//
// - "fieldName+" - append one or more values to the existing record one. For example:
//
// record.Set("roles+", []string{"new1", "new2"}) // []string{"old1", "old2", "new1", "new2"}
//
// - "+fieldName" - prepend one or more values to the existing record one. For example:
//
// record.Set("+roles", []string{"new1", "new2"}) // []string{"new1", "new2", "old1", "old2"}
//
// - "fieldName-" - subtract one or more values from the existing record one. For example:
//
// record.Set("roles-", "old1") // []string{"old2"}
type SelectField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Values specifies the list of accepted values.
Values []string `form:"values" json:"values"`
// MaxSelect specifies the max allowed selected values.
//
// For multiple select the value must be > 1, otherwise fallbacks to single (default).
MaxSelect int `form:"maxSelect" json:"maxSelect"`
// Required will require the field value to be non-empty.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *SelectField) Type() string {
return FieldTypeSelect
}
// GetId implements [Field.GetId] interface method.
func (f *SelectField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *SelectField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *SelectField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *SelectField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *SelectField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *SelectField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *SelectField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *SelectField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// IsMultiple implements [MultiValuer] interface and checks whether the
// current field options support multiple values.
func (f *SelectField) IsMultiple() bool {
return f.MaxSelect > 1
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *SelectField) ColumnType(app App) string {
if f.IsMultiple() {
return "JSON DEFAULT '[]' NOT NULL"
}
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *SelectField) PrepareValue(record *Record, raw any) (any, error) {
return f.normalizeValue(raw), nil
}
func (f *SelectField) normalizeValue(raw any) any {
val := list.ToUniqueStringSlice(raw)
if !f.IsMultiple() {
if len(val) > 0 {
return val[len(val)-1] // the last selected
}
return ""
}
return val
}
// DriverValue implements the [DriverValuer] interface.
func (f *SelectField) DriverValue(record *Record) (driver.Value, error) {
val := list.ToUniqueStringSlice(record.GetRaw(f.Name))
if !f.IsMultiple() {
if len(val) > 0 {
return val[len(val)-1], nil // the last selected
}
return "", nil
}
// serialize as json string array
return append(types.JSONArray[string]{}, val...), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *SelectField) ValidateValue(ctx context.Context, app App, record *Record) error {
normalizedVal := list.ToUniqueStringSlice(record.GetRaw(f.Name))
if len(normalizedVal) == 0 {
if f.Required {
return validation.ErrRequired
}
return nil // nothing to check
}
maxSelect := max(f.MaxSelect, 1)
// check max selected items
if len(normalizedVal) > maxSelect {
return validation.NewError("validation_too_many_values", "Select no more than {{.maxSelect}}").
SetParams(map[string]any{"maxSelect": maxSelect})
}
// check against the allowed values
for _, val := range normalizedVal {
if !slices.Contains(f.Values, val) {
return validation.NewError("validation_invalid_value", "Invalid value {{.value}}").
SetParams(map[string]any{"value": val})
}
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *SelectField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
max := len(f.Values)
if max == 0 {
max = 1
}
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.Values, validation.Required),
validation.Field(&f.MaxSelect, validation.Min(0), validation.Max(max)),
)
}
// FindSetter implements the [SetterFinder] interface.
func (f *SelectField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return f.setValue
case "+" + f.Name:
return f.prependValue
case f.Name + "+":
return f.appendValue
case f.Name + "-":
return f.subtractValue
default:
return nil
}
}
func (f *SelectField) setValue(record *Record, raw any) {
record.SetRaw(f.Name, f.normalizeValue(raw))
}
func (f *SelectField) appendValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = append(
list.ToUniqueStringSlice(val),
list.ToUniqueStringSlice(modifierValue)...,
)
f.setValue(record, val)
}
func (f *SelectField) prependValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = append(
list.ToUniqueStringSlice(modifierValue),
list.ToUniqueStringSlice(val)...,
)
f.setValue(record, val)
}
func (f *SelectField) subtractValue(record *Record, modifierValue any) {
val := record.GetRaw(f.Name)
val = list.SubtractSlice(
list.ToUniqueStringSlice(val),
list.ToUniqueStringSlice(modifierValue),
)
f.setValue(record, val)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/syscall_wasm.go | core/syscall_wasm.go | //go:build js && wasm
package core
import "errors"
// https://github.com/pocketbase/pocketbase/pull/7116
func execve(argv0 string, argv []string, envv []string) error {
return errors.ErrUnsupported
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/external_auth_query_test.go | core/external_auth_query_test.go | package core_test
import (
"fmt"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestFindAllExternalAuthsByRecord(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser1, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if err != nil {
t.Fatal(err)
}
user1, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
user2, err := app.FindAuthRecordByEmail("users", "test2@example.com")
if err != nil {
t.Fatal(err)
}
user3, err := app.FindAuthRecordByEmail("users", "test3@example.com")
if err != nil {
t.Fatal(err)
}
client1, err := app.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
expected []string
}{
{demo1, nil},
{superuser1, nil},
{client1, []string{"f1z5b3843pzc964"}},
{user1, []string{"clmflokuq1xl341", "dlmflokuq1xl342"}},
{user2, nil},
{user3, []string{"5eto7nmys833164"}},
}
for _, s := range scenarios {
t.Run(s.record.Collection().Name+"_"+s.record.Id, func(t *testing.T) {
result, err := app.FindAllExternalAuthsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total models %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindAllExternalAuthsByCollection(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
clients, err := app.FindCollectionByNameOrId("clients")
if err != nil {
t.Fatal(err)
}
users, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
collection *core.Collection
expected []string
}{
{demo1, nil},
{superusers, nil},
{clients, []string{
"f1z5b3843pzc964",
}},
{users, []string{
"5eto7nmys833164",
"clmflokuq1xl341",
"dlmflokuq1xl342",
}},
}
for _, s := range scenarios {
t.Run(s.collection.Name, func(t *testing.T) {
result, err := app.FindAllExternalAuthsByCollection(s.collection)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total models %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindFirstExternalAuthByExpr(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
expr dbx.Expression
expectedId string
}{
{dbx.HashExp{"collectionRef": "invalid"}, ""},
{dbx.HashExp{"collectionRef": "_pb_users_auth_"}, "5eto7nmys833164"},
{dbx.HashExp{"collectionRef": "_pb_users_auth_", "provider": "gitlab"}, "dlmflokuq1xl342"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%v", i, s.expr.Build(app.ConcurrentDB().(*dbx.DB), dbx.Params{})), func(t *testing.T) {
result, err := app.FindFirstExternalAuthByExpr(s.expr)
hasErr := err != nil
expectErr := s.expectedId == ""
if hasErr != expectErr {
t.Fatalf("Expected hasErr %v, got %v", expectErr, hasErr)
}
if hasErr {
return
}
if result.Id != s.expectedId {
t.Errorf("Expected id %q, got %q", s.expectedId, result.Id)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/migrations_runner_test.go | core/migrations_runner_test.go | package core_test
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestMigrationsRunnerUpAndDown(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
callsOrder := []string{}
l := core.MigrationsList{}
l.Register(func(app core.App) error {
callsOrder = append(callsOrder, "up2")
return nil
}, func(app core.App) error {
callsOrder = append(callsOrder, "down2")
return nil
}, "2_test")
l.Register(func(app core.App) error {
callsOrder = append(callsOrder, "up3")
return nil
}, func(app core.App) error {
callsOrder = append(callsOrder, "down3")
return nil
}, "3_test")
l.Register(func(app core.App) error {
callsOrder = append(callsOrder, "up1")
return nil
}, func(app core.App) error {
callsOrder = append(callsOrder, "down1")
return nil
}, "1_test")
l.Register(func(app core.App) error {
callsOrder = append(callsOrder, "up4")
return nil
}, func(app core.App) error {
callsOrder = append(callsOrder, "down4")
return nil
}, "4_test")
l.Add(&core.Migration{
Up: func(app core.App) error {
callsOrder = append(callsOrder, "up5")
return nil
},
Down: func(app core.App) error {
callsOrder = append(callsOrder, "down5")
return nil
},
File: "5_test",
ReapplyCondition: func(txApp core.App, runner *core.MigrationsRunner, fileName string) (bool, error) {
return true, nil
},
})
runner := core.NewMigrationsRunner(app, l)
// ---------------------------------------------------------------
// simulate partially out-of-order applied migration
// ---------------------------------------------------------------
_, err := app.DB().Insert(core.DefaultMigrationsTable, dbx.Params{
"file": "4_test",
"applied": time.Now().UnixMicro() - 2,
}).Execute()
if err != nil {
t.Fatalf("Failed to insert 5_test migration: %v", err)
}
_, err = app.DB().Insert(core.DefaultMigrationsTable, dbx.Params{
"file": "5_test",
"applied": time.Now().UnixMicro() - 1,
}).Execute()
if err != nil {
t.Fatalf("Failed to insert 5_test migration: %v", err)
}
_, err = app.DB().Insert(core.DefaultMigrationsTable, dbx.Params{
"file": "2_test",
"applied": time.Now().UnixMicro(),
}).Execute()
if err != nil {
t.Fatalf("Failed to insert 2_test migration: %v", err)
}
// ---------------------------------------------------------------
// Up()
// ---------------------------------------------------------------
if _, err := runner.Up(); err != nil {
t.Fatal(err)
}
expectedUpCallsOrder := `["up1","up3","up5"]` // skip up2 and up4 since they were applied already (up5 has extra reapply condition)
upCallsOrder, err := json.Marshal(callsOrder)
if err != nil {
t.Fatal(err)
}
if v := string(upCallsOrder); v != expectedUpCallsOrder {
t.Fatalf("Expected Up() calls order %s, got %s", expectedUpCallsOrder, upCallsOrder)
}
// ---------------------------------------------------------------
// reset callsOrder
callsOrder = []string{}
// simulate unrun migration
l.Register(nil, func(app core.App) error {
callsOrder = append(callsOrder, "down6")
return nil
}, "6_test")
// simulate applied migrations from different migrations list
_, err = app.DB().Insert(core.DefaultMigrationsTable, dbx.Params{
"file": "from_different_list",
"applied": time.Now().UnixMicro(),
}).Execute()
if err != nil {
t.Fatalf("Failed to insert from_different_list migration: %v", err)
}
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// Down()
// ---------------------------------------------------------------
if _, err := runner.Down(2); err != nil {
t.Fatal(err)
}
expectedDownCallsOrder := `["down5","down3"]` // revert in the applied order
downCallsOrder, err := json.Marshal(callsOrder)
if err != nil {
t.Fatal(err)
}
if v := string(downCallsOrder); v != expectedDownCallsOrder {
t.Fatalf("Expected Down() calls order %s, got %s", expectedDownCallsOrder, downCallsOrder)
}
}
func TestMigrationsRunnerRemoveMissingAppliedMigrations(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
// mock migrations history
for i := 1; i <= 3; i++ {
_, err := app.DB().Insert(core.DefaultMigrationsTable, dbx.Params{
"file": fmt.Sprintf("%d_test", i),
"applied": time.Now().UnixMicro(),
}).Execute()
if err != nil {
t.Fatal(err)
}
}
if !isMigrationApplied(app, "2_test") {
t.Fatalf("Expected 2_test migration to be applied")
}
// create a runner without 2_test to mock deleted migration
l := core.MigrationsList{}
l.Register(func(app core.App) error {
return nil
}, func(app core.App) error {
return nil
}, "1_test")
l.Register(func(app core.App) error {
return nil
}, func(app core.App) error {
return nil
}, "3_test")
r := core.NewMigrationsRunner(app, l)
if err := r.RemoveMissingAppliedMigrations(); err != nil {
t.Fatalf("Failed to remove missing applied migrations: %v", err)
}
if isMigrationApplied(app, "2_test") {
t.Fatalf("Expected 2_test migration to NOT be applied")
}
}
func isMigrationApplied(app core.App, file string) bool {
var exists int
err := app.DB().Select("(1)").
From(core.DefaultMigrationsTable).
Where(dbx.HashExp{"file": file}).
Limit(1).
Row(&exists)
return err == nil && exists > 0
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_autodate_test.go | core/field_autodate_test.go | package core_test
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestAutodateFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeAutodate)
}
func TestAutodateFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.AutodateField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestAutodateFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.AutodateField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"invalid", ""},
{"2024-01-01 00:11:22.345Z", "2024-01-01 00:11:22.345Z"},
{time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC), "2024-01-02 03:04:05.000Z"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vDate, ok := v.(types.DateTime)
if !ok {
t.Fatalf("Expected types.DateTime instance, got %T", v)
}
if vDate.String() != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestAutodateFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.AutodateField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.AutodateField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
false,
},
{
"missing field value",
&core.AutodateField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("abc", true)
return record
},
false,
},
{
"existing field value",
&core.AutodateField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.NowDateTime())
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestAutodateFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeAutodate)
testDefaultFieldNameValidation(t, core.FieldTypeAutodate)
app, _ := tests.NewTestApp()
defer app.Cleanup()
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
field func() *core.AutodateField
expectErrors []string
}{
{
"empty onCreate and onUpdate",
func() *core.AutodateField {
return &core.AutodateField{
Id: "test",
Name: "test",
}
},
[]string{"onCreate", "onUpdate"},
},
{
"with onCreate",
func() *core.AutodateField {
return &core.AutodateField{
Id: "test",
Name: "test",
OnCreate: true,
}
},
[]string{},
},
{
"with onUpdate",
func() *core.AutodateField {
return &core.AutodateField{
Id: "test",
Name: "test",
OnUpdate: true,
}
},
[]string{},
},
{
"change of a system autodate field",
func() *core.AutodateField {
created := superusers.Fields.GetByName("created").(*core.AutodateField)
created.OnCreate = !created.OnCreate
created.OnUpdate = !created.OnUpdate
return created
},
[]string{"onCreate", "onUpdate"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, superusers)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestAutodateFieldFindSetter(t *testing.T) {
field := &core.AutodateField{Name: "test"}
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(field)
initialDate, err := types.ParseDateTime("2024-01-02 03:04:05.789Z")
if err != nil {
t.Fatal(err)
}
record := core.NewRecord(collection)
record.SetRaw("test", initialDate)
t.Run("no matching setter", func(t *testing.T) {
f := field.FindSetter("abc")
if f != nil {
t.Fatal("Expected nil setter")
}
})
t.Run("matching setter", func(t *testing.T) {
f := field.FindSetter("test")
if f == nil {
t.Fatal("Expected non-nil setter")
}
f(record, types.NowDateTime()) // should be ignored
if v := record.GetString("test"); v != "2024-01-02 03:04:05.789Z" {
t.Fatalf("Expected no value change, got %q", v)
}
})
}
func cutMilliseconds(datetime string) string {
if len(datetime) > 19 {
return datetime[:19]
}
return datetime
}
func TestAutodateFieldIntercept(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
initialDate, err := types.ParseDateTime("2024-01-02 03:04:05.789Z")
if err != nil {
t.Fatal(err)
}
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
actionName string
field *core.AutodateField
record func() *core.Record
expected string
}{
{
"non-matching action",
"test",
&core.AutodateField{Name: "test", OnCreate: true, OnUpdate: true},
func() *core.Record {
return core.NewRecord(collection)
},
"",
},
{
"create with zero value (disabled onCreate)",
core.InterceptorActionCreateExecute,
&core.AutodateField{Name: "test", OnCreate: false, OnUpdate: true},
func() *core.Record {
return core.NewRecord(collection)
},
"",
},
{
"create with zero value",
core.InterceptorActionCreateExecute,
&core.AutodateField{Name: "test", OnCreate: true, OnUpdate: true},
func() *core.Record {
return core.NewRecord(collection)
},
"{NOW}",
},
{
"create with non-zero value",
core.InterceptorActionCreateExecute,
&core.AutodateField{Name: "test", OnCreate: true, OnUpdate: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", initialDate)
return record
},
initialDate.String(),
},
{
"update with zero value (disabled onUpdate)",
core.InterceptorActionUpdateExecute,
&core.AutodateField{Name: "test", OnCreate: true, OnUpdate: false},
func() *core.Record {
return core.NewRecord(collection)
},
"",
},
{
"update with zero value",
core.InterceptorActionUpdateExecute,
&core.AutodateField{Name: "test", OnCreate: true, OnUpdate: true},
func() *core.Record {
return core.NewRecord(collection)
},
"{NOW}",
},
{
"update with non-zero value",
core.InterceptorActionUpdateExecute,
&core.AutodateField{Name: "test", OnCreate: true, OnUpdate: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", initialDate)
return record
},
initialDate.String(),
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
actionCalls := 0
record := s.record()
now := types.NowDateTime().String()
err := s.field.Intercept(context.Background(), app, record, s.actionName, func() error {
actionCalls++
return nil
})
if err != nil {
t.Fatal(err)
}
if actionCalls != 1 {
t.Fatalf("Expected actionCalls %d, got %d", 1, actionCalls)
}
expected := cutMilliseconds(strings.ReplaceAll(s.expected, "{NOW}", now))
v := cutMilliseconds(record.GetString(s.field.GetName()))
if v != expected {
t.Fatalf("Expected value %q, got %q", expected, v)
}
})
}
}
func TestAutodateRecordResave(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
t.Fatal(err)
}
record, err := app.FindRecordById(collection, "llvuca81nly1qls")
if err != nil {
t.Fatal(err)
}
lastUpdated := record.GetDateTime("updated")
// save with autogenerated date
err = app.Save(record)
if err != nil {
t.Fatal(err)
}
newUpdated := record.GetDateTime("updated")
if newUpdated.Equal(lastUpdated) {
t.Fatalf("[0] Expected updated to change, got %v", newUpdated)
}
lastUpdated = newUpdated
// save with custom date
manualUpdated := lastUpdated.Add(-1 * time.Minute)
record.SetRaw("updated", manualUpdated)
err = app.Save(record)
if err != nil {
t.Fatal(err)
}
newUpdated = record.GetDateTime("updated")
if !newUpdated.Equal(manualUpdated) {
t.Fatalf("[1] Expected updated to be the manual set date %v, got %v", manualUpdated, newUpdated)
}
lastUpdated = newUpdated
// save again with autogenerated date
err = app.Save(record)
if err != nil {
t.Fatal(err)
}
newUpdated = record.GetDateTime("updated")
if newUpdated.Equal(lastUpdated) {
t.Fatalf("[2] Expected updated to change, got %v", newUpdated)
}
lastUpdated = newUpdated
// simulate save failure
app.OnRecordUpdateExecute(collection.Id).Bind(&hook.Handler[*core.RecordEvent]{
Id: "test_failure",
Func: func(*core.RecordEvent) error {
return errors.New("test")
},
Priority: 9999999999, // as latest as possible
})
// save again with autogenerated date (should fail)
err = app.Save(record)
if err == nil {
t.Fatal("Expected save failure")
}
// updated should still be set even after save failure
newUpdated = record.GetDateTime("updated")
if newUpdated.Equal(lastUpdated) {
t.Fatalf("[3] Expected updated to change, got %v", newUpdated)
}
lastUpdated = newUpdated
// cleanup the error and resave again
app.OnRecordUpdateExecute(collection.Id).Unbind("test_failure")
err = app.Save(record)
if err != nil {
t.Fatal(err)
}
newUpdated = record.GetDateTime("updated")
if newUpdated.Equal(lastUpdated) {
t.Fatalf("[4] Expected updated to change, got %v", newUpdated)
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_url_test.go | core/field_url_test.go | package core_test
import (
"context"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestURLFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeURL)
}
func TestURLFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.URLField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestURLFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.URLField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"test", "test"},
{false, "false"},
{true, "true"},
{123.456, "123.456"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vStr, ok := v.(string)
if !ok {
t.Fatalf("Expected string instance, got %T", v)
}
if vStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, v)
}
})
}
}
func TestURLFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.URLField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.URLField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (not required)",
&core.URLField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
false,
},
{
"zero field value (required)",
&core.URLField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"non-zero field value (required)",
&core.URLField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "https://example.com")
return record
},
false,
},
{
"invalid url",
&core.URLField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "invalid")
return record
},
true,
},
{
"failed onlyDomains",
&core.URLField{Name: "test", OnlyDomains: []string{"example.org", "example.net"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "https://example.com")
return record
},
true,
},
{
"success onlyDomains",
&core.URLField{Name: "test", OnlyDomains: []string{"example.org", "example.com"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "https://example.com")
return record
},
false,
},
{
"failed exceptDomains",
&core.URLField{Name: "test", ExceptDomains: []string{"example.org", "example.com"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "https://example.com")
return record
},
true,
},
{
"success exceptDomains",
&core.URLField{Name: "test", ExceptDomains: []string{"example.org", "example.net"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "https://example.com")
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestURLFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeURL)
testDefaultFieldNameValidation(t, core.FieldTypeURL)
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() *core.URLField
expectErrors []string
}{
{
"zero minimal",
func() *core.URLField {
return &core.URLField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"both onlyDomains and exceptDomains",
func() *core.URLField {
return &core.URLField{
Id: "test",
Name: "test",
OnlyDomains: []string{"example.com"},
ExceptDomains: []string{"example.org"},
}
},
[]string{"onlyDomains", "exceptDomains"},
},
{
"invalid onlyDomains",
func() *core.URLField {
return &core.URLField{
Id: "test",
Name: "test",
OnlyDomains: []string{"example.com", "invalid"},
}
},
[]string{"onlyDomains"},
},
{
"valid onlyDomains",
func() *core.URLField {
return &core.URLField{
Id: "test",
Name: "test",
OnlyDomains: []string{"example.com", "example.org"},
}
},
[]string{},
},
{
"invalid exceptDomains",
func() *core.URLField {
return &core.URLField{
Id: "test",
Name: "test",
ExceptDomains: []string{"example.com", "invalid"},
}
},
[]string{"exceptDomains"},
},
{
"valid exceptDomains",
func() *core.URLField {
return &core.URLField{
Id: "test",
Name: "test",
ExceptDomains: []string{"example.com", "example.org"},
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_date_test.go | core/field_date_test.go | package core_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestDateFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeDate)
}
func TestDateFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.DateField{}
expected := "TEXT DEFAULT '' NOT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestDateFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.DateField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"", ""},
{"invalid", ""},
{"2024-01-01 00:11:22.345Z", "2024-01-01 00:11:22.345Z"},
{time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC), "2024-01-02 03:04:05.000Z"},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vDate, ok := v.(types.DateTime)
if !ok {
t.Fatalf("Expected types.DateTime instance, got %T", v)
}
if vDate.String() != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestDateFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.DateField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.DateField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (not required)",
&core.DateField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.DateTime{})
return record
},
false,
},
{
"zero field value (required)",
&core.DateField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.DateTime{})
return record
},
true,
},
{
"non-zero field value (required)",
&core.DateField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.NowDateTime())
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestDateFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeDate)
testDefaultFieldNameValidation(t, core.FieldTypeDate)
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() *core.DateField
expectErrors []string
}{
{
"zero Min/Max",
func() *core.DateField {
return &core.DateField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"non-empty Min with empty Max",
func() *core.DateField {
return &core.DateField{
Id: "test",
Name: "test",
Min: types.NowDateTime(),
}
},
[]string{},
},
{
"empty Min non-empty Max",
func() *core.DateField {
return &core.DateField{
Id: "test",
Name: "test",
Max: types.NowDateTime(),
}
},
[]string{},
},
{
"Min = Max",
func() *core.DateField {
date := types.NowDateTime()
return &core.DateField{
Id: "test",
Name: "test",
Min: date,
Max: date,
}
},
[]string{},
},
{
"Min > Max",
func() *core.DateField {
min := types.NowDateTime()
max := min.Add(-5 * time.Second)
return &core.DateField{
Id: "test",
Name: "test",
Min: min,
Max: max,
}
},
[]string{},
},
{
"Min < Max",
func() *core.DateField {
max := types.NowDateTime()
min := max.Add(-5 * time.Second)
return &core.DateField{
Id: "test",
Name: "test",
Min: min,
Max: max,
}
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/settings_model.go | core/settings_model.go | package core
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/pocketbase/pocketbase/tools/cron"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
)
const (
paramsTable = "_params"
paramsKeySettings = "settings"
systemHookIdSettings = "__pbSettingsSystemHook__"
)
func (app *BaseApp) registerSettingsHooks() {
saveFunc := func(me *ModelEvent) error {
if err := me.Next(); err != nil {
return err
}
if me.Model.PK() == paramsKeySettings {
// auto reload the app settings because we don't know whether
// the Settings model is the app one or a different one
return errors.Join(
me.App.Settings().PostScan(),
me.App.ReloadSettings(),
)
}
return nil
}
app.OnModelAfterCreateSuccess(paramsTable).Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdSettings,
Func: saveFunc,
Priority: -999,
})
app.OnModelAfterUpdateSuccess(paramsTable).Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdSettings,
Func: saveFunc,
Priority: -999,
})
app.OnModelDelete(paramsTable).Bind(&hook.Handler[*ModelEvent]{
Id: systemHookIdSettings,
Func: func(me *ModelEvent) error {
if me.Model.PK() == paramsKeySettings {
return errors.New("the app params settings cannot be deleted")
}
return me.Next()
},
Priority: -999,
})
app.OnCollectionUpdate().Bind(&hook.Handler[*CollectionEvent]{
Id: systemHookIdSettings,
Func: func(e *CollectionEvent) error {
oldCollection, err := e.App.FindCachedCollectionByNameOrId(e.Collection.Id)
if err != nil {
return fmt.Errorf("failed to retrieve old cached collection: %w", err)
}
err = e.Next()
if err != nil {
return err
}
// update existing rate limit rules on collection rename
if oldCollection.Name != e.Collection.Name {
var hasChange bool
rules := e.App.Settings().RateLimits.Rules
for i := 0; i < len(rules); i++ {
if strings.HasPrefix(rules[i].Label, oldCollection.Name+":") {
rules[i].Label = strings.Replace(rules[i].Label, oldCollection.Name+":", e.Collection.Name+":", 1)
hasChange = true
}
}
if hasChange {
e.App.Settings().RateLimits.Rules = rules
err = e.App.Save(e.App.Settings())
if err != nil {
return err
}
}
}
return nil
},
Priority: 99,
})
}
var (
_ Model = (*Settings)(nil)
_ PostValidator = (*Settings)(nil)
_ DBExporter = (*Settings)(nil)
)
type settings struct {
SMTP SMTPConfig `form:"smtp" json:"smtp"`
Backups BackupsConfig `form:"backups" json:"backups"`
S3 S3Config `form:"s3" json:"s3"`
Meta MetaConfig `form:"meta" json:"meta"`
RateLimits RateLimitsConfig `form:"rateLimits" json:"rateLimits"`
TrustedProxy TrustedProxyConfig `form:"trustedProxy" json:"trustedProxy"`
Batch BatchConfig `form:"batch" json:"batch"`
Logs LogsConfig `form:"logs" json:"logs"`
}
// Settings defines the PocketBase app settings.
type Settings struct {
settings
mu sync.RWMutex
isNew bool
}
func newDefaultSettings() *Settings {
return &Settings{
isNew: true,
settings: settings{
Meta: MetaConfig{
AppName: "Acme",
AppURL: "http://localhost:8090",
HideControls: false,
SenderName: "Support",
SenderAddress: "support@example.com",
},
Logs: LogsConfig{
MaxDays: 5,
LogIP: true,
},
SMTP: SMTPConfig{
Enabled: false,
Host: "smtp.example.com",
Port: 587,
Username: "",
Password: "",
TLS: false,
},
Backups: BackupsConfig{
CronMaxKeep: 3,
},
Batch: BatchConfig{
Enabled: false,
MaxRequests: 50,
Timeout: 3,
},
RateLimits: RateLimitsConfig{
Enabled: false, // @todo once tested enough enable by default for new installations
Rules: []RateLimitRule{
{Label: "*:auth", MaxRequests: 2, Duration: 3},
{Label: "*:create", MaxRequests: 20, Duration: 5},
{Label: "/api/batch", MaxRequests: 3, Duration: 1},
{Label: "/api/", MaxRequests: 300, Duration: 10},
},
},
},
}
}
// TableName implements [Model.TableName] interface method.
func (s *Settings) TableName() string {
return paramsTable
}
// PK implements [Model.LastSavedPK] interface method.
func (s *Settings) LastSavedPK() any {
return paramsKeySettings
}
// PK implements [Model.PK] interface method.
func (s *Settings) PK() any {
return paramsKeySettings
}
// IsNew implements [Model.IsNew] interface method.
func (s *Settings) IsNew() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.isNew
}
// MarkAsNew implements [Model.MarkAsNew] interface method.
func (s *Settings) MarkAsNew() {
s.mu.Lock()
defer s.mu.Unlock()
s.isNew = true
}
// MarkAsNew implements [Model.MarkAsNotNew] interface method.
func (s *Settings) MarkAsNotNew() {
s.mu.Lock()
defer s.mu.Unlock()
s.isNew = false
}
// PostScan implements [Model.PostScan] interface method.
func (s *Settings) PostScan() error {
s.MarkAsNotNew()
return nil
}
// String returns a serialized string representation of the current settings.
func (s *Settings) String() string {
s.mu.RLock()
defer s.mu.RUnlock()
raw, _ := json.Marshal(s)
return string(raw)
}
// DBExport prepares and exports the current settings for db persistence.
func (s *Settings) DBExport(app App) (map[string]any, error) {
s.mu.RLock()
defer s.mu.RUnlock()
now := types.NowDateTime()
result := map[string]any{
"id": s.PK(),
}
if s.IsNew() {
result["created"] = now
}
result["updated"] = now
encoded, err := json.Marshal(s.settings)
if err != nil {
return nil, err
}
encryptionKey := os.Getenv(app.EncryptionEnv())
if encryptionKey != "" {
encryptVal, encryptErr := security.Encrypt(encoded, encryptionKey)
if encryptErr != nil {
return nil, encryptErr
}
result["value"] = encryptVal
} else {
result["value"] = encoded
}
return result, nil
}
// PostValidate implements the [PostValidator] interface and defines
// the Settings model validations.
func (s *Settings) PostValidate(ctx context.Context, app App) error {
s.mu.RLock()
defer s.mu.RUnlock()
return validation.ValidateStructWithContext(ctx, s,
validation.Field(&s.Meta),
validation.Field(&s.Logs),
validation.Field(&s.SMTP),
validation.Field(&s.S3),
validation.Field(&s.Backups),
validation.Field(&s.Batch),
validation.Field(&s.RateLimits),
validation.Field(&s.TrustedProxy),
)
}
// Merge merges the "other" settings into the current one.
func (s *Settings) Merge(other *Settings) error {
other.mu.RLock()
defer other.mu.RUnlock()
raw, err := json.Marshal(other.settings)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
return json.Unmarshal(raw, &s)
}
// Clone creates a new deep copy of the current settings.
func (s *Settings) Clone() (*Settings, error) {
clone := &Settings{
isNew: s.isNew,
}
if err := clone.Merge(s); err != nil {
return nil, err
}
return clone, nil
}
// MarshalJSON implements the [json.Marshaler] interface.
//
// Note that sensitive fields (S3 secret, SMTP password, etc.) are excluded.
func (s *Settings) MarshalJSON() ([]byte, error) {
s.mu.RLock()
copy := s.settings
s.mu.RUnlock()
sensitiveFields := []*string{
©.SMTP.Password,
©.S3.Secret,
©.Backups.S3.Secret,
}
// mask all sensitive fields
for _, v := range sensitiveFields {
if v != nil && *v != "" {
*v = ""
}
}
return json.Marshal(copy)
}
// -------------------------------------------------------------------
type SMTPConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
Port int `form:"port" json:"port"`
Host string `form:"host" json:"host"`
Username string `form:"username" json:"username"`
Password string `form:"password" json:"password,omitempty"`
// SMTP AUTH - PLAIN (default) or LOGIN
AuthMethod string `form:"authMethod" json:"authMethod"`
// Whether to enforce TLS encryption for the mail server connection.
//
// When set to false StartTLS command is send, leaving the server
// to decide whether to upgrade the connection or not.
TLS bool `form:"tls" json:"tls"`
// LocalName is optional domain name or IP address used for the
// EHLO/HELO exchange (if not explicitly set, defaults to "localhost").
//
// This is required only by some SMTP servers, such as Gmail SMTP-relay.
LocalName string `form:"localName" json:"localName"`
}
// Validate makes SMTPConfig validatable by implementing [validation.Validatable] interface.
func (c SMTPConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(
&c.Host,
validation.When(c.Enabled, validation.Required),
is.Host,
),
validation.Field(
&c.Port,
validation.When(c.Enabled, validation.Required),
validation.Min(0),
),
validation.Field(
&c.AuthMethod,
// don't require it for backward compatibility
// (fallback internally to PLAIN)
// validation.When(c.Enabled, validation.Required),
validation.In(mailer.SMTPAuthLogin, mailer.SMTPAuthPlain),
),
validation.Field(&c.LocalName, is.Host),
)
}
// -------------------------------------------------------------------
type S3Config struct {
Enabled bool `form:"enabled" json:"enabled"`
Bucket string `form:"bucket" json:"bucket"`
Region string `form:"region" json:"region"`
Endpoint string `form:"endpoint" json:"endpoint"`
AccessKey string `form:"accessKey" json:"accessKey"`
Secret string `form:"secret" json:"secret,omitempty"`
ForcePathStyle bool `form:"forcePathStyle" json:"forcePathStyle"`
}
// Validate makes S3Config validatable by implementing [validation.Validatable] interface.
func (c S3Config) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Endpoint, is.URL, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.Bucket, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.Region, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.AccessKey, validation.When(c.Enabled, validation.Required)),
validation.Field(&c.Secret, validation.When(c.Enabled, validation.Required)),
)
}
// -------------------------------------------------------------------
type BatchConfig struct {
Enabled bool `form:"enabled" json:"enabled"`
// MaxRequests is the maximum allowed batch request to execute.
MaxRequests int `form:"maxRequests" json:"maxRequests"`
// Timeout is the the max duration in seconds to wait before cancelling the batch transaction.
Timeout int64 `form:"timeout" json:"timeout"`
// MaxBodySize is the maximum allowed batch request body size in bytes.
//
// If not set, fallbacks to max ~128MB.
MaxBodySize int64 `form:"maxBodySize" json:"maxBodySize"`
}
// Validate makes BatchConfig validatable by implementing [validation.Validatable] interface.
func (c BatchConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.MaxRequests, validation.When(c.Enabled, validation.Required), validation.Min(0)),
validation.Field(&c.Timeout, validation.When(c.Enabled, validation.Required), validation.Min(0)),
validation.Field(&c.MaxBodySize, validation.Min(0)),
)
}
// -------------------------------------------------------------------
type BackupsConfig struct {
// Cron is a cron expression to schedule auto backups, eg. "* * * * *".
//
// Leave it empty to disable the auto backups functionality.
Cron string `form:"cron" json:"cron"`
// CronMaxKeep is the the max number of cron generated backups to
// keep before removing older entries.
//
// This field works only when the cron config has valid cron expression.
CronMaxKeep int `form:"cronMaxKeep" json:"cronMaxKeep"`
// S3 is an optional S3 storage config specifying where to store the app backups.
S3 S3Config `form:"s3" json:"s3"`
}
// Validate makes BackupsConfig validatable by implementing [validation.Validatable] interface.
func (c BackupsConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.S3),
validation.Field(&c.Cron, validation.By(checkCronExpression)),
validation.Field(
&c.CronMaxKeep,
validation.When(c.Cron != "", validation.Required),
validation.Min(1),
),
)
}
func checkCronExpression(value any) error {
v, _ := value.(string)
if v == "" {
return nil // nothing to check
}
_, err := cron.NewSchedule(v)
if err != nil {
return validation.NewError("validation_invalid_cron", err.Error())
}
return nil
}
// -------------------------------------------------------------------
type MetaConfig struct {
AppName string `form:"appName" json:"appName"`
AppURL string `form:"appURL" json:"appURL"`
SenderName string `form:"senderName" json:"senderName"`
SenderAddress string `form:"senderAddress" json:"senderAddress"`
HideControls bool `form:"hideControls" json:"hideControls"`
}
// Validate makes MetaConfig validatable by implementing [validation.Validatable] interface.
func (c MetaConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.AppName, validation.Required, validation.Length(1, 255)),
validation.Field(&c.AppURL, validation.Required, is.URL),
validation.Field(&c.SenderName, validation.Required, validation.Length(1, 255)),
validation.Field(&c.SenderAddress, is.EmailFormat, validation.Required),
)
}
// -------------------------------------------------------------------
type LogsConfig struct {
MaxDays int `form:"maxDays" json:"maxDays"`
MinLevel int `form:"minLevel" json:"minLevel"`
LogIP bool `form:"logIP" json:"logIP"`
LogAuthId bool `form:"logAuthId" json:"logAuthId"`
}
// Validate makes LogsConfig validatable by implementing [validation.Validatable] interface.
func (c LogsConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.MaxDays, validation.Min(0)),
)
}
// -------------------------------------------------------------------
type TrustedProxyConfig struct {
// Headers is a list of explicit trusted header(s) to check.
Headers []string `form:"headers" json:"headers"`
// UseLeftmostIP specifies to use the left-mostish IP from the trusted headers.
//
// Note that this could be insecure when used with X-Forwarded-For header
// because some proxies like AWS ELB allow users to prepend their own header value
// before appending the trusted ones.
UseLeftmostIP bool `form:"useLeftmostIP" json:"useLeftmostIP"`
}
// MarshalJSON implements the [json.Marshaler] interface.
func (c TrustedProxyConfig) MarshalJSON() ([]byte, error) {
type alias TrustedProxyConfig
// serialize as empty array
if c.Headers == nil {
c.Headers = []string{}
}
return json.Marshal(alias(c))
}
// Validate makes RateLimitRule validatable by implementing [validation.Validatable] interface.
func (c TrustedProxyConfig) Validate() error {
return nil
}
// -------------------------------------------------------------------
type RateLimitsConfig struct {
Rules []RateLimitRule `form:"rules" json:"rules"`
Enabled bool `form:"enabled" json:"enabled"`
}
// FindRateLimitRule returns the first matching rule based on the provided labels.
//
// Optionally you can further specify a list of valid RateLimitRule.Audience values to further filter the matching rule
// (aka. the rule Audience will have to exist in one of the specified options).
func (c *RateLimitsConfig) FindRateLimitRule(searchLabels []string, optOnlyAudience ...string) (RateLimitRule, bool) {
var prefixRules []int
for i, label := range searchLabels {
// check for direct match
for j := range c.Rules {
if label == c.Rules[j].Label &&
(len(optOnlyAudience) == 0 || slices.Contains(optOnlyAudience, c.Rules[j].Audience)) {
return c.Rules[j], true
}
if i == 0 && strings.HasSuffix(c.Rules[j].Label, "/") {
prefixRules = append(prefixRules, j)
}
}
// check for prefix match
if len(prefixRules) > 0 {
for j := range prefixRules {
if strings.HasPrefix(label+"/", c.Rules[prefixRules[j]].Label) &&
(len(optOnlyAudience) == 0 || slices.Contains(optOnlyAudience, c.Rules[prefixRules[j]].Audience)) {
return c.Rules[prefixRules[j]], true
}
}
}
}
return RateLimitRule{}, false
}
// MarshalJSON implements the [json.Marshaler] interface.
func (c RateLimitsConfig) MarshalJSON() ([]byte, error) {
type alias RateLimitsConfig
// serialize as empty array
if c.Rules == nil {
c.Rules = []RateLimitRule{}
}
return json.Marshal(alias(c))
}
// Validate makes RateLimitsConfig validatable by implementing [validation.Validatable] interface.
func (c RateLimitsConfig) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(
&c.Rules,
validation.When(c.Enabled, validation.Required),
validation.By(checkUniqueRuleLabel),
),
)
}
func checkUniqueRuleLabel(value any) error {
rules, ok := value.([]RateLimitRule)
if !ok {
return validators.ErrUnsupportedValueType
}
existing := make([]string, 0, len(rules))
for i, rule := range rules {
fullKey := rule.Label + "@@" + rule.Audience
var conflicts bool
for _, key := range existing {
if strings.HasPrefix(key, fullKey) || strings.HasPrefix(fullKey, key) {
conflicts = true
break
}
}
if conflicts {
return validation.Errors{
strconv.Itoa(i): validation.Errors{
"label": validation.NewError("validation_conflicting_rate_limit_rule", "Rate limit rule configuration with label {{.label}} already exists or conflicts with another rule.").
SetParams(map[string]any{"label": rule.Label}),
},
}
} else {
existing = append(existing, fullKey)
}
}
return nil
}
var rateLimitRuleLabelRegex = regexp.MustCompile(`^(\w+\ \/[\w\/-]*|\/[\w\/-]*|^\w+\:\w+|\*\:\w+|\w+)$`)
// The allowed RateLimitRule.Audience values
const (
RateLimitRuleAudienceAll = ""
RateLimitRuleAudienceGuest = "@guest"
RateLimitRuleAudienceAuth = "@auth"
)
type RateLimitRule struct {
// Label is the identifier of the current rule.
//
// It could be a tag, complete path or path prerefix (when ends with `/`).
//
// Example supported labels:
// - test_a (plain text "tag")
// - users:create
// - *:create
// - /
// - /api
// - POST /api/collections/
Label string `form:"label" json:"label"`
// Audience specifies the auth group the rule should apply for:
// - "" - both guests and authenticated users (default)
// - "@guest" - only for guests
// - "@auth" - only for authenticated users
Audience string `form:"audience" json:"audience"`
// Duration specifies the interval (in seconds) per which to reset
// the counted/accumulated rate limiter tokens.
Duration int64 `form:"duration" json:"duration"`
// MaxRequests is the max allowed number of requests per Duration.
MaxRequests int `form:"maxRequests" json:"maxRequests"`
}
// Validate makes RateLimitRule validatable by implementing [validation.Validatable] interface.
func (c RateLimitRule) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Label, validation.Required, validation.Match(rateLimitRuleLabelRegex)),
validation.Field(&c.MaxRequests, validation.Required, validation.Min(1)),
validation.Field(&c.Duration, validation.Required, validation.Min(1)),
validation.Field(&c.Audience,
validation.In(RateLimitRuleAudienceAll, RateLimitRuleAudienceGuest, RateLimitRuleAudienceAuth),
),
)
}
// DurationTime returns the tag's Duration as [time.Duration].
func (c RateLimitRule) DurationTime() time.Duration {
return time.Duration(c.Duration) * time.Second
}
// String returns a string representation of the rule.
func (c RateLimitRule) String() string {
raw, err := json.Marshal(c)
if err != nil {
return c.Label // extremely rare case
}
return string(raw)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/settings_query_test.go | core/settings_query_test.go | package core_test
import (
"os"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestReloadSettings(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
// cleanup all stored settings
// ---
if _, err := app.DB().NewQuery("DELETE from _params;").Execute(); err != nil {
t.Fatalf("Failed to delete all test settings: %v", err)
}
// check if the new settings are saved in the db
// ---
app.Settings().Meta.AppName = "test_name_after_delete"
app.ResetEventCalls()
if err := app.ReloadSettings(); err != nil {
t.Fatalf("Failed to reload the settings after delete: %v", err)
}
testEventCalls(t, app, map[string]int{
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnSettingsReload": 1,
})
param := &core.Param{}
err := app.ModelQuery(param).Model("settings", param)
if err != nil {
t.Fatalf("Expected new settings to be persisted, got %v", err)
}
if !strings.Contains(param.Value.String(), "test_name_after_delete") {
t.Fatalf("Expected to find AppName test_name_after_delete in\n%s", param.Value.String())
}
// change the db entry and reload the app settings (ensure that there was no db update)
// ---
param.Value = types.JSONRaw([]byte(`{"meta": {"appName":"test_name_after_update"}}`))
if err := app.Save(param); err != nil {
t.Fatalf("Failed to update the test settings: %v", err)
}
app.ResetEventCalls()
if err := app.ReloadSettings(); err != nil {
t.Fatalf("Failed to reload app settings: %v", err)
}
testEventCalls(t, app, map[string]int{
"OnSettingsReload": 1,
})
// try to reload again without doing any changes
// ---
app.ResetEventCalls()
if err := app.ReloadSettings(); err != nil {
t.Fatalf("Failed to reload app settings without change: %v", err)
}
testEventCalls(t, app, map[string]int{
"OnSettingsReload": 1,
})
if app.Settings().Meta.AppName != "test_name_after_update" {
t.Fatalf("Expected AppName %q, got %q", "test_name_after_update", app.Settings().Meta.AppName)
}
}
func TestReloadSettingsWithEncryption(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
os.Setenv("pb_test_env", strings.Repeat("a", 32))
// cleanup all stored settings
// ---
if _, err := app.DB().NewQuery("DELETE from _params;").Execute(); err != nil {
t.Fatalf("Failed to delete all test settings: %v", err)
}
// check if the new settings are saved in the db
// ---
app.Settings().Meta.AppName = "test_name_after_delete"
app.ResetEventCalls()
if err := app.ReloadSettings(); err != nil {
t.Fatalf("Failed to reload the settings after delete: %v", err)
}
testEventCalls(t, app, map[string]int{
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnSettingsReload": 1,
})
param := &core.Param{}
err := app.ModelQuery(param).Model("settings", param)
if err != nil {
t.Fatalf("Expected new settings to be persisted, got %v", err)
}
rawValue := param.Value.String()
if rawValue == "" || strings.Contains(rawValue, "test_name") {
t.Fatalf("Expected inserted settings to be encrypted, found\n%s", rawValue)
}
// change and reload the app settings (ensure that there was no db update)
// ---
app.Settings().Meta.AppName = "test_name_after_update"
if err := app.Save(app.Settings()); err != nil {
t.Fatalf("Failed to update app settings: %v", err)
}
// try to reload again without doing any changes
// ---
app.ResetEventCalls()
if err := app.ReloadSettings(); err != nil {
t.Fatalf("Failed to reload app settings: %v", err)
}
testEventCalls(t, app, map[string]int{
"OnSettingsReload": 1,
})
// refetch the settings param to ensure that the new value was stored encrypted
err = app.ModelQuery(param).Model("settings", param)
if err != nil {
t.Fatalf("Expected new settings to be persisted, got %v", err)
}
rawValue = param.Value.String()
if rawValue == "" || strings.Contains(rawValue, "test_name") {
t.Fatalf("Expected updated settings to be encrypted, found\n%s", rawValue)
}
if app.Settings().Meta.AppName != "test_name_after_update" {
t.Fatalf("Expected AppName %q, got %q", "test_name_after_update", app.Settings().Meta.AppName)
}
}
func testEventCalls(t *testing.T, app *tests.TestApp, events map[string]int) {
if len(events) != len(app.EventCalls) {
t.Fatalf("Expected events doesn't match:\n%v\ngot\n%v", events, app.EventCalls)
}
for name, total := range events {
if v, ok := app.EventCalls[name]; !ok || v != total {
t.Fatalf("Expected events doesn't exist or match:\n%v\ngot\n%v", events, app.EventCalls)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_field_resolver_multi_match.go | core/record_field_resolver_multi_match.go | package core
import (
"fmt"
"strings"
"github.com/pocketbase/dbx"
)
var _ dbx.Expression = (*multiMatchSubquery)(nil)
// join defines the specification for a single SQL JOIN clause.
type join struct {
tableName string
tableAlias string
on dbx.Expression
}
// multiMatchSubquery defines a record multi-match subquery expression.
type multiMatchSubquery struct {
baseTableAlias string
fromTableName string
fromTableAlias string
valueIdentifier string
joins []*join
params dbx.Params
}
// Build converts the expression into a SQL fragment.
//
// Implements [dbx.Expression] interface.
func (m *multiMatchSubquery) Build(db *dbx.DB, params dbx.Params) string {
if m.baseTableAlias == "" || m.fromTableName == "" || m.fromTableAlias == "" {
return "0=1"
}
if params == nil {
params = m.params
} else {
// merge by updating the parent params
for k, v := range m.params {
params[k] = v
}
}
var mergedJoins strings.Builder
for i, j := range m.joins {
if i > 0 {
mergedJoins.WriteString(" ")
}
mergedJoins.WriteString("LEFT JOIN ")
mergedJoins.WriteString(db.QuoteTableName(j.tableName))
mergedJoins.WriteString(" ")
mergedJoins.WriteString(db.QuoteTableName(j.tableAlias))
if j.on != nil {
mergedJoins.WriteString(" ON ")
mergedJoins.WriteString(j.on.Build(db, params))
}
}
return fmt.Sprintf(
`SELECT %s as [[multiMatchValue]] FROM %s %s %s WHERE %s = %s`,
db.QuoteColumnName(m.valueIdentifier),
db.QuoteTableName(m.fromTableName),
db.QuoteTableName(m.fromTableAlias),
mergedJoins.String(),
db.QuoteColumnName(m.fromTableAlias+".id"),
db.QuoteColumnName(m.baseTableAlias+".id"),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_json_test.go | core/field_json_test.go | package core_test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestJSONFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeJSON)
}
func TestJSONFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.JSONField{}
expected := "JSON DEFAULT NULL"
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestJSONFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.JSONField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{"null", `null`},
{"", `""`},
{"true", `true`},
{"false", `false`},
{"test", `"test"`},
{"123", `123`},
{"-456", `-456`},
{"[1,2,3]", `[1,2,3]`},
{"[1,2,3", `"[1,2,3"`},
{`{"a":1,"b":2}`, `{"a":1,"b":2}`},
{`{"a":1,"b":2`, `"{\"a\":1,\"b\":2"`},
{[]int{1, 2, 3}, `[1,2,3]`},
{map[string]int{"a": 1, "b": 2}, `{"a":1,"b":2}`},
{nil, `null`},
{false, `false`},
{true, `true`},
{-78, `-78`},
{123.456, `123.456`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
raw, ok := v.(types.JSONRaw)
if !ok {
t.Fatalf("Expected string instance, got %T", v)
}
rawStr := raw.String()
if rawStr != s.expected {
t.Fatalf("Expected\n%#v\ngot\n%#v", s.expected, rawStr)
}
})
}
}
func TestJSONFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.JSONField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.JSONField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (not required)",
&core.JSONField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw{})
return record
},
false,
},
{
"zero field value (required)",
&core.JSONField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw{})
return record
},
true,
},
{
"non-zero field value (required)",
&core.JSONField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw("[1,2,3]"))
return record
},
false,
},
{
"non-zero field value (required)",
&core.JSONField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw(`"aaa"`))
return record
},
false,
},
{
"> default MaxSize",
&core.JSONField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw(`"`+strings.Repeat("a", (1<<20))+`"`))
return record
},
true,
},
{
"> MaxSize",
&core.JSONField{Name: "test", MaxSize: 5},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw(`"aaaa"`))
return record
},
true,
},
{
"<= MaxSize",
&core.JSONField{Name: "test", MaxSize: 5},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.JSONRaw(`"aaa"`))
return record
},
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestJSONFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeJSON)
testDefaultFieldNameValidation(t, core.FieldTypeJSON)
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() *core.JSONField
expectErrors []string
}{
{
"MaxSize < 0",
func() *core.JSONField {
return &core.JSONField{
Id: "test",
Name: "test",
MaxSize: -1,
}
},
[]string{"maxSize"},
},
{
"MaxSize = 0",
func() *core.JSONField {
return &core.JSONField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"MaxSize > 0",
func() *core.JSONField {
return &core.JSONField{
Id: "test",
Name: "test",
MaxSize: 1,
}
},
[]string{},
},
{
"MaxSize > safe json int",
func() *core.JSONField {
return &core.JSONField{
Id: "test",
Name: "test",
MaxSize: 1 << 53,
}
},
[]string{"maxSize"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := s.field().ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestJSONFieldCalculateMaxBodySize(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
scenarios := []struct {
field *core.JSONField
expected int64
}{
{&core.JSONField{}, core.DefaultJSONFieldMaxSize},
{&core.JSONField{MaxSize: 10}, 10},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d", i, s.field.MaxSize), func(t *testing.T) {
result := s.field.CalculateMaxBodySize()
if result != s.expected {
t.Fatalf("Expected %d, got %d", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_proxy_test.go | core/record_proxy_test.go | package core_test
import (
"testing"
"github.com/pocketbase/pocketbase/core"
)
func TestBaseRecordProxy(t *testing.T) {
p := core.BaseRecordProxy{}
record := core.NewRecord(core.NewBaseCollection("test"))
record.Id = "test"
p.SetProxyRecord(record)
if p.ProxyRecord() == nil || p.ProxyRecord().Id != p.Id || p.Id != "test" {
t.Fatalf("Expected proxy record to be set")
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_retry.go | core/db_retry.go | package core
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/pocketbase/dbx"
)
// default retries intervals (in ms)
var defaultRetryIntervals = []int{50, 100, 150, 200, 300, 400, 500, 700, 1000}
// default max retry attempts
const defaultMaxLockRetries = 12
func execLockRetry(timeout time.Duration, maxRetries int) dbx.ExecHookFunc {
return func(q *dbx.Query, op func() error) error {
if q.Context() == nil {
cancelCtx, cancel := context.WithTimeout(context.Background(), timeout)
defer func() {
cancel()
//nolint:staticcheck
q.WithContext(nil) // reset
}()
q.WithContext(cancelCtx)
}
execErr := baseLockRetry(func(attempt int) error {
return op()
}, maxRetries)
if execErr != nil && !errors.Is(execErr, sql.ErrNoRows) {
execErr = fmt.Errorf("%w; failed query: %s", execErr, q.SQL())
}
return execErr
}
}
func baseLockRetry(op func(attempt int) error, maxRetries int) error {
attempt := 1
Retry:
err := op(attempt)
if err != nil && attempt <= maxRetries {
errStr := err.Error()
// we are checking the error against the plain error texts since the codes could vary between drivers
if strings.Contains(errStr, "database is locked") ||
strings.Contains(errStr, "table is locked") {
// wait and retry
time.Sleep(getDefaultRetryInterval(attempt))
attempt++
goto Retry
}
}
return err
}
func getDefaultRetryInterval(attempt int) time.Duration {
if attempt < 0 || attempt > len(defaultRetryIntervals)-1 {
return time.Duration(defaultRetryIntervals[len(defaultRetryIntervals)-1]) * time.Millisecond
}
return time.Duration(defaultRetryIntervals[attempt]) * time.Millisecond
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_number.go | core/field_number.go | package core
import (
"context"
"fmt"
"math"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeNumber] = func() Field {
return &NumberField{}
}
}
const FieldTypeNumber = "number"
var (
_ Field = (*NumberField)(nil)
_ SetterFinder = (*NumberField)(nil)
)
// NumberField defines "number" type field for storing numeric (float64) value.
//
// The respective zero record field value is 0.
//
// The following additional setter keys are available:
//
// - "fieldName+" - appends to the existing record value. For example:
// record.Set("total+", 5)
// - "fieldName-" - subtracts from the existing record value. For example:
// record.Set("total-", 5)
type NumberField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// Min specifies the min allowed field value.
//
// Leave it nil to skip the validator.
Min *float64 `form:"min" json:"min"`
// Max specifies the max allowed field value.
//
// Leave it nil to skip the validator.
Max *float64 `form:"max" json:"max"`
// OnlyInt will require the field value to be integer.
OnlyInt bool `form:"onlyInt" json:"onlyInt"`
// Required will require the field value to be non-zero.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *NumberField) Type() string {
return FieldTypeNumber
}
// GetId implements [Field.GetId] interface method.
func (f *NumberField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *NumberField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *NumberField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *NumberField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *NumberField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *NumberField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *NumberField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *NumberField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *NumberField) ColumnType(app App) string {
return "NUMERIC DEFAULT 0 NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *NumberField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToFloat64(raw), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *NumberField) ValidateValue(ctx context.Context, app App, record *Record) error {
val, ok := record.GetRaw(f.Name).(float64)
if !ok {
return validators.ErrUnsupportedValueType
}
if math.IsInf(val, 0) || math.IsNaN(val) {
return validation.NewError("validation_not_a_number", "The submitted number is not properly formatted")
}
if val == 0 {
if f.Required {
if err := validation.Required.Validate(val); err != nil {
return err
}
}
return nil
}
if f.OnlyInt && val != float64(int64(val)) {
return validation.NewError("validation_only_int_constraint", "Decimal numbers are not allowed")
}
if f.Min != nil && val < *f.Min {
return validation.NewError("validation_min_number_constraint", fmt.Sprintf("Must be larger than %f", *f.Min))
}
if f.Max != nil && val > *f.Max {
return validation.NewError("validation_max_number_constraint", fmt.Sprintf("Must be less than %f", *f.Max))
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *NumberField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
maxRules := []validation.Rule{
validation.By(f.checkOnlyInt),
}
if f.Min != nil && f.Max != nil {
maxRules = append(maxRules, validation.Min(*f.Min))
}
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.Min, validation.By(f.checkOnlyInt)),
validation.Field(&f.Max, maxRules...),
)
}
func (f *NumberField) checkOnlyInt(value any) error {
v, _ := value.(*float64)
if v == nil || !f.OnlyInt {
return nil // nothing to check
}
if *v != float64(int64(*v)) {
return validation.NewError("validation_only_int_constraint", "Decimal numbers are not allowed.")
}
return nil
}
// FindSetter implements the [SetterFinder] interface.
func (f *NumberField) FindSetter(key string) SetterFunc {
switch key {
case f.Name:
return f.setValue
case f.Name + "+":
return f.addValue
case f.Name + "-":
return f.subtractValue
default:
return nil
}
}
func (f *NumberField) setValue(record *Record, raw any) {
record.SetRaw(f.Name, cast.ToFloat64(raw))
}
func (f *NumberField) addValue(record *Record, raw any) {
val := cast.ToFloat64(record.GetRaw(f.Name))
record.SetRaw(f.Name, val+cast.ToFloat64(raw))
}
func (f *NumberField) subtractValue(record *Record, raw any) {
val := cast.ToFloat64(record.GetRaw(f.Name))
record.SetRaw(f.Name, val-cast.ToFloat64(raw))
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_base_options.go | core/collection_model_base_options.go | package core
var _ optionsValidator = (*collectionBaseOptions)(nil)
// collectionBaseOptions defines the options for the "base" type collection.
type collectionBaseOptions struct {
}
func (o *collectionBaseOptions) validate(cv *collectionValidator) error {
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/fields_list.go | core/fields_list.go | package core
import (
"database/sql/driver"
"encoding/json"
"fmt"
"slices"
"strconv"
)
// NewFieldsList creates a new FieldsList instance with the provided fields.
func NewFieldsList(fields ...Field) FieldsList {
l := make(FieldsList, 0, len(fields))
for _, f := range fields {
l.add(-1, f)
}
return l
}
// FieldsList defines a Collection slice of fields.
type FieldsList []Field
// Clone creates a deep clone of the current list.
func (l FieldsList) Clone() (FieldsList, error) {
copyRaw, err := json.Marshal(l)
if err != nil {
return nil, err
}
result := FieldsList{}
if err := json.Unmarshal(copyRaw, &result); err != nil {
return nil, err
}
return result, nil
}
// FieldNames returns a slice with the name of all list fields.
func (l FieldsList) FieldNames() []string {
result := make([]string, len(l))
for i, field := range l {
result[i] = field.GetName()
}
return result
}
// AsMap returns a map with all registered list field.
// The returned map is indexed with each field name.
func (l FieldsList) AsMap() map[string]Field {
result := make(map[string]Field, len(l))
for _, field := range l {
result[field.GetName()] = field
}
return result
}
// GetById returns a single field by its id.
func (l FieldsList) GetById(fieldId string) Field {
for _, field := range l {
if field.GetId() == fieldId {
return field
}
}
return nil
}
// GetByName returns a single field by its name.
func (l FieldsList) GetByName(fieldName string) Field {
for _, field := range l {
if field.GetName() == fieldName {
return field
}
}
return nil
}
// RemoveById removes a single field by its id.
//
// This method does nothing if field with the specified id doesn't exist.
func (l *FieldsList) RemoveById(fieldId string) {
fields := *l
for i, field := range fields {
if field.GetId() == fieldId {
*l = append(fields[:i], fields[i+1:]...)
return
}
}
}
// RemoveByName removes a single field by its name.
//
// This method does nothing if field with the specified name doesn't exist.
func (l *FieldsList) RemoveByName(fieldName string) {
fields := *l
for i, field := range fields {
if field.GetName() == fieldName {
*l = append(fields[:i], fields[i+1:]...)
return
}
}
}
// Add adds one or more fields to the current list.
//
// By default this method will try to REPLACE existing fields with
// the new ones by their id or by their name if the new field doesn't have an explicit id.
//
// If no matching existing field is found, it will APPEND the field to the end of the list.
//
// In all cases, if any of the new fields don't have an explicit id it will auto generate a default one for them
// (the id value doesn't really matter and it is mostly used as a stable identifier in case of a field rename).
func (l *FieldsList) Add(fields ...Field) {
for _, f := range fields {
l.add(-1, f)
}
}
// AddAt is the same as Add but insert/move the fields at the specific position.
//
// If pos < 0, then this method acts the same as calling Add.
//
// If pos > FieldsList total items, then the specified fields are inserted/moved at the end of the list.
func (l *FieldsList) AddAt(pos int, fields ...Field) {
total := len(*l)
for i, f := range fields {
if pos < 0 {
l.add(-1, f)
} else if pos > total {
l.add(total+i, f)
} else {
l.add(pos+i, f)
}
}
}
// AddMarshaledJSON parses the provided raw json data and adds the
// found fields into the current list (following the same rule as the Add method).
//
// The rawJSON argument could be one of:
// - serialized array of field objects
// - single field object.
//
// Example:
//
// l.AddMarshaledJSON([]byte{`{"type":"text", name: "test"}`})
// l.AddMarshaledJSON([]byte{`[{"type":"text", name: "test1"}, {"type":"text", name: "test2"}]`})
func (l *FieldsList) AddMarshaledJSON(rawJSON []byte) error {
extractedFields, err := marshaledJSONtoFieldsList(rawJSON)
if err != nil {
return err
}
l.Add(extractedFields...)
return nil
}
// AddMarshaledJSONAt is the same as AddMarshaledJSON but insert/move the fields at the specific position.
//
// If pos < 0, then this method acts the same as calling AddMarshaledJSON.
//
// If pos > FieldsList total items, then the specified fields are inserted/moved at the end of the list.
func (l *FieldsList) AddMarshaledJSONAt(pos int, rawJSON []byte) error {
extractedFields, err := marshaledJSONtoFieldsList(rawJSON)
if err != nil {
return err
}
l.AddAt(pos, extractedFields...)
return nil
}
func marshaledJSONtoFieldsList(rawJSON []byte) (FieldsList, error) {
extractedFields := FieldsList{}
// nothing to add
if len(rawJSON) == 0 {
return extractedFields, nil
}
// try to unmarshal first into a new fieds list
// (assuming that rawJSON is array of objects)
err := json.Unmarshal(rawJSON, &extractedFields)
if err != nil {
// try again but wrap the rawJSON in []
// (assuming that rawJSON is a single object)
wrapped := make([]byte, 0, len(rawJSON)+2)
wrapped = append(wrapped, '[')
wrapped = append(wrapped, rawJSON...)
wrapped = append(wrapped, ']')
err = json.Unmarshal(wrapped, &extractedFields)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal the provided JSON - expects array of objects or just single object: %w", err)
}
}
return extractedFields, nil
}
func (l *FieldsList) add(pos int, newField Field) {
fields := *l
var replaceByName bool
var replaceInPlace bool
if pos < 0 {
replaceInPlace = true
pos = len(fields)
} else if pos > len(fields) {
pos = len(fields)
}
newFieldId := newField.GetId()
// set default id
if newFieldId == "" {
replaceByName = true
baseId := newField.Type() + crc32Checksum(newField.GetName())
newFieldId = baseId
for i := 2; i < 1000; i++ {
if l.GetById(newFieldId) == nil {
break // already unique
}
newFieldId = baseId + strconv.Itoa(i)
}
newField.SetId(newFieldId)
}
// try to replace existing
for i, field := range fields {
if replaceByName {
if name := newField.GetName(); name != "" && field.GetName() == name {
// reuse the original id
newField.SetId(field.GetId())
if replaceInPlace {
(*l)[i] = newField
return
} else {
// remove the current field and insert it later at the specific position
*l = slices.Delete(*l, i, i+1)
if total := len(*l); pos > total {
pos = total
}
break
}
}
} else {
if field.GetId() == newFieldId {
if replaceInPlace {
(*l)[i] = newField
return
} else {
// remove the current field and insert it later at the specific position
*l = slices.Delete(*l, i, i+1)
if total := len(*l); pos > total {
pos = total
}
break
}
}
}
}
// insert the new field
*l = slices.Insert(*l, pos, newField)
}
// String returns the string representation of the current list.
func (l FieldsList) String() string {
v, _ := json.Marshal(l)
return string(v)
}
type onlyFieldType struct {
Type string `json:"type"`
}
type fieldWithType struct {
Field
Type string `json:"type"`
}
func (fwt *fieldWithType) UnmarshalJSON(data []byte) error {
// extract the field type to init a blank factory
t := &onlyFieldType{}
if err := json.Unmarshal(data, t); err != nil {
return fmt.Errorf("failed to unmarshal field type: %w", err)
}
factory, ok := Fields[t.Type]
if !ok {
return fmt.Errorf("missing or unknown field type in %s", data)
}
fwt.Type = t.Type
fwt.Field = factory()
// unmarshal the rest of the data into the created field
if err := json.Unmarshal(data, fwt.Field); err != nil {
return fmt.Errorf("failed to unmarshal field: %w", err)
}
return nil
}
// UnmarshalJSON implements [json.Unmarshaler] and
// loads the provided json data into the current FieldsList.
func (l *FieldsList) UnmarshalJSON(data []byte) error {
fwts := []fieldWithType{}
if err := json.Unmarshal(data, &fwts); err != nil {
return err
}
*l = []Field{} // reset
for _, fwt := range fwts {
l.add(-1, fwt.Field)
}
return nil
}
// MarshalJSON implements the [json.Marshaler] interface.
func (l FieldsList) MarshalJSON() ([]byte, error) {
if l == nil {
l = []Field{} // always init to ensure that it is serialized as empty array
}
wrapper := make([]map[string]any, 0, len(l))
for _, f := range l {
// precompute the json into a map so that we can append the type to a flatten object
raw, err := json.Marshal(f)
if err != nil {
return nil, err
}
data := map[string]any{}
if err := json.Unmarshal(raw, &data); err != nil {
return nil, err
}
data["type"] = f.Type()
wrapper = append(wrapper, data)
}
return json.Marshal(wrapper)
}
// Value implements the [driver.Valuer] interface.
func (l FieldsList) Value() (driver.Value, error) {
data, err := json.Marshal(l)
return string(data), err
}
// Scan implements [sql.Scanner] interface to scan the provided value
// into the current FieldsList instance.
func (l *FieldsList) Scan(value any) error {
var data []byte
switch v := value.(type) {
case nil:
// no cast needed
case []byte:
data = v
case string:
data = []byte(v)
default:
return fmt.Errorf("failed to unmarshal FieldsList value %q", value)
}
if len(data) == 0 {
data = []byte("[]")
}
return l.UnmarshalJSON(data)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_field_resolver_test.go | core/record_field_resolver_test.go | package core_test
import (
"encoding/json"
"regexp"
"slices"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestRecordFieldResolverAllowedFields(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
r := core.NewRecordFieldResolver(app, collection, nil, false)
fields := r.AllowedFields()
if len(fields) != 8 {
t.Fatalf("Expected %d original allowed fields, got %d", 8, len(fields))
}
// change the allowed fields
newFields := []string{"a", "b", "c"}
expected := slices.Clone(newFields)
r.SetAllowedFields(newFields)
// change the new fields to ensure that the slice was cloned
newFields[2] = "d"
fields = r.AllowedFields()
if len(fields) != len(expected) {
t.Fatalf("Expected %d changed allowed fields, got %d", len(expected), len(fields))
}
for i, v := range expected {
if fields[i] != v {
t.Errorf("[%d] Expected field %q", i, v)
}
}
}
func TestRecordFieldResolverAllowHiddenFields(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
r := core.NewRecordFieldResolver(app, collection, nil, false)
allowHiddenFields := r.AllowHiddenFields()
if allowHiddenFields {
t.Fatalf("Expected original allowHiddenFields %v, got %v", allowHiddenFields, !allowHiddenFields)
}
// change the flag
expected := !allowHiddenFields
r.SetAllowHiddenFields(expected)
allowHiddenFields = r.AllowHiddenFields()
if allowHiddenFields != expected {
t.Fatalf("Expected changed allowHiddenFields %v, got %v", expected, allowHiddenFields)
}
}
func TestRecordFieldResolverUpdateQuery(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
authRecord, err := app.FindRecordById("users", "4q1xlclmfloku33")
if err != nil {
t.Fatal(err)
}
requestInfo := &core.RequestInfo{
Context: "ctx",
Headers: map[string]string{
"a": "123",
"b": "456",
},
Query: map[string]string{
"a": "", // to ensure that :isset returns true because the key exists
"b": "123",
},
Body: map[string]any{
"a": nil, // to ensure that :isset returns true because the key exists
"b": 123,
"number": 10,
"select_many": []string{"optionA", "optionC"},
"rel_one": "test",
"rel_many": []string{"test1", "test2"},
"file_one": "test",
"file_many": []string{"test1", "test2", "test3"},
"self_rel_one": "test",
"self_rel_many": []string{"test1"},
"rel_many_cascade": []string{"test1", "test2"},
"rel_one_cascade": "test1",
"rel_one_no_cascade": "test1",
},
Auth: authRecord,
}
scenarios := []struct {
name string
collectionIdOrName string
rule string
allowHiddenFields bool
expectQuery string
}{
{
"non relation field (with all default operators)",
"demo4",
"title = true || title != 'test' || title ~ 'test1' || title !~ '%test2' || title > 1 || title >= 2 || title < 3 || title <= 4",
false,
"SELECT `demo4`.* FROM `demo4` WHERE ([[demo4.title]] = 1 OR [[demo4.title]] IS NOT {:TEST} OR [[demo4.title]] LIKE {:TEST} ESCAPE '\\' OR [[demo4.title]] NOT LIKE {:TEST} ESCAPE '\\' OR [[demo4.title]] > {:TEST} OR [[demo4.title]] >= {:TEST} OR [[demo4.title]] < {:TEST} OR [[demo4.title]] <= {:TEST})",
},
{
"non relation field (with all opt/any operators)",
"demo4",
"title ?= true || title ?!= 'test' || title ?~ 'test1' || title ?!~ '%test2' || title ?> 1 || title ?>= 2 || title ?< 3 || title ?<= 4",
false,
"SELECT `demo4`.* FROM `demo4` WHERE ([[demo4.title]] = 1 OR [[demo4.title]] IS NOT {:TEST} OR [[demo4.title]] LIKE {:TEST} ESCAPE '\\' OR [[demo4.title]] NOT LIKE {:TEST} ESCAPE '\\' OR [[demo4.title]] > {:TEST} OR [[demo4.title]] >= {:TEST} OR [[demo4.title]] < {:TEST} OR [[demo4.title]] <= {:TEST})",
},
{
"single direct rel",
"demo4",
"self_rel_one > true",
false,
"SELECT `demo4`.* FROM `demo4` WHERE [[demo4.self_rel_one]] > 1",
},
{
"single direct rel (with id)",
"demo4",
"self_rel_one.id > true", // should NOT have join
false,
"SELECT `demo4`.* FROM `demo4` WHERE [[demo4.self_rel_one]] > 1",
},
{
"multiple direct rel (with id)",
"demo4",
"self_rel_many.id ?> true", // should have join
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] WHERE [[demo4_self_rel_many.id]] > 1",
},
{
"rel to collection with empty list rule",
"demo4",
"self_rel_one.created > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] WHERE [[demo4_self_rel_one.created]] > 1",
},
{
"rel to collection with non-empty list rule",
"demo4",
"rel_one_cascade.created > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo3` `demo4_rel_one_cascade` ON [[demo4_rel_one_cascade.id]] = [[demo4.rel_one_cascade]] WHERE (({:TEST} IS NOT '' AND {:TEST} IS NOT {:TEST})) AND ([[demo4_rel_one_cascade.created]] > 1)",
},
{
"rel to collection with non-empty list rule (with allowHiddenFields)",
"demo4",
"rel_one_cascade.created > true",
true,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo3` `demo4_rel_one_cascade` ON [[demo4_rel_one_cascade.id]] = [[demo4.rel_one_cascade]] WHERE [[demo4_rel_one_cascade.created]] > 1",
},
{
"rel to collection with superusers only list rule",
"demo1",
"rel_many.created ?> true",
false,
"",
},
{
"rel to collection with superusers only list rule (with allowHiddenFields)",
"demo1",
"rel_many.created ?> true",
true,
"SELECT DISTINCT `demo1`.* FROM `demo1` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo1.rel_many]]), json_type([[demo1.rel_many]])='array', FALSE) THEN [[demo1.rel_many]] ELSE json_array([[demo1.rel_many]]) END) `__je_demo1_rel_many` LEFT JOIN `users` `demo1_rel_many` ON [[demo1_rel_many.id]] = [[__je_demo1_rel_many.value]] WHERE [[demo1_rel_many.created]] > 1",
},
{
"nested rels with all empty list rules",
"demo4",
"self_rel_one.self_rel_one.title > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] LEFT JOIN `demo4` `demo4_self_rel_one_self_rel_one` ON [[demo4_self_rel_one_self_rel_one.id]] = [[demo4_self_rel_one.self_rel_one]] WHERE [[demo4_self_rel_one_self_rel_one.title]] > 1",
},
{
"nested rels with non-empty list rule",
"demo4",
"self_rel_one.rel_one_cascade.created > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] LEFT JOIN `demo3` `demo4_self_rel_one_rel_one_cascade` ON [[demo4_self_rel_one_rel_one_cascade.id]] = [[demo4_self_rel_one.rel_one_cascade]] WHERE (({:TEST} IS NOT '' AND {:TEST} IS NOT {:TEST})) AND ([[demo4_self_rel_one_rel_one_cascade.created]] > 1)",
},
{
"nested rels with non-empty list rule (joins reuse test)",
"demo4",
"self_rel_one.rel_one_cascade.created > true && self_rel_one.rel_one_cascade.updated > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] LEFT JOIN `demo3` `demo4_self_rel_one_rel_one_cascade` ON [[demo4_self_rel_one_rel_one_cascade.id]] = [[demo4_self_rel_one.rel_one_cascade]] WHERE (({:TEST} IS NOT '' AND {:TEST} IS NOT {:TEST})) AND (([[demo4_self_rel_one_rel_one_cascade.created]] > 1 AND [[demo4_self_rel_one_rel_one_cascade.updated]] > 1))",
},
{
"nested rels with non-empty list rule (with allowHiddenFields)",
"demo4",
"self_rel_one.rel_one_cascade.created > true",
true,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] LEFT JOIN `demo3` `demo4_self_rel_one_rel_one_cascade` ON [[demo4_self_rel_one_rel_one_cascade.id]] = [[demo4_self_rel_one.rel_one_cascade]] WHERE [[demo4_self_rel_one_rel_one_cascade.created]] > 1",
},
{
"non-relation field + single rel",
"demo4",
"title > true || self_rel_one.title > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] WHERE ([[demo4.title]] > 1 OR [[demo4_self_rel_one.title]] > 1)",
},
{
"nested incomplete relations (opt/any operator)",
"demo4",
"self_rel_many.self_rel_one ?> true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] WHERE [[demo4_self_rel_many.self_rel_one]] > 1",
},
{
"nested incomplete relations (multi-match operator)",
"demo4",
"self_rel_many.self_rel_one > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] WHERE ((([[demo4_self_rel_many.self_rel_one]] > 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo4_self_rel_many.self_rel_one]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[__mm_demo4.self_rel_many]]), json_type([[__mm_demo4.self_rel_many]])='array', FALSE) THEN [[__mm_demo4.self_rel_many]] ELSE json_array([[__mm_demo4.self_rel_many]]) END) `__mm_demo4_self_rel_many_je` LEFT JOIN `demo4` `__mm_demo4_self_rel_many` ON [[__mm_demo4_self_rel_many.id]] = [[__mm_demo4_self_rel_many_je.value]] WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] > 1)))))",
},
{
"nested complete relations (opt/any operator)",
"demo4",
"self_rel_many.self_rel_one.title ?> true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one` ON [[demo4_self_rel_many_self_rel_one.id]] = [[demo4_self_rel_many.self_rel_one]] WHERE [[demo4_self_rel_many_self_rel_one.title]] > 1",
},
{
"nested complete relations (multi-match operator)",
"demo4",
"self_rel_many.self_rel_one.title > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one` ON [[demo4_self_rel_many_self_rel_one.id]] = [[demo4_self_rel_many.self_rel_one]] WHERE ((([[demo4_self_rel_many_self_rel_one.title]] > 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo4_self_rel_many_self_rel_one.title]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[__mm_demo4.self_rel_many]]), json_type([[__mm_demo4.self_rel_many]])='array', FALSE) THEN [[__mm_demo4.self_rel_many]] ELSE json_array([[__mm_demo4.self_rel_many]]) END) `__mm_demo4_self_rel_many_je` LEFT JOIN `demo4` `__mm_demo4_self_rel_many` ON [[__mm_demo4_self_rel_many.id]] = [[__mm_demo4_self_rel_many_je.value]] LEFT JOIN `demo4` `__mm_demo4_self_rel_many_self_rel_one` ON [[__mm_demo4_self_rel_many_self_rel_one.id]] = [[__mm_demo4_self_rel_many.self_rel_one]] WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] > 1)))))",
},
{
"repeated nested relations (opt/any operator)",
"demo4",
"self_rel_many.self_rel_one.self_rel_many.self_rel_one.title ?> true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one` ON [[demo4_self_rel_many_self_rel_one.id]] = [[demo4_self_rel_many.self_rel_one]] LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4_self_rel_many_self_rel_one.self_rel_many]]), json_type([[demo4_self_rel_many_self_rel_one.self_rel_many]])='array', FALSE) THEN [[demo4_self_rel_many_self_rel_one.self_rel_many]] ELSE json_array([[demo4_self_rel_many_self_rel_one.self_rel_many]]) END) `__je_demo4_self_rel_many_self_rel_one_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one_self_rel_many` ON [[demo4_self_rel_many_self_rel_one_self_rel_many.id]] = [[__je_demo4_self_rel_many_self_rel_one_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one` ON [[demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one.id]] = [[demo4_self_rel_many_self_rel_one_self_rel_many.self_rel_one]] WHERE [[demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one.title]] > 1",
},
{
"repeated nested relations (multi-match operator)",
"demo4",
"self_rel_many.self_rel_one.self_rel_many.self_rel_one.title > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one` ON [[demo4_self_rel_many_self_rel_one.id]] = [[demo4_self_rel_many.self_rel_one]] LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4_self_rel_many_self_rel_one.self_rel_many]]), json_type([[demo4_self_rel_many_self_rel_one.self_rel_many]])='array', FALSE) THEN [[demo4_self_rel_many_self_rel_one.self_rel_many]] ELSE json_array([[demo4_self_rel_many_self_rel_one.self_rel_many]]) END) `__je_demo4_self_rel_many_self_rel_one_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one_self_rel_many` ON [[demo4_self_rel_many_self_rel_one_self_rel_many.id]] = [[__je_demo4_self_rel_many_self_rel_one_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one` ON [[demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one.id]] = [[demo4_self_rel_many_self_rel_one_self_rel_many.self_rel_one]] WHERE ((([[demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one.title]] > 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one.title]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[__mm_demo4.self_rel_many]]), json_type([[__mm_demo4.self_rel_many]])='array', FALSE) THEN [[__mm_demo4.self_rel_many]] ELSE json_array([[__mm_demo4.self_rel_many]]) END) `__mm_demo4_self_rel_many_je` LEFT JOIN `demo4` `__mm_demo4_self_rel_many` ON [[__mm_demo4_self_rel_many.id]] = [[__mm_demo4_self_rel_many_je.value]] LEFT JOIN `demo4` `__mm_demo4_self_rel_many_self_rel_one` ON [[__mm_demo4_self_rel_many_self_rel_one.id]] = [[__mm_demo4_self_rel_many.self_rel_one]] LEFT JOIN json_each(CASE WHEN iif(json_valid([[__mm_demo4_self_rel_many_self_rel_one.self_rel_many]]), json_type([[__mm_demo4_self_rel_many_self_rel_one.self_rel_many]])='array', FALSE) THEN [[__mm_demo4_self_rel_many_self_rel_one.self_rel_many]] ELSE json_array([[__mm_demo4_self_rel_many_self_rel_one.self_rel_many]]) END) `__mm_demo4_self_rel_many_self_rel_one_self_rel_many_je` LEFT JOIN `demo4` `__mm_demo4_self_rel_many_self_rel_one_self_rel_many` ON [[__mm_demo4_self_rel_many_self_rel_one_self_rel_many.id]] = [[__mm_demo4_self_rel_many_self_rel_one_self_rel_many_je.value]] LEFT JOIN `demo4` `__mm_demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one` ON [[__mm_demo4_self_rel_many_self_rel_one_self_rel_many_self_rel_one.id]] = [[__mm_demo4_self_rel_many_self_rel_one_self_rel_many.self_rel_one]] WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] > 1)))))",
},
{
"multiple relations (opt/any operators)",
"demo4",
"self_rel_many.title ?= 'test' || self_rel_one.json_object.a ?> true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] WHERE ([[demo4_self_rel_many.title]] = {:TEST} OR (CASE WHEN json_valid([[demo4_self_rel_one.json_object]]) THEN JSON_EXTRACT([[demo4_self_rel_one.json_object]], '$.a') ELSE JSON_EXTRACT(json_object('pb', [[demo4_self_rel_one.json_object]]), '$.pb.a') END) > 1)",
},
{
"multiple relations (multi-match operators)",
"demo4",
"self_rel_many.title = 'test' || self_rel_one.json_object.a > true",
false,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo4.self_rel_many]]), json_type([[demo4.self_rel_many]])='array', FALSE) THEN [[demo4.self_rel_many]] ELSE json_array([[demo4.self_rel_many]]) END) `__je_demo4_self_rel_many` LEFT JOIN `demo4` `demo4_self_rel_many` ON [[demo4_self_rel_many.id]] = [[__je_demo4_self_rel_many.value]] LEFT JOIN `demo4` `demo4_self_rel_one` ON [[demo4_self_rel_one.id]] = [[demo4.self_rel_one]] WHERE ((([[demo4_self_rel_many.title]] = {:TEST}) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo4_self_rel_many.title]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN json_each(CASE WHEN iif(json_valid([[__mm_demo4.self_rel_many]]), json_type([[__mm_demo4.self_rel_many]])='array', FALSE) THEN [[__mm_demo4.self_rel_many]] ELSE json_array([[__mm_demo4.self_rel_many]]) END) `__mm_demo4_self_rel_many_je` LEFT JOIN `demo4` `__mm_demo4_self_rel_many` ON [[__mm_demo4_self_rel_many.id]] = [[__mm_demo4_self_rel_many_je.value]] WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] = {:TEST})))) OR (CASE WHEN json_valid([[demo4_self_rel_one.json_object]]) THEN JSON_EXTRACT([[demo4_self_rel_one.json_object]], '$.a') ELSE JSON_EXTRACT(json_object('pb', [[demo4_self_rel_one.json_object]]), '$.pb.a') END) > 1)",
},
{
"back relations via single relation field (without unique index)",
"demo3",
"demo4_via_rel_one_cascade.id = true",
false,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_one_cascade` ON [[demo3.id]] IN (SELECT [[__je_demo3_demo4_via_rel_one_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_one_cascade.rel_one_cascade]]), json_type([[demo3_demo4_via_rel_one_cascade.rel_one_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_one_cascade.rel_one_cascade]] ELSE json_array([[demo3_demo4_via_rel_one_cascade.rel_one_cascade]]) END) {{__je_demo3_demo4_via_rel_one_cascade}}) WHERE ((([[demo3_demo4_via_rel_one_cascade.id]] = 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo3_demo4_via_rel_one_cascade.id]] as [[multiMatchValue]] FROM `demo3` `__mm_demo3` LEFT JOIN `demo4` `__mm_demo3_demo4_via_rel_one_cascade` ON [[__mm_demo3.id]] IN (SELECT [[__je___mm_demo3_demo4_via_rel_one_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[__mm_demo3_demo4_via_rel_one_cascade.rel_one_cascade]]), json_type([[__mm_demo3_demo4_via_rel_one_cascade.rel_one_cascade]])='array', FALSE) THEN [[__mm_demo3_demo4_via_rel_one_cascade.rel_one_cascade]] ELSE json_array([[__mm_demo3_demo4_via_rel_one_cascade.rel_one_cascade]]) END) {{__je___mm_demo3_demo4_via_rel_one_cascade}}) WHERE `__mm_demo3`.`id` = `demo3`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] = 1)))))",
},
{
"back relations via single relation field (with unique index)",
"demo3",
"demo4_via_rel_one_unique.id = true",
false,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_one_unique` ON [[demo3_demo4_via_rel_one_unique.rel_one_unique]] = [[demo3.id]] WHERE [[demo3_demo4_via_rel_one_unique.id]] = 1",
},
{
"back relations via multiple relation field (opt/any operators)",
"demo3",
"demo4_via_rel_many_cascade.id ?= true",
false,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_many_cascade` ON [[demo3.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je_demo3_demo4_via_rel_many_cascade}}) WHERE [[demo3_demo4_via_rel_many_cascade.id]] = 1",
},
{
"back relations via multiple relation field (multi-match operators)",
"demo3",
"demo4_via_rel_many_cascade.id = true",
false,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_many_cascade` ON [[demo3.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je_demo3_demo4_via_rel_many_cascade}}) WHERE ((([[demo3_demo4_via_rel_many_cascade.id]] = 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo3_demo4_via_rel_many_cascade.id]] as [[multiMatchValue]] FROM `demo3` `__mm_demo3` LEFT JOIN `demo4` `__mm_demo3_demo4_via_rel_many_cascade` ON [[__mm_demo3.id]] IN (SELECT [[__je___mm_demo3_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[__mm_demo3_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[__mm_demo3_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[__mm_demo3_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[__mm_demo3_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je___mm_demo3_demo4_via_rel_many_cascade}}) WHERE `__mm_demo3`.`id` = `demo3`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] = 1)))))",
},
{
"back relations via unique multiple relation field (should be the same as multi-match)",
"demo3",
"demo4_via_rel_many_unique.id = true",
false,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_many_unique` ON [[demo3.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_unique.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_unique.rel_many_unique]]), json_type([[demo3_demo4_via_rel_many_unique.rel_many_unique]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_unique.rel_many_unique]] ELSE json_array([[demo3_demo4_via_rel_many_unique.rel_many_unique]]) END) {{__je_demo3_demo4_via_rel_many_unique}}) WHERE ((([[demo3_demo4_via_rel_many_unique.id]] = 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm_demo3_demo4_via_rel_many_unique.id]] as [[multiMatchValue]] FROM `demo3` `__mm_demo3` LEFT JOIN `demo4` `__mm_demo3_demo4_via_rel_many_unique` ON [[__mm_demo3.id]] IN (SELECT [[__je___mm_demo3_demo4_via_rel_many_unique.value]] FROM json_each(CASE WHEN iif(json_valid([[__mm_demo3_demo4_via_rel_many_unique.rel_many_unique]]), json_type([[__mm_demo3_demo4_via_rel_many_unique.rel_many_unique]])='array', FALSE) THEN [[__mm_demo3_demo4_via_rel_many_unique.rel_many_unique]] ELSE json_array([[__mm_demo3_demo4_via_rel_many_unique.rel_many_unique]]) END) {{__je___mm_demo3_demo4_via_rel_many_unique}}) WHERE `__mm_demo3`.`id` = `demo3`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] = 1)))))",
},
{
"view back relation with non-empty and superusers list rules",
"demo1",
"view1_via_rel_one.rel_many.created ?> true",
false,
"",
},
{
"view back relation with non-empty and superusers list rules (with allowHiddenFields)",
"demo1",
"view1_via_rel_one.rel_many.created ?> true",
true,
"SELECT DISTINCT `demo1`.* FROM `demo1` LEFT JOIN `view1` `demo1_view1_via_rel_one` ON [[demo1.id]] IN (SELECT [[__je_demo1_view1_via_rel_one.value]] FROM json_each(CASE WHEN iif(json_valid([[demo1_view1_via_rel_one.rel_one]]), json_type([[demo1_view1_via_rel_one.rel_one]])='array', FALSE) THEN [[demo1_view1_via_rel_one.rel_one]] ELSE json_array([[demo1_view1_via_rel_one.rel_one]]) END) {{__je_demo1_view1_via_rel_one}}) LEFT JOIN json_each(CASE WHEN iif(json_valid([[demo1_view1_via_rel_one.rel_many]]), json_type([[demo1_view1_via_rel_one.rel_many]])='array', FALSE) THEN [[demo1_view1_via_rel_one.rel_many]] ELSE json_array([[demo1_view1_via_rel_one.rel_many]]) END) `__je_demo1_view1_via_rel_one_rel_many` LEFT JOIN `users` `demo1_view1_via_rel_one_rel_many` ON [[demo1_view1_via_rel_one_rel_many.id]] = [[__je_demo1_view1_via_rel_one_rel_many.value]] WHERE [[demo1_view1_via_rel_one_rel_many.created]] > 1",
},
{
"recursive back relations with non-empty list rule",
"demo3",
"demo4_via_rel_many_cascade.rel_one_cascade.demo4_via_rel_many_cascade.id ?= true",
false,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_many_cascade` ON [[demo3.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je_demo3_demo4_via_rel_many_cascade}}) LEFT JOIN `demo3` `demo3_demo4_via_rel_many_cascade_rel_one_cascade` ON [[demo3_demo4_via_rel_many_cascade_rel_one_cascade.id]] = [[demo3_demo4_via_rel_many_cascade.rel_one_cascade]] LEFT JOIN `demo4` `demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade` ON [[demo3_demo4_via_rel_many_cascade_rel_one_cascade.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je_demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade}}) WHERE (({:TEST} IS NOT '' AND {:TEST} IS NOT {:TEST})) AND ([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.id]] = 1)",
},
{
"recursive back relations with non-empty list rule (with allowHiddenFields)",
"demo3",
"demo4_via_rel_many_cascade.rel_one_cascade.demo4_via_rel_many_cascade.id ?= true",
true,
"SELECT DISTINCT `demo3`.* FROM `demo3` LEFT JOIN `demo4` `demo3_demo4_via_rel_many_cascade` ON [[demo3.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[demo3_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je_demo3_demo4_via_rel_many_cascade}}) LEFT JOIN `demo3` `demo3_demo4_via_rel_many_cascade_rel_one_cascade` ON [[demo3_demo4_via_rel_many_cascade_rel_one_cascade.id]] = [[demo3_demo4_via_rel_many_cascade.rel_one_cascade]] LEFT JOIN `demo4` `demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade` ON [[demo3_demo4_via_rel_many_cascade_rel_one_cascade.id]] IN (SELECT [[__je_demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.value]] FROM json_each(CASE WHEN iif(json_valid([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]]), json_type([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]])='array', FALSE) THEN [[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]] ELSE json_array([[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.rel_many_cascade]]) END) {{__je_demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade}}) WHERE [[demo3_demo4_via_rel_many_cascade_rel_one_cascade_demo4_via_rel_many_cascade.id]] = 1",
},
{
"@collection join (opt/any operators)",
"demo4",
"@collection.demo1.text ?> true || @collection.demo2.active ?> true || @collection.demo1:demo1_alias.file_one ?> true",
true,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo1` `__collection_demo1` LEFT JOIN `demo2` `__collection_demo2` LEFT JOIN `demo1` `__collection_alias_demo1_alias` WHERE ([[__collection_demo1.text]] > 1 OR [[__collection_demo2.active]] > 1 OR [[__collection_alias_demo1_alias.file_one]] > 1)",
},
{
"@collection join (multi-match operators)",
"demo4",
"@collection.demo1.text > true || @collection.demo2.active > true || @collection.demo1.file_one > true",
true,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `demo1` `__collection_demo1` LEFT JOIN `demo2` `__collection_demo2` WHERE ((([[__collection_demo1.text]] > 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm___collection_demo1.text]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN `demo1` `__mm___collection_demo1` WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] > 1)))) OR (([[__collection_demo2.active]] > 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm___collection_demo2.active]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN `demo2` `__mm___collection_demo2` WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] > 1)))) OR (([[__collection_demo1.file_one]] > 1) AND (NOT EXISTS (SELECT 1 FROM (SELECT [[__mm___collection_demo1.file_one]] as [[multiMatchValue]] FROM `demo4` `__mm_demo4` LEFT JOIN `demo1` `__mm___collection_demo1` WHERE `__mm_demo4`.`id` = `demo4`.`id`) {{__smTEST}} WHERE NOT ([[__smTEST.multiMatchValue]] > 1)))))",
},
{
"@request.auth fields",
"demo4",
"@request.auth.id > true || @request.auth.username > true || @request.auth.rel.title > true || @request.body.demo < true || @request.auth.missingA.missingB > false",
true,
"SELECT DISTINCT `demo4`.* FROM `demo4` LEFT JOIN `users` `__auth_users` ON `__auth_users`.`id`={:p0} LEFT JOIN `demo2` `__auth_users_rel` ON [[__auth_users_rel.id]] = [[__auth_users.rel]] WHERE ({:TEST} > 1 OR [[__auth_users.username]] > 1 OR [[__auth_users_rel.title]] > 1 OR NULL < 1 OR NULL > 0)",
},
{
"@request.* static fields",
"demo4",
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/mfa_model_test.go | core/mfa_model_test.go | package core_test
import (
"fmt"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestNewMFA(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfa := core.NewMFA(app)
if mfa.Collection().Name != core.CollectionNameMFAs {
t.Fatalf("Expected record with %q collection, got %q", core.CollectionNameMFAs, mfa.Collection().Name)
}
}
func TestMFAProxyRecord(t *testing.T) {
t.Parallel()
record := core.NewRecord(core.NewBaseCollection("test"))
record.Id = "test_id"
mfa := core.MFA{}
mfa.SetProxyRecord(record)
if mfa.ProxyRecord() == nil || mfa.ProxyRecord().Id != record.Id {
t.Fatalf("Expected proxy record with id %q, got %v", record.Id, mfa.ProxyRecord())
}
}
func TestMFARecordRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfa := core.NewMFA(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
mfa.SetRecordRef(testValue)
if v := mfa.RecordRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := mfa.GetString("recordRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestMFACollectionRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfa := core.NewMFA(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
mfa.SetCollectionRef(testValue)
if v := mfa.CollectionRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := mfa.GetString("collectionRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestMFAMethod(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfa := core.NewMFA(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
mfa.SetMethod(testValue)
if v := mfa.Method(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := mfa.GetString("method"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestMFACreated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfa := core.NewMFA(app)
if v := mfa.Created().String(); v != "" {
t.Fatalf("Expected empty created, got %q", v)
}
now := types.NowDateTime()
mfa.SetRaw("created", now)
if v := mfa.Created().String(); v != now.String() {
t.Fatalf("Expected %q created, got %q", now.String(), v)
}
}
func TestMFAUpdated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfa := core.NewMFA(app)
if v := mfa.Updated().String(); v != "" {
t.Fatalf("Expected empty updated, got %q", v)
}
now := types.NowDateTime()
mfa.SetRaw("updated", now)
if v := mfa.Updated().String(); v != now.String() {
t.Fatalf("Expected %q updated, got %q", now.String(), v)
}
}
func TestMFAHasExpired(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
now := types.NowDateTime()
mfa := core.NewMFA(app)
mfa.SetRaw("created", now.Add(-5*time.Minute))
scenarios := []struct {
maxElapsed time.Duration
expected bool
}{
{0 * time.Minute, true},
{3 * time.Minute, true},
{5 * time.Minute, true},
{6 * time.Minute, false},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.maxElapsed.String()), func(t *testing.T) {
result := mfa.HasExpired(s.maxElapsed)
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
func TestMFAPreValidate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
mfasCol, err := app.FindCollectionByNameOrId(core.CollectionNameMFAs)
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
t.Run("no proxy record", func(t *testing.T) {
mfa := &core.MFA{}
if err := app.Validate(mfa); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("non-MFA collection", func(t *testing.T) {
mfa := &core.MFA{}
mfa.SetProxyRecord(core.NewRecord(core.NewBaseCollection("invalid")))
mfa.SetRecordRef(user.Id)
mfa.SetCollectionRef(user.Collection().Id)
mfa.SetMethod("test123")
if err := app.Validate(mfa); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("MFA collection", func(t *testing.T) {
mfa := &core.MFA{}
mfa.SetProxyRecord(core.NewRecord(mfasCol))
mfa.SetRecordRef(user.Id)
mfa.SetCollectionRef(user.Collection().Id)
mfa.SetMethod("test123")
if err := app.Validate(mfa); err != nil {
t.Fatalf("Expected nil validation error, got %v", err)
}
})
}
func TestMFAValidateHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
mfa func() *core.MFA
expectErrors []string
}{
{
"empty",
func() *core.MFA {
return core.NewMFA(app)
},
[]string{"collectionRef", "recordRef", "method"},
},
{
"non-auth collection",
func() *core.MFA {
mfa := core.NewMFA(app)
mfa.SetCollectionRef(demo1.Collection().Id)
mfa.SetRecordRef(demo1.Id)
mfa.SetMethod("test123")
return mfa
},
[]string{"collectionRef"},
},
{
"missing record id",
func() *core.MFA {
mfa := core.NewMFA(app)
mfa.SetCollectionRef(user.Collection().Id)
mfa.SetRecordRef("missing")
mfa.SetMethod("test123")
return mfa
},
[]string{"recordRef"},
},
{
"valid ref",
func() *core.MFA {
mfa := core.NewMFA(app)
mfa.SetCollectionRef(user.Collection().Id)
mfa.SetRecordRef(user.Id)
mfa.SetMethod("test123")
return mfa
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := app.Validate(s.mfa())
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/settings_model_test.go | core/settings_model_test.go | package core_test
import (
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/mailer"
)
func TestSettingsDelete(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
err := app.Delete(app.Settings())
if err == nil {
t.Fatal("Exected settings delete to fail")
}
}
func TestSettingsMerge(t *testing.T) {
s1 := &core.Settings{}
s1.Meta.AppURL = "app_url" // should be unset
s2 := &core.Settings{}
s2.Meta.AppName = "test"
s2.Logs.MaxDays = 123
s2.SMTP.Host = "test"
s2.SMTP.Enabled = true
s2.S3.Enabled = true
s2.S3.Endpoint = "test"
s2.Backups.Cron = "* * * * *"
s2.Batch.Timeout = 15
if err := s1.Merge(s2); err != nil {
t.Fatal(err)
}
s1Encoded, err := json.Marshal(s1)
if err != nil {
t.Fatal(err)
}
s2Encoded, err := json.Marshal(s2)
if err != nil {
t.Fatal(err)
}
if string(s1Encoded) != string(s2Encoded) {
t.Fatalf("Expected the same serialization, got\n%v\nVS\n%v", string(s1Encoded), string(s2Encoded))
}
}
func TestSettingsClone(t *testing.T) {
s1 := &core.Settings{}
s1.Meta.AppName = "test_name"
s2, err := s1.Clone()
if err != nil {
t.Fatal(err)
}
s1Bytes, err := json.Marshal(s1)
if err != nil {
t.Fatal(err)
}
s2Bytes, err := json.Marshal(s2)
if err != nil {
t.Fatal(err)
}
if string(s1Bytes) != string(s2Bytes) {
t.Fatalf("Expected equivalent serialization, got %v VS %v", string(s1Bytes), string(s2Bytes))
}
// verify that it is a deep copy
s2.Meta.AppName = "new_test_name"
if s1.Meta.AppName == s2.Meta.AppName {
t.Fatalf("Expected s1 and s2 to have different Meta.AppName, got %s", s1.Meta.AppName)
}
}
func TestSettingsMarshalJSON(t *testing.T) {
settings := &core.Settings{}
// control fields
settings.Meta.AppName = "test123"
settings.SMTP.Username = "abc"
// secrets
testSecret := "test_secret"
settings.SMTP.Password = testSecret
settings.S3.Secret = testSecret
settings.Backups.S3.Secret = testSecret
raw, err := json.Marshal(settings)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
expected := `{"smtp":{"enabled":false,"port":0,"host":"","username":"abc","authMethod":"","tls":false,"localName":""},"backups":{"cron":"","cronMaxKeep":0,"s3":{"enabled":false,"bucket":"","region":"","endpoint":"","accessKey":"","forcePathStyle":false}},"s3":{"enabled":false,"bucket":"","region":"","endpoint":"","accessKey":"","forcePathStyle":false},"meta":{"appName":"test123","appURL":"","senderName":"","senderAddress":"","hideControls":false},"rateLimits":{"rules":[],"enabled":false},"trustedProxy":{"headers":[],"useLeftmostIP":false},"batch":{"enabled":false,"maxRequests":0,"timeout":0,"maxBodySize":0},"logs":{"maxDays":0,"minLevel":0,"logIP":false,"logAuthId":false}}`
if rawStr != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, rawStr)
}
}
func TestSettingsValidate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
s := app.Settings()
// set invalid settings data
s.Meta.AppName = ""
s.Logs.MaxDays = -10
s.SMTP.Enabled = true
s.SMTP.Host = ""
s.S3.Enabled = true
s.S3.Endpoint = "invalid"
s.Backups.Cron = "invalid"
s.Backups.CronMaxKeep = -10
s.Batch.Enabled = true
s.Batch.MaxRequests = -1
s.Batch.Timeout = -1
s.RateLimits.Enabled = true
s.RateLimits.Rules = nil
// check if Validate() is triggering the members validate methods.
err := app.Validate(s)
if err == nil {
t.Fatalf("Expected error, got nil")
}
expectations := []string{
`"meta":{`,
`"logs":{`,
`"smtp":{`,
`"s3":{`,
`"backups":{`,
`"batch":{`,
`"rateLimits":{`,
}
errBytes, _ := json.Marshal(err)
jsonErr := string(errBytes)
for _, expected := range expectations {
if !strings.Contains(jsonErr, expected) {
t.Errorf("Expected error key %s in %v", expected, jsonErr)
}
}
}
func TestMetaConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.MetaConfig
expectedErrors []string
}{
{
"zero values",
core.MetaConfig{},
[]string{
"appName",
"appURL",
"senderName",
"senderAddress",
},
},
{
"invalid data",
core.MetaConfig{
AppName: strings.Repeat("a", 300),
AppURL: "test",
SenderName: strings.Repeat("a", 300),
SenderAddress: "invalid_email",
},
[]string{
"appName",
"appURL",
"senderName",
"senderAddress",
},
},
{
"valid data",
core.MetaConfig{
AppName: "test",
AppURL: "https://example.com",
SenderName: "test",
SenderAddress: "test@example.com",
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestLogsConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.LogsConfig
expectedErrors []string
}{
{
"zero values",
core.LogsConfig{},
[]string{},
},
{
"invalid data",
core.LogsConfig{MaxDays: -1},
[]string{"maxDays"},
},
{
"valid data",
core.LogsConfig{MaxDays: 2},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestSMTPConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.SMTPConfig
expectedErrors []string
}{
{
"zero values (disabled)",
core.SMTPConfig{},
[]string{},
},
{
"zero values (enabled)",
core.SMTPConfig{Enabled: true},
[]string{"host", "port"},
},
{
"invalid data",
core.SMTPConfig{
Enabled: true,
Host: "test:test:test",
Port: -10,
LocalName: "invalid!",
AuthMethod: "invalid",
},
[]string{"host", "port", "authMethod", "localName"},
},
{
"valid data (no explicit auth method and localName)",
core.SMTPConfig{
Enabled: true,
Host: "example.com",
Port: 100,
TLS: true,
},
[]string{},
},
{
"valid data (explicit auth method and localName)",
core.SMTPConfig{
Enabled: true,
Host: "example.com",
Port: 100,
AuthMethod: mailer.SMTPAuthLogin,
LocalName: "example.com",
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestS3ConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.S3Config
expectedErrors []string
}{
{
"zero values (disabled)",
core.S3Config{},
[]string{},
},
{
"zero values (enabled)",
core.S3Config{Enabled: true},
[]string{
"bucket",
"region",
"endpoint",
"accessKey",
"secret",
},
},
{
"invalid data",
core.S3Config{
Enabled: true,
Endpoint: "test:test:test",
},
[]string{
"bucket",
"region",
"endpoint",
"accessKey",
"secret",
},
},
{
"valid data (url endpoint)",
core.S3Config{
Enabled: true,
Endpoint: "https://localhost:8090",
Bucket: "test",
Region: "test",
AccessKey: "test",
Secret: "test",
},
[]string{},
},
{
"valid data (hostname endpoint)",
core.S3Config{
Enabled: true,
Endpoint: "example.com",
Bucket: "test",
Region: "test",
AccessKey: "test",
Secret: "test",
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestBackupsConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.BackupsConfig
expectedErrors []string
}{
{
"zero value",
core.BackupsConfig{},
[]string{},
},
{
"invalid cron",
core.BackupsConfig{
Cron: "invalid",
CronMaxKeep: 0,
},
[]string{"cron", "cronMaxKeep"},
},
{
"invalid enabled S3",
core.BackupsConfig{
S3: core.S3Config{
Enabled: true,
},
},
[]string{"s3"},
},
{
"valid data",
core.BackupsConfig{
S3: core.S3Config{
Enabled: true,
Endpoint: "example.com",
Bucket: "test",
Region: "test",
AccessKey: "test",
Secret: "test",
},
Cron: "*/10 * * * *",
CronMaxKeep: 1,
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestBatchConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.BatchConfig
expectedErrors []string
}{
{
"zero value",
core.BatchConfig{},
[]string{},
},
{
"zero value (enabled)",
core.BatchConfig{Enabled: true},
[]string{"maxRequests", "timeout"},
},
{
"invalid data (negative values)",
core.BatchConfig{
MaxRequests: -1,
Timeout: -1,
MaxBodySize: -1,
},
[]string{"maxRequests", "timeout", "maxBodySize"},
},
{
"min fields valid data",
core.BatchConfig{
Enabled: true,
MaxRequests: 1,
Timeout: 1,
},
[]string{},
},
{
"all fields valid data",
core.BatchConfig{
Enabled: true,
MaxRequests: 10,
Timeout: 1,
MaxBodySize: 1,
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestRateLimitsConfigValidate(t *testing.T) {
scenarios := []struct {
name string
config core.RateLimitsConfig
expectedErrors []string
}{
{
"zero value (disabled)",
core.RateLimitsConfig{},
[]string{},
},
{
"zero value (enabled)",
core.RateLimitsConfig{Enabled: true},
[]string{"rules"},
},
{
"invalid data",
core.RateLimitsConfig{
Enabled: true,
Rules: []core.RateLimitRule{
{
Label: "/123abc/",
Duration: 1,
MaxRequests: 2,
},
{
Label: "!abc",
Duration: -1,
MaxRequests: -1,
},
},
},
[]string{"rules"},
},
{
"valid data",
core.RateLimitsConfig{
Enabled: true,
Rules: []core.RateLimitRule{
{
Label: "123_abc",
Duration: 1,
MaxRequests: 2,
},
{
Label: "/456-abc",
Duration: 1,
MaxRequests: 2,
},
},
},
[]string{},
},
{
"duplicated rules with the same audience",
core.RateLimitsConfig{
Enabled: true,
Rules: []core.RateLimitRule{
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
},
{
Label: "/a",
Duration: 2,
MaxRequests: 3,
},
},
},
[]string{"rules"},
},
{
"duplicated rule with conflicting audience (A)",
core.RateLimitsConfig{
Enabled: true,
Rules: []core.RateLimitRule{
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
},
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
Audience: core.RateLimitRuleAudienceGuest,
},
},
},
[]string{"rules"},
},
{
"duplicated rule with conflicting audience (B)",
core.RateLimitsConfig{
Enabled: true,
Rules: []core.RateLimitRule{
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
Audience: core.RateLimitRuleAudienceAuth,
},
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
},
},
},
[]string{"rules"},
},
{
"duplicated rule with non-conflicting audience",
core.RateLimitsConfig{
Enabled: true,
Rules: []core.RateLimitRule{
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
Audience: core.RateLimitRuleAudienceAuth,
},
{
Label: "/a",
Duration: 1,
MaxRequests: 2,
Audience: core.RateLimitRuleAudienceGuest,
},
},
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.config.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestRateLimitsFindRateLimitRule(t *testing.T) {
limits := core.RateLimitsConfig{
Rules: []core.RateLimitRule{
{Label: "abc"},
{Label: "def", Audience: core.RateLimitRuleAudienceGuest},
{Label: "/test/a", Audience: core.RateLimitRuleAudienceGuest},
{Label: "POST /test/a"},
{Label: "/test/a/", Audience: core.RateLimitRuleAudienceAuth},
{Label: "POST /test/a/"},
},
}
scenarios := []struct {
labels []string
audience []string
expected string
}{
{[]string{}, []string{}, ""},
{[]string{"missing"}, []string{}, ""},
{[]string{"abc"}, []string{}, "abc"},
{[]string{"abc"}, []string{core.RateLimitRuleAudienceGuest}, ""},
{[]string{"abc"}, []string{core.RateLimitRuleAudienceAuth}, ""},
{[]string{"def"}, []string{core.RateLimitRuleAudienceGuest}, "def"},
{[]string{"def"}, []string{core.RateLimitRuleAudienceAuth}, ""},
{[]string{"/test"}, []string{}, ""},
{[]string{"/test/a"}, []string{}, "/test/a"},
{[]string{"/test/a"}, []string{core.RateLimitRuleAudienceAuth}, "/test/a/"},
{[]string{"/test/a"}, []string{core.RateLimitRuleAudienceGuest}, "/test/a"},
{[]string{"GET /test/a"}, []string{}, ""},
{[]string{"POST /test/a"}, []string{}, "POST /test/a"},
{[]string{"/test/a/b/c"}, []string{}, "/test/a/"},
{[]string{"/test/a/b/c"}, []string{core.RateLimitRuleAudienceAuth}, "/test/a/"},
{[]string{"/test/a/b/c"}, []string{core.RateLimitRuleAudienceGuest}, ""},
{[]string{"GET /test/a/b/c"}, []string{}, ""},
{[]string{"POST /test/a/b/c"}, []string{}, "POST /test/a/"},
{[]string{"/test/a", "abc"}, []string{}, "/test/a"}, // priority checks
}
for _, s := range scenarios {
t.Run(strings.Join(s.labels, "_")+":"+strings.Join(s.audience, "_"), func(t *testing.T) {
rule, ok := limits.FindRateLimitRule(s.labels, s.audience...)
hasLabel := rule.Label != ""
if hasLabel != ok {
t.Fatalf("Expected hasLabel %v, got %v", hasLabel, ok)
}
if rule.Label != s.expected {
t.Fatalf("Expected rule with label %q, got %q", s.expected, rule.Label)
}
})
}
}
func TestRateLimitRuleValidate(t *testing.T) {
scenarios := []struct {
name string
rule core.RateLimitRule
expectedErrors []string
}{
{
"zero value",
core.RateLimitRule{},
[]string{"label", "duration", "maxRequests"},
},
{
"invalid data",
core.RateLimitRule{
Label: "@abc",
Duration: -1,
MaxRequests: -1,
Audience: "invalid",
},
[]string{"label", "duration", "maxRequests", "audience"},
},
{
"valid data (name)",
core.RateLimitRule{
Label: "abc:123",
Duration: 1,
MaxRequests: 1,
},
[]string{},
},
{
"valid data (name:action)",
core.RateLimitRule{
Label: "abc:123",
Duration: 1,
MaxRequests: 1,
},
[]string{},
},
{
"valid data (*:action)",
core.RateLimitRule{
Label: "*:123",
Duration: 1,
MaxRequests: 1,
},
[]string{},
},
{
"valid data (path /a/b)",
core.RateLimitRule{
Label: "/a/b",
Duration: 1,
MaxRequests: 1,
},
[]string{},
},
{
"valid data (path POST /a/b)",
core.RateLimitRule{
Label: "POST /a/b/",
Duration: 1,
MaxRequests: 1,
},
[]string{},
},
{
"invalid audience",
core.RateLimitRule{
Label: "/a/b/",
Duration: 1,
MaxRequests: 1,
Audience: "invalid",
},
[]string{"audience"},
},
{
"valid audience - " + core.RateLimitRuleAudienceGuest,
core.RateLimitRule{
Label: "POST /a/b/",
Duration: 1,
MaxRequests: 1,
Audience: core.RateLimitRuleAudienceGuest,
},
[]string{},
},
{
"valid audience - " + core.RateLimitRuleAudienceAuth,
core.RateLimitRule{
Label: "POST /a/b/",
Duration: 1,
MaxRequests: 1,
Audience: core.RateLimitRuleAudienceAuth,
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.rule.Validate()
tests.TestValidationErrors(t, result, s.expectedErrors)
})
}
}
func TestRateLimitRuleDurationTime(t *testing.T) {
scenarios := []struct {
rule core.RateLimitRule
expected time.Duration
}{
{core.RateLimitRule{}, 0 * time.Second},
{core.RateLimitRule{Duration: 1234}, 1234 * time.Second},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d", i, s.rule.Duration), func(t *testing.T) {
result := s.rule.DurationTime()
if result != s.expected {
t.Fatalf("Expected duration %d, got %d", s.expected, result)
}
})
}
}
func TestRateLimitRuleString(t *testing.T) {
scenarios := []struct {
name string
rule core.RateLimitRule
expected string
}{
{
"empty",
core.RateLimitRule{},
`{"label":"","audience":"","duration":0,"maxRequests":0}`,
},
{
"all fields",
core.RateLimitRule{
Label: "POST /a/b/",
Duration: 1,
MaxRequests: 2,
Audience: core.RateLimitRuleAudienceAuth,
},
`{"label":"POST /a/b/","audience":"@auth","duration":1,"maxRequests":2}`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result := s.rule.String()
if result != s.expected {
t.Fatalf("Expected string\n%s\ngot\n%s", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_model_superusers_test.go | core/record_model_superusers_test.go | package core_test
import (
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestRecordIsSuperUser(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
expected bool
}{
{demo1, false},
{user, false},
{superuser, true},
}
for _, s := range scenarios {
t.Run(s.record.Collection().Name, func(t *testing.T) {
result := s.record.IsSuperuser()
if result != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, result)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_geo_point_test.go | core/field_geo_point_test.go | package core_test
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestGeoPointFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeGeoPoint)
}
func TestGeoPointFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.GeoPointField{}
expected := `JSON DEFAULT '{"lon":0,"lat":0}' NOT NULL`
if v := f.ColumnType(app); v != expected {
t.Fatalf("Expected\n%q\ngot\n%q", expected, v)
}
}
func TestGeoPointFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f := &core.GeoPointField{}
record := core.NewRecord(core.NewBaseCollection("test"))
scenarios := []struct {
raw any
expected string
}{
{nil, `{"lon":0,"lat":0}`},
{"", `{"lon":0,"lat":0}`},
{[]byte{}, `{"lon":0,"lat":0}`},
{map[string]any{}, `{"lon":0,"lat":0}`},
{types.GeoPoint{Lon: 10, Lat: 20}, `{"lon":10,"lat":20}`},
{&types.GeoPoint{Lon: 10, Lat: 20}, `{"lon":10,"lat":20}`},
{[]byte(`{"lon": 10, "lat": 20}`), `{"lon":10,"lat":20}`},
{map[string]any{"lon": 10, "lat": 20}, `{"lon":10,"lat":20}`},
{map[string]float64{"lon": 10, "lat": 20}, `{"lon":10,"lat":20}`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v", i, s.raw), func(t *testing.T) {
v, err := f.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected\n%s\ngot\n%s", s.expected, rawStr)
}
})
}
}
func TestGeoPointFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field *core.GeoPointField
record func() *core.Record
expectError bool
}{
{
"invalid raw value",
&core.GeoPointField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", 123)
return record
},
true,
},
{
"zero field value (non-required)",
&core.GeoPointField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{})
return record
},
false,
},
{
"zero field value (required)",
&core.GeoPointField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{})
return record
},
true,
},
{
"non-zero Lat field value (required)",
&core.GeoPointField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lat: 1})
return record
},
false,
},
{
"non-zero Lon field value (required)",
&core.GeoPointField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lon: 1})
return record
},
false,
},
{
"non-zero Lat-Lon field value (required)",
&core.GeoPointField{Name: "test", Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lon: -1, Lat: -2})
return record
},
false,
},
{
"lat < -90",
&core.GeoPointField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lat: -90.1})
return record
},
true,
},
{
"lat > 90",
&core.GeoPointField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lat: 90.1})
return record
},
true,
},
{
"lon < -180",
&core.GeoPointField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lon: -180.1})
return record
},
true,
},
{
"lon > 180",
&core.GeoPointField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", types.GeoPoint{Lon: 180.1})
return record
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestGeoPointFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeGeoPoint)
testDefaultFieldNameValidation(t, core.FieldTypeGeoPoint)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_test.go | core/collection_model_test.go | package core_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestNewCollection(t *testing.T) {
t.Parallel()
scenarios := []struct {
typ string
name string
expected []string
}{
{
"",
"",
[]string{
`"id":"pbc_`,
`"name":""`,
`"type":"base"`,
`"system":false`,
`"indexes":[]`,
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
{
"unknown",
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"base"`,
`"system":false`,
`"indexes":[]`,
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
{
"base",
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"base"`,
`"system":false`,
`"indexes":[]`,
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
{
"view",
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"view"`,
`"indexes":[]`,
`"fields":[]`,
`"system":false`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
{
"auth",
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"auth"`,
`"fields":[{`,
`"system":false`,
`"type":"text"`,
`"type":"email"`,
`"name":"id"`,
`"name":"email"`,
`"name":"password"`,
`"name":"tokenKey"`,
`"name":"emailVisibility"`,
`"name":"verified"`,
`idx_email`,
`idx_tokenKey`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
`"identityFields":["email"]`,
},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.typ, s.name), func(t *testing.T) {
result := core.NewCollection(s.typ, s.name).String()
for _, part := range s.expected {
if !strings.Contains(result, part) {
t.Fatalf("Missing part %q in\n%v", part, result)
}
}
})
}
}
func TestNewBaseCollection(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
expected []string
}{
{
"",
[]string{
`"id":"pbc_`,
`"name":""`,
`"type":"base"`,
`"system":false`,
`"indexes":[]`,
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
{
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"base"`,
`"system":false`,
`"indexes":[]`,
`"fields":[{`,
`"name":"id"`,
`"type":"text"`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.name), func(t *testing.T) {
result := core.NewBaseCollection(s.name).String()
for _, part := range s.expected {
if !strings.Contains(result, part) {
t.Fatalf("Missing part %q in\n%v", part, result)
}
}
})
}
}
func TestNewViewCollection(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
expected []string
}{
{
"",
[]string{
`"id":"pbc_`,
`"name":""`,
`"type":"view"`,
`"indexes":[]`,
`"fields":[]`,
`"system":false`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
{
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"view"`,
`"indexes":[]`,
`"fields":[]`,
`"system":false`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.name), func(t *testing.T) {
result := core.NewViewCollection(s.name).String()
for _, part := range s.expected {
if !strings.Contains(result, part) {
t.Fatalf("Missing part %q in\n%v", part, result)
}
}
})
}
}
func TestNewAuthCollection(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
expected []string
}{
{
"",
[]string{
`"id":""`,
`"name":""`,
`"type":"auth"`,
`"fields":[{`,
`"system":false`,
`"type":"text"`,
`"type":"email"`,
`"name":"id"`,
`"name":"email"`,
`"name":"password"`,
`"name":"tokenKey"`,
`"name":"emailVisibility"`,
`"name":"verified"`,
`idx_email`,
`idx_tokenKey`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
`"identityFields":["email"]`,
},
},
{
"test",
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"auth"`,
`"fields":[{`,
`"system":false`,
`"type":"text"`,
`"type":"email"`,
`"name":"id"`,
`"name":"email"`,
`"name":"password"`,
`"name":"tokenKey"`,
`"name":"emailVisibility"`,
`"name":"verified"`,
`idx_email`,
`idx_tokenKey`,
`"listRule":null`,
`"viewRule":null`,
`"createRule":null`,
`"updateRule":null`,
`"deleteRule":null`,
`"identityFields":["email"]`,
},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.name), func(t *testing.T) {
result := core.NewAuthCollection(s.name).String()
for _, part := range s.expected {
if !strings.Contains(result, part) {
t.Fatalf("Missing part %q in\n%v", part, result)
}
}
})
}
}
func TestCollectionTableName(t *testing.T) {
t.Parallel()
c := core.NewBaseCollection("test")
if c.TableName() != "_collections" {
t.Fatalf("Expected tableName %q, got %q", "_collections", c.TableName())
}
}
func TestCollectionBaseFilesPath(t *testing.T) {
t.Parallel()
c := core.Collection{}
if c.BaseFilesPath() != "" {
t.Fatalf("Expected empty string, got %q", c.BaseFilesPath())
}
c.Id = "test"
if c.BaseFilesPath() != c.Id {
t.Fatalf("Expected %q, got %q", c.Id, c.BaseFilesPath())
}
}
func TestCollectionIsBase(t *testing.T) {
t.Parallel()
scenarios := []struct {
typ string
expected bool
}{
{"unknown", false},
{core.CollectionTypeBase, true},
{core.CollectionTypeView, false},
{core.CollectionTypeAuth, false},
}
for _, s := range scenarios {
t.Run(s.typ, func(t *testing.T) {
c := core.Collection{}
c.Type = s.typ
if v := c.IsBase(); v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestCollectionIsView(t *testing.T) {
t.Parallel()
scenarios := []struct {
typ string
expected bool
}{
{"unknown", false},
{core.CollectionTypeBase, false},
{core.CollectionTypeView, true},
{core.CollectionTypeAuth, false},
}
for _, s := range scenarios {
t.Run(s.typ, func(t *testing.T) {
c := core.Collection{}
c.Type = s.typ
if v := c.IsView(); v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestCollectionIsAuth(t *testing.T) {
t.Parallel()
scenarios := []struct {
typ string
expected bool
}{
{"unknown", false},
{core.CollectionTypeBase, false},
{core.CollectionTypeView, false},
{core.CollectionTypeAuth, true},
}
for _, s := range scenarios {
t.Run(s.typ, func(t *testing.T) {
c := core.Collection{}
c.Type = s.typ
if v := c.IsAuth(); v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestCollectionPostScan(t *testing.T) {
t.Parallel()
rawOptions := types.JSONRaw(`{
"viewQuery":"select 1",
"authRule":"1=2"
}`)
scenarios := []struct {
typ string
rawOptions types.JSONRaw
expected []string
}{
{
core.CollectionTypeBase,
rawOptions,
[]string{
`lastSavedPK:"test"`,
`ViewQuery:""`,
`AuthRule:(*string)(nil)`,
},
},
{
core.CollectionTypeView,
rawOptions,
[]string{
`lastSavedPK:"test"`,
`ViewQuery:"select 1"`,
`AuthRule:(*string)(nil)`,
},
},
{
core.CollectionTypeAuth,
rawOptions,
[]string{
`lastSavedPK:"test"`,
`ViewQuery:""`,
`AuthRule:(*string)(0x`,
},
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.typ), func(t *testing.T) {
c := core.Collection{}
c.Id = "test"
c.Type = s.typ
c.RawOptions = s.rawOptions
err := c.PostScan()
if err != nil {
t.Fatal(err)
}
if c.IsNew() {
t.Fatal("Expected the collection to be marked as not new")
}
rawModel := fmt.Sprintf("%#v", c)
for _, part := range s.expected {
if !strings.Contains(rawModel, part) {
t.Fatalf("Missing part %q in\n%v", part, rawModel)
}
}
})
}
}
func TestCollectionUnmarshalJSON(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
raw string
collection func() *core.Collection
expected []string
notExpected []string
}{
{
"base new empty",
`{"type":"base","name":"test","listRule":"1=2","authRule":"1=3","viewQuery":"abc"}`,
func() *core.Collection {
return &core.Collection{}
},
[]string{
`"type":"base"`,
`"id":"pbc_`,
`"name":"test"`,
`"listRule":"1=2"`,
`"fields":[`,
`"name":"id"`,
`"indexes":[]`,
},
[]string{
`"authRule":"1=3"`,
`"viewQuery":"abc"`,
},
},
{
"view new empty",
`{"type":"view","name":"test","listRule":"1=2","authRule":"1=3","viewQuery":"abc"}`,
func() *core.Collection {
return &core.Collection{}
},
[]string{
`"type":"view"`,
`"id":"pbc_`,
`"name":"test"`,
`"listRule":"1=2"`,
`"fields":[]`,
`"viewQuery":"abc"`,
`"indexes":[]`,
},
[]string{
`"authRule":"1=3"`,
},
},
{
"auth new empty",
`{"type":"auth","name":"test","listRule":"1=2","authRule":"1=3","viewQuery":"abc"}`,
func() *core.Collection {
return &core.Collection{}
},
[]string{
`"type":"auth"`,
`"id":"pbc_`,
`"name":"test"`,
`"listRule":"1=2"`,
`"authRule":"1=3"`,
`"fields":[`,
`"name":"id"`,
},
[]string{
`"indexes":[]`,
`"viewQuery":"abc"`,
},
},
{
"new but with set type (no default fields load)",
`{"type":"base","name":"test","listRule":"1=2","authRule":"1=3","viewQuery":"abc"}`,
func() *core.Collection {
c := &core.Collection{}
c.Type = core.CollectionTypeBase
return c
},
[]string{
`"type":"base"`,
`"id":""`,
`"name":"test"`,
`"listRule":"1=2"`,
`"fields":[]`,
},
[]string{
`"authRule":"1=3"`,
`"viewQuery":"abc"`,
},
},
{
"existing (no default fields load)",
`{"type":"auth","name":"test","listRule":"1=2","authRule":"1=3","viewQuery":"abc"}`,
func() *core.Collection {
c, _ := app.FindCollectionByNameOrId("demo1")
return c
},
[]string{
`"type":"auth"`,
`"name":"test"`,
`"listRule":"1=2"`,
`"authRule":"1=3"`,
`"fields":[`,
`"name":"id"`,
},
[]string{
`"name":"tokenKey"`,
`"viewQuery":"abc"`,
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := s.collection()
err := json.Unmarshal([]byte(s.raw), collection)
if err != nil {
t.Fatal(err)
}
rawResult, err := json.Marshal(collection)
if err != nil {
t.Fatal(err)
}
rawResultStr := string(rawResult)
for _, part := range s.expected {
if !strings.Contains(rawResultStr, part) {
t.Fatalf("Missing expected %q in\n%v", part, rawResultStr)
}
}
for _, part := range s.notExpected {
if strings.Contains(rawResultStr, part) {
t.Fatalf("Didn't expected %q in\n%v", part, rawResultStr)
}
}
})
}
}
func TestCollectionSerialize(t *testing.T) {
scenarios := []struct {
name string
collection func() *core.Collection
expected []string
notExpected []string
}{
{
"base",
func() *core.Collection {
c := core.NewCollection(core.CollectionTypeBase, "test")
c.ViewQuery = "1=1"
c.OAuth2.Providers = []core.OAuth2ProviderConfig{
{Name: "test1", ClientId: "test_client_id1", ClientSecret: "test_client_secret1"},
{Name: "test2", ClientId: "test_client_id2", ClientSecret: "test_client_secret2"},
}
return c
},
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"base"`,
},
[]string{
"verificationTemplate",
"manageRule",
"authRule",
"secret",
"oauth2",
"clientId",
"clientSecret",
"viewQuery",
},
},
{
"view",
func() *core.Collection {
c := core.NewCollection(core.CollectionTypeView, "test")
c.ViewQuery = "1=1"
c.OAuth2.Providers = []core.OAuth2ProviderConfig{
{Name: "test1", ClientId: "test_client_id1", ClientSecret: "test_client_secret1"},
{Name: "test2", ClientId: "test_client_id2", ClientSecret: "test_client_secret2"},
}
return c
},
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"view"`,
`"viewQuery":"1=1"`,
},
[]string{
"verificationTemplate",
"manageRule",
"authRule",
"secret",
"oauth2",
"clientId",
"clientSecret",
},
},
{
"auth",
func() *core.Collection {
c := core.NewCollection(core.CollectionTypeAuth, "test")
c.ViewQuery = "1=1"
c.OAuth2.Providers = []core.OAuth2ProviderConfig{
{Name: "test1", ClientId: "test_client_id1", ClientSecret: "test_client_secret1"},
{Name: "test2", ClientId: "test_client_id2", ClientSecret: "test_client_secret2"},
}
return c
},
[]string{
`"id":"pbc_`,
`"name":"test"`,
`"type":"auth"`,
`"oauth2":{`,
`"providers":[{`,
`"clientId":"test_client_id1"`,
`"clientId":"test_client_id2"`,
},
[]string{
"viewQuery",
"secret",
"clientSecret",
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := s.collection()
raw, err := collection.MarshalJSON()
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != collection.String() {
t.Fatalf("Expected the same serialization, got\n%v\nVS\n%v", collection.String(), rawStr)
}
for _, part := range s.expected {
if !strings.Contains(rawStr, part) {
t.Fatalf("Missing part %q in\n%v", part, rawStr)
}
}
for _, part := range s.notExpected {
if strings.Contains(rawStr, part) {
t.Fatalf("Didn't expect part %q in\n%v", part, rawStr)
}
}
})
}
}
func TestCollectionDBExport(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
date, err := types.ParseDateTime("2024-07-01 01:02:03.456Z")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
typ string
expected string
}{
{
"unknown",
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":"{}","system":true,"type":"unknown","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
{
core.CollectionTypeBase,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":"{}","system":true,"type":"base","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
{
core.CollectionTypeView,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":{"viewQuery":"select 1"},"system":true,"type":"view","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
{
core.CollectionTypeAuth,
`{"createRule":"1=3","created":"2024-07-01 01:02:03.456Z","deleteRule":"1=5","fields":[{"hidden":false,"id":"f1_id","name":"f1","presentable":false,"required":false,"system":true,"type":"bool"},{"hidden":false,"id":"f2_id","name":"f2","presentable":false,"required":true,"system":false,"type":"bool"}],"id":"test_id","indexes":["CREATE INDEX idx1 on test_name(id)","CREATE INDEX idx2 on test_name(id)"],"listRule":"1=1","name":"test_name","options":{"authRule":null,"manageRule":"1=6","authAlert":{"enabled":false,"emailTemplate":{"subject":"","body":""}},"oauth2":{"providers":null,"mappedFields":{"id":"","name":"","username":"","avatarURL":""},"enabled":false},"passwordAuth":{"enabled":false,"identityFields":null},"mfa":{"enabled":false,"duration":0,"rule":""},"otp":{"enabled":false,"duration":0,"length":0,"emailTemplate":{"subject":"","body":""}},"authToken":{"duration":0},"passwordResetToken":{"duration":0},"emailChangeToken":{"duration":0},"verificationToken":{"duration":0},"fileToken":{"duration":0},"verificationTemplate":{"subject":"","body":""},"resetPasswordTemplate":{"subject":"","body":""},"confirmEmailChangeTemplate":{"subject":"","body":""}},"system":true,"type":"auth","updateRule":"1=4","updated":"2024-07-01 01:02:03.456Z","viewRule":"1=7"}`,
},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s", i, s.typ), func(t *testing.T) {
c := core.Collection{}
c.Type = s.typ
c.Id = "test_id"
c.Name = "test_name"
c.System = true
c.ListRule = types.Pointer("1=1")
c.ViewRule = types.Pointer("1=2")
c.CreateRule = types.Pointer("1=3")
c.UpdateRule = types.Pointer("1=4")
c.DeleteRule = types.Pointer("1=5")
c.ManageRule = types.Pointer("1=6")
c.ViewRule = types.Pointer("1=7")
c.Created = date
c.Updated = date
c.Indexes = types.JSONArray[string]{"CREATE INDEX idx1 on test_name(id)", "CREATE INDEX idx2 on test_name(id)"}
c.ViewQuery = "select 1"
c.Fields.Add(&core.BoolField{Id: "f1_id", Name: "f1", System: true})
c.Fields.Add(&core.BoolField{Id: "f2_id", Name: "f2", Required: true})
c.RawOptions = types.JSONRaw(`{"viewQuery": "select 2"}`) // should be ignored
result, err := c.DBExport(app)
if err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
if str := string(raw); str != s.expected {
t.Fatalf("Expected\n%v\ngot\n%v", s.expected, str)
}
})
}
}
func TestCollectionIndexHelpers(t *testing.T) {
t.Parallel()
checkIndexes := func(t *testing.T, indexes, expectedIndexes []string) {
if len(indexes) != len(expectedIndexes) {
t.Fatalf("Expected %d indexes, got %d\n%v", len(expectedIndexes), len(indexes), indexes)
}
for _, idx := range expectedIndexes {
if !slices.Contains(indexes, idx) {
t.Fatalf("Missing index\n%v\nin\n%v", idx, indexes)
}
}
}
c := core.NewBaseCollection("test")
checkIndexes(t, c.Indexes, nil)
c.AddIndex("idx1", false, "colA,colB", "colA != 1")
c.AddIndex("idx2", true, "colA", "")
c.AddIndex("idx3", false, "colA", "")
c.AddIndex("idx3", false, "colB", "") // should overwrite the previous one
idx1 := "CREATE INDEX `idx1` ON `test` (colA,colB) WHERE colA != 1"
idx2 := "CREATE UNIQUE INDEX `idx2` ON `test` (colA)"
idx3 := "CREATE INDEX `idx3` ON `test` (colB)"
checkIndexes(t, c.Indexes, []string{idx1, idx2, idx3})
c.RemoveIndex("iDx2") // case-insensitive
c.RemoveIndex("missing") // noop
checkIndexes(t, c.Indexes, []string{idx1, idx3})
expectedIndexes := map[string]string{
"missing": "",
"idx1": idx1,
// the name is case insensitive
"iDX3": idx3,
}
for key, expectedIdx := range expectedIndexes {
idx := c.GetIndex(key)
if idx != expectedIdx {
t.Errorf("Expected index %q to be\n%v\ngot\n%v", key, expectedIdx, idx)
}
}
}
// -------------------------------------------------------------------
func TestCollectionDelete(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
collection string
disableIntegrityChecks bool
expectError bool
}{
{
name: "unsaved",
collection: "",
expectError: true,
},
{
name: "system",
collection: core.CollectionNameSuperusers,
expectError: true,
},
{
name: "base with references",
collection: "demo1",
expectError: true,
},
{
name: "base with references with disabled integrity checks",
collection: "demo1",
disableIntegrityChecks: true,
expectError: false,
},
{
name: "base without references",
collection: "demo1",
expectError: true,
},
{
name: "view with reference",
collection: "view1",
expectError: true,
},
{
name: "view with references with disabled integrity checks",
collection: "view1",
disableIntegrityChecks: true,
expectError: false,
},
{
name: "view without references",
collection: "view2",
disableIntegrityChecks: true,
expectError: false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
var col *core.Collection
if s.collection == "" {
col = core.NewBaseCollection("test")
} else {
var err error
col, err = app.FindCollectionByNameOrId(s.collection)
if err != nil {
t.Fatal(err)
}
}
if s.disableIntegrityChecks {
col.IntegrityChecks(!s.disableIntegrityChecks)
}
err := app.Delete(col)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
exists := app.HasTable(col.Name)
if !col.IsNew() && exists != hasErr {
t.Fatalf("Expected HasTable %v, got %v", hasErr, exists)
}
if !hasErr {
cache, _ := app.FindCachedCollectionByNameOrId(col.Id)
if cache != nil {
t.Fatal("Expected the collection to be removed from the cache.")
}
}
})
}
}
func TestCollectionModelEventSync(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
testCollections := make([]*core.Collection, 4)
for i := 0; i < 4; i++ {
testCollections[i] = core.NewBaseCollection("sync_test_" + strconv.Itoa(i))
if err := app.Save(testCollections[i]); err != nil {
t.Fatal(err)
}
}
createModelEvent := func() *core.ModelEvent {
event := new(core.ModelEvent)
event.App = app
event.Context = context.Background()
event.Type = "test_a"
event.Model = testCollections[0]
return event
}
createModelErrorEvent := func() *core.ModelErrorEvent {
event := new(core.ModelErrorEvent)
event.ModelEvent = *createModelEvent()
event.Error = errors.New("error_a")
return event
}
changeCollectionEventBefore := func(e *core.CollectionEvent) {
e.Type = "test_b"
//nolint:staticcheck
e.Context = context.WithValue(context.Background(), "test", 123)
e.Collection = testCollections[1]
}
modelEventFinalizerChange := func(e *core.ModelEvent) {
e.Type = "test_c"
//nolint:staticcheck
e.Context = context.WithValue(context.Background(), "test", 456)
e.Model = testCollections[2]
}
changeCollectionEventAfter := func(e *core.CollectionEvent) {
e.Type = "test_d"
//nolint:staticcheck
e.Context = context.WithValue(context.Background(), "test", 789)
e.Collection = testCollections[3]
}
expectedBeforeModelEventHandlerChecks := func(t *testing.T, e *core.ModelEvent) {
if e.Type != "test_a" {
t.Fatalf("Expected type %q, got %q", "test_a", e.Type)
}
if v := e.Context.Value("test"); v != nil {
t.Fatalf("Expected context value %v, got %v", nil, v)
}
if e.Model.PK() != testCollections[0].Id {
t.Fatalf("Expected collection with id %q, got %q (%d)", testCollections[0].Id, e.Model.PK(), 0)
}
}
expectedAfterModelEventHandlerChecks := func(t *testing.T, e *core.ModelEvent) {
if e.Type != "test_d" {
t.Fatalf("Expected type %q, got %q", "test_d", e.Type)
}
if v := e.Context.Value("test"); v != 789 {
t.Fatalf("Expected context value %v, got %v", 789, v)
}
if e.Model.PK() != testCollections[3].Id {
t.Fatalf("Expected collection with id %q, got %q (%d)", testCollections[3].Id, e.Model.PK(), 3)
}
}
expectedBeforeCollectionEventHandlerChecks := func(t *testing.T, e *core.CollectionEvent) {
if e.Type != "test_a" {
t.Fatalf("Expected type %q, got %q", "test_a", e.Type)
}
if v := e.Context.Value("test"); v != nil {
t.Fatalf("Expected context value %v, got %v", nil, v)
}
if e.Collection.Id != testCollections[0].Id {
t.Fatalf("Expected collection with id %q, got %q (%d)", testCollections[0].Id, e.Collection.Id, 0)
}
}
expectedAfterCollectionEventHandlerChecks := func(t *testing.T, e *core.CollectionEvent) {
if e.Type != "test_c" {
t.Fatalf("Expected type %q, got %q", "test_c", e.Type)
}
if v := e.Context.Value("test"); v != 456 {
t.Fatalf("Expected context value %v, got %v", 456, v)
}
if e.Collection.Id != testCollections[2].Id {
t.Fatalf("Expected collection with id %q, got %q (%d)", testCollections[2].Id, e.Collection.Id, 2)
}
}
modelEventFinalizer := func(e *core.ModelEvent) error {
modelEventFinalizerChange(e)
return nil
}
modelErrorEventFinalizer := func(e *core.ModelErrorEvent) error {
modelEventFinalizerChange(&e.ModelEvent)
e.Error = errors.New("error_c")
return nil
}
modelEventHandler := &hook.Handler[*core.ModelEvent]{
Priority: -999,
Func: func(e *core.ModelEvent) error {
t.Run("before model", func(t *testing.T) {
expectedBeforeModelEventHandlerChecks(t, e)
})
_ = e.Next()
t.Run("after model", func(t *testing.T) {
expectedAfterModelEventHandlerChecks(t, e)
})
return nil
},
}
modelErrorEventHandler := &hook.Handler[*core.ModelErrorEvent]{
Priority: -999,
Func: func(e *core.ModelErrorEvent) error {
t.Run("before model error", func(t *testing.T) {
expectedBeforeModelEventHandlerChecks(t, &e.ModelEvent)
if v := e.Error.Error(); v != "error_a" {
t.Fatalf("Expected error %q, got %q", "error_a", v)
}
})
_ = e.Next()
t.Run("after model error", func(t *testing.T) {
expectedAfterModelEventHandlerChecks(t, &e.ModelEvent)
if v := e.Error.Error(); v != "error_d" {
t.Fatalf("Expected error %q, got %q", "error_d", v)
}
})
return nil
},
}
recordEventHandler := &hook.Handler[*core.CollectionEvent]{
Priority: -999,
Func: func(e *core.CollectionEvent) error {
t.Run("before collection", func(t *testing.T) {
expectedBeforeCollectionEventHandlerChecks(t, e)
})
changeCollectionEventBefore(e)
_ = e.Next()
t.Run("after collection", func(t *testing.T) {
expectedAfterCollectionEventHandlerChecks(t, e)
})
changeCollectionEventAfter(e)
return nil
},
}
collectionErrorEventHandler := &hook.Handler[*core.CollectionErrorEvent]{
Priority: -999,
Func: func(e *core.CollectionErrorEvent) error {
t.Run("before collection error", func(t *testing.T) {
expectedBeforeCollectionEventHandlerChecks(t, &e.CollectionEvent)
if v := e.Error.Error(); v != "error_a" {
t.Fatalf("Expected error %q, got %q", "error_c", v)
}
})
changeCollectionEventBefore(&e.CollectionEvent)
e.Error = errors.New("error_b")
_ = e.Next()
t.Run("after collection error", func(t *testing.T) {
expectedAfterCollectionEventHandlerChecks(t, &e.CollectionEvent)
if v := e.Error.Error(); v != "error_c" {
t.Fatalf("Expected error %q, got %q", "error_c", v)
}
})
changeCollectionEventAfter(&e.CollectionEvent)
e.Error = errors.New("error_d")
return nil
},
}
// OnModelValidate
app.OnCollectionValidate().Bind(recordEventHandler)
app.OnModelValidate().Bind(modelEventHandler)
app.OnModelValidate().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelCreate
app.OnCollectionCreate().Bind(recordEventHandler)
app.OnModelCreate().Bind(modelEventHandler)
app.OnModelCreate().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelCreateExecute
app.OnCollectionCreateExecute().Bind(recordEventHandler)
app.OnModelCreateExecute().Bind(modelEventHandler)
app.OnModelCreateExecute().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelAfterCreateSuccess
app.OnCollectionAfterCreateSuccess().Bind(recordEventHandler)
app.OnModelAfterCreateSuccess().Bind(modelEventHandler)
app.OnModelAfterCreateSuccess().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelAfterCreateError
app.OnCollectionAfterCreateError().Bind(collectionErrorEventHandler)
app.OnModelAfterCreateError().Bind(modelErrorEventHandler)
app.OnModelAfterCreateError().Trigger(createModelErrorEvent(), modelErrorEventFinalizer)
// OnModelUpdate
app.OnCollectionUpdate().Bind(recordEventHandler)
app.OnModelUpdate().Bind(modelEventHandler)
app.OnModelUpdate().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelUpdateExecute
app.OnCollectionUpdateExecute().Bind(recordEventHandler)
app.OnModelUpdateExecute().Bind(modelEventHandler)
app.OnModelUpdateExecute().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelAfterUpdateSuccess
app.OnCollectionAfterUpdateSuccess().Bind(recordEventHandler)
app.OnModelAfterUpdateSuccess().Bind(modelEventHandler)
app.OnModelAfterUpdateSuccess().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelAfterUpdateError
app.OnCollectionAfterUpdateError().Bind(collectionErrorEventHandler)
app.OnModelAfterUpdateError().Bind(modelErrorEventHandler)
app.OnModelAfterUpdateError().Trigger(createModelErrorEvent(), modelErrorEventFinalizer)
// OnModelDelete
app.OnCollectionDelete().Bind(recordEventHandler)
app.OnModelDelete().Bind(modelEventHandler)
app.OnModelDelete().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelDeleteExecute
app.OnCollectionDeleteExecute().Bind(recordEventHandler)
app.OnModelDeleteExecute().Bind(modelEventHandler)
app.OnModelDeleteExecute().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelAfterDeleteSuccess
app.OnCollectionAfterDeleteSuccess().Bind(recordEventHandler)
app.OnModelAfterDeleteSuccess().Bind(modelEventHandler)
app.OnModelAfterDeleteSuccess().Trigger(createModelEvent(), modelEventFinalizer)
// OnModelAfterDeleteError
app.OnCollectionAfterDeleteError().Bind(collectionErrorEventHandler)
app.OnModelAfterDeleteError().Bind(modelErrorEventHandler)
app.OnModelAfterDeleteError().Trigger(createModelErrorEvent(), modelErrorEventFinalizer)
}
func TestCollectionSaveModel(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
collection func(app core.App) (*core.Collection, error)
expectError bool
expectColumns []string
}{
// trigger validators
{
name: "create - trigger validators",
collection: func(app core.App) (*core.Collection, error) {
c := core.NewBaseCollection("!invalid")
c.Fields.Add(&core.TextField{Name: "example"})
c.AddIndex("test_save_idx", false, "example", "")
return c, nil
},
expectError: true,
},
{
name: "update - trigger validators",
collection: func(app core.App) (*core.Collection, error) {
c, _ := app.FindCollectionByNameOrId("demo5")
c.Name = "demo1"
c.Fields.Add(&core.TextField{Name: "example"})
c.Fields.RemoveByName("file")
c.AddIndex("test_save_idx", false, "example", "")
return c, nil
},
expectError: true,
},
// create
{
name: "create base collection",
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | true |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/external_auth_query.go | core/external_auth_query.go | package core
import (
"github.com/pocketbase/dbx"
)
// FindAllExternalAuthsByRecord returns all ExternalAuth models
// linked to the provided auth record.
func (app *BaseApp) FindAllExternalAuthsByRecord(authRecord *Record) ([]*ExternalAuth, error) {
auths := []*ExternalAuth{}
err := app.RecordQuery(CollectionNameExternalAuths).
AndWhere(dbx.HashExp{
"collectionRef": authRecord.Collection().Id,
"recordRef": authRecord.Id,
}).
OrderBy("created DESC").
All(&auths)
if err != nil {
return nil, err
}
return auths, nil
}
// FindAllExternalAuthsByCollection returns all ExternalAuth models
// linked to the provided auth collection.
func (app *BaseApp) FindAllExternalAuthsByCollection(collection *Collection) ([]*ExternalAuth, error) {
auths := []*ExternalAuth{}
err := app.RecordQuery(CollectionNameExternalAuths).
AndWhere(dbx.HashExp{"collectionRef": collection.Id}).
OrderBy("created DESC").
All(&auths)
if err != nil {
return nil, err
}
return auths, nil
}
// FindFirstExternalAuthByExpr returns the first available (the most recent created)
// ExternalAuth model that satisfies the non-nil expression.
func (app *BaseApp) FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalAuth, error) {
model := &ExternalAuth{}
err := app.RecordQuery(CollectionNameExternalAuths).
AndWhere(dbx.Not(dbx.HashExp{"providerId": ""})). // exclude empty providerIds
AndWhere(expr).
OrderBy("created DESC").
Limit(1).
One(model)
if err != nil {
return nil, err
}
return model, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_email.go | core/field_email.go | package core
import (
"context"
"slices"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeEmail] = func() Field {
return &EmailField{}
}
}
const FieldTypeEmail = "email"
var _ Field = (*EmailField)(nil)
// EmailField defines "email" type field for storing a single email string address.
//
// The respective zero record field value is empty string.
type EmailField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// ExceptDomains will require the email domain to NOT be included in the listed ones.
//
// This validator can be set only if OnlyDomains is empty.
ExceptDomains []string `form:"exceptDomains" json:"exceptDomains"`
// OnlyDomains will require the email domain to be included in the listed ones.
//
// This validator can be set only if ExceptDomains is empty.
OnlyDomains []string `form:"onlyDomains" json:"onlyDomains"`
// Required will require the field value to be non-empty email string.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *EmailField) Type() string {
return FieldTypeEmail
}
// GetId implements [Field.GetId] interface method.
func (f *EmailField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *EmailField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *EmailField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *EmailField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *EmailField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *EmailField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *EmailField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *EmailField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *EmailField) ColumnType(app App) string {
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *EmailField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToString(raw), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *EmailField) ValidateValue(ctx context.Context, app App, record *Record) error {
val, ok := record.GetRaw(f.Name).(string)
if !ok {
return validators.ErrUnsupportedValueType
}
if f.Required {
if err := validation.Required.Validate(val); err != nil {
return err
}
}
if val == "" {
return nil // nothing to check
}
if err := is.EmailFormat.Validate(val); err != nil {
return err
}
domain := val[strings.LastIndex(val, "@")+1:]
// only domains check
if len(f.OnlyDomains) > 0 && !slices.Contains(f.OnlyDomains, domain) {
return validation.NewError("validation_email_domain_not_allowed", "Email domain is not allowed")
}
// except domains check
if len(f.ExceptDomains) > 0 && slices.Contains(f.ExceptDomains, domain) {
return validation.NewError("validation_email_domain_not_allowed", "Email domain is not allowed")
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *EmailField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(
&f.ExceptDomains,
validation.When(len(f.OnlyDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
validation.Field(
&f.OnlyDomains,
validation.When(len(f.ExceptDomains) > 0, validation.Empty).Else(validation.Each(is.Domain)),
),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_record_table_sync_test.go | core/collection_record_table_sync_test.go | package core_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestSyncRecordTableSchema(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
oldCollection, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
t.Fatal(err)
}
updatedCollection, err := app.FindCollectionByNameOrId("demo2")
if err != nil {
t.Fatal(err)
}
updatedCollection.Name = "demo_renamed"
updatedCollection.Fields.RemoveByName("active")
updatedCollection.Fields.Add(&core.EmailField{
Name: "new_field",
})
updatedCollection.Fields.Add(&core.EmailField{
Id: updatedCollection.Fields.GetByName("title").GetId(),
Name: "title_renamed",
})
updatedCollection.Indexes = types.JSONArray[string]{"create index idx_title_renamed on anything (title_renamed)"}
baseCol := core.NewBaseCollection("new_base")
baseCol.Fields.Add(&core.TextField{Name: "test"})
authCol := core.NewAuthCollection("new_auth")
authCol.Fields.Add(&core.TextField{Name: "test"})
authCol.AddIndex("idx_auth_test", false, "email, id", "")
scenarios := []struct {
name string
newCollection *core.Collection
oldCollection *core.Collection
expectedColumns []string
expectedIndexesCount int
}{
{
"new base collection",
baseCol,
nil,
[]string{"id", "test"},
0,
},
{
"new auth collection",
authCol,
nil,
[]string{
"id", "test", "email", "verified",
"emailVisibility", "tokenKey", "password",
},
3,
},
{
"no changes",
oldCollection,
oldCollection,
[]string{"id", "created", "updated", "title", "active"},
3,
},
{
"renamed table, deleted column, renamed columnd and new column",
updatedCollection,
oldCollection,
[]string{"id", "created", "updated", "title_renamed", "new_field"},
1,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := app.SyncRecordTableSchema(s.newCollection, s.oldCollection)
if err != nil {
t.Fatal(err)
}
if !app.HasTable(s.newCollection.Name) {
t.Fatalf("Expected table %s to exist", s.newCollection.Name)
}
cols, _ := app.TableColumns(s.newCollection.Name)
if len(cols) != len(s.expectedColumns) {
t.Fatalf("Expected columns %v, got %v", s.expectedColumns, cols)
}
for _, col := range cols {
if !list.ExistInSlice(col, s.expectedColumns) {
t.Fatalf("Couldn't find column %s in %v", col, s.expectedColumns)
}
}
indexes, _ := app.TableIndexes(s.newCollection.Name)
if totalIndexes := len(indexes); totalIndexes != s.expectedIndexesCount {
t.Fatalf("Expected %d indexes, got %d:\n%v", s.expectedIndexesCount, totalIndexes, indexes)
}
})
}
}
func getTotalViews(app core.App) (int, error) {
var total int
err := app.DB().Select("count(*)").
From("sqlite_master").
AndWhere(dbx.NewExp("sql is not null")).
AndWhere(dbx.HashExp{"type": "view"}).
Row(&total)
return total, err
}
func TestSingleVsMultipleValuesNormalization(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
beforeTotalViews, err := getTotalViews(app)
if err != nil {
t.Fatal(err)
}
// mock field changes
collection.Fields.GetByName("select_one").(*core.SelectField).MaxSelect = 2
collection.Fields.GetByName("select_many").(*core.SelectField).MaxSelect = 1
collection.Fields.GetByName("file_one").(*core.FileField).MaxSelect = 2
collection.Fields.GetByName("file_many").(*core.FileField).MaxSelect = 1
collection.Fields.GetByName("rel_one").(*core.RelationField).MaxSelect = 2
collection.Fields.GetByName("rel_many").(*core.RelationField).MaxSelect = 1
// new multivaluer field to check whether the array normalization
// will be applied for already inserted data
collection.Fields.Add(&core.SelectField{
Name: "new_multiple",
Values: []string{"a", "b", "c"},
MaxSelect: 3,
})
if err := app.Save(collection); err != nil {
t.Fatal(err)
}
// ensure that the views were reinserted
afterTotalViews, err := getTotalViews(app)
if err != nil {
t.Fatal(err)
}
if afterTotalViews != beforeTotalViews {
t.Fatalf("Expected total views %d, got %d", beforeTotalViews, afterTotalViews)
}
// check whether the columns DEFAULT definition was updated
// ---------------------------------------------------------------
tableInfo, err := app.TableInfo(collection.Name)
if err != nil {
t.Fatal(err)
}
tableInfoExpectations := map[string]string{
"select_one": `'[]'`,
"select_many": `''`,
"file_one": `'[]'`,
"file_many": `''`,
"rel_one": `'[]'`,
"rel_many": `''`,
"new_multiple": `'[]'`,
}
for col, dflt := range tableInfoExpectations {
t.Run("check default for "+col, func(t *testing.T) {
var row *core.TableInfoRow
for _, r := range tableInfo {
if r.Name == col {
row = r
break
}
}
if row == nil {
t.Fatalf("Missing info for column %q", col)
}
if v := row.DefaultValue.String; v != dflt {
t.Fatalf("Expected default value %q, got %q", dflt, v)
}
})
}
// check whether the values were normalized
// ---------------------------------------------------------------
type fieldsExpectation struct {
SelectOne string `db:"select_one"`
SelectMany string `db:"select_many"`
FileOne string `db:"file_one"`
FileMany string `db:"file_many"`
RelOne string `db:"rel_one"`
RelMany string `db:"rel_many"`
NewMultiple string `db:"new_multiple"`
}
fieldsScenarios := []struct {
recordId string
expected fieldsExpectation
}{
{
"imy661ixudk5izi",
fieldsExpectation{
SelectOne: `[]`,
SelectMany: ``,
FileOne: `[]`,
FileMany: ``,
RelOne: `[]`,
RelMany: ``,
NewMultiple: `[]`,
},
},
{
"al1h9ijdeojtsjy",
fieldsExpectation{
SelectOne: `["optionB"]`,
SelectMany: `optionB`,
FileOne: `["300_Jsjq7RdBgA.png"]`,
FileMany: ``,
RelOne: `["84nmscqy84lsi1t"]`,
RelMany: `oap640cot4yru2s`,
NewMultiple: `[]`,
},
},
{
"84nmscqy84lsi1t",
fieldsExpectation{
SelectOne: `["optionB"]`,
SelectMany: `optionC`,
FileOne: `["test_d61b33QdDU.txt"]`,
FileMany: `test_tC1Yc87DfC.txt`,
RelOne: `[]`,
RelMany: `oap640cot4yru2s`,
NewMultiple: `[]`,
},
},
}
for _, s := range fieldsScenarios {
t.Run("check fields for record "+s.recordId, func(t *testing.T) {
result := new(fieldsExpectation)
err := app.DB().Select(
"select_one",
"select_many",
"file_one",
"file_many",
"rel_one",
"rel_many",
"new_multiple",
).From(collection.Name).Where(dbx.HashExp{"id": s.recordId}).One(result)
if err != nil {
t.Fatalf("Failed to load record: %v", err)
}
encodedResult, err := json.Marshal(result)
if err != nil {
t.Fatalf("Failed to encode result: %v", err)
}
encodedExpectation, err := json.Marshal(s.expected)
if err != nil {
t.Fatalf("Failed to encode expectation: %v", err)
}
if !bytes.EqualFold(encodedExpectation, encodedResult) {
t.Fatalf("Expected \n%s, \ngot \n%s", encodedExpectation, encodedResult)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_record_table_sync.go | core/collection_record_table_sync.go | package core
import (
"fmt"
"log/slog"
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/security"
)
// SyncRecordTableSchema compares the two provided collections
// and applies the necessary related record table changes.
//
// If oldCollection is null, then only newCollection is used to create the record table.
//
// This method is automatically invoked as part of a collection create/update/delete operation.
func (app *BaseApp) SyncRecordTableSchema(newCollection *Collection, oldCollection *Collection) error {
if newCollection.IsView() {
return nil // nothing to sync since views don't have records table
}
txErr := app.RunInTransaction(func(txApp App) error {
// create
// -----------------------------------------------------------
if oldCollection == nil || !app.HasTable(oldCollection.Name) {
tableName := newCollection.Name
fields := newCollection.Fields
cols := make(map[string]string, len(fields))
// add fields definition
for _, field := range fields {
cols[field.GetName()] = field.ColumnType(app)
}
// create table
if _, err := txApp.DB().CreateTable(tableName, cols).Execute(); err != nil {
return err
}
return createCollectionIndexes(txApp, newCollection)
}
// update
// -----------------------------------------------------------
oldTableName := oldCollection.Name
newTableName := newCollection.Name
oldFields := oldCollection.Fields
newFields := newCollection.Fields
needTableRename := !strings.EqualFold(oldTableName, newTableName)
var needIndexesUpdate bool
if needTableRename ||
oldFields.String() != newFields.String() ||
oldCollection.Indexes.String() != newCollection.Indexes.String() {
needIndexesUpdate = true
}
if needIndexesUpdate {
// drop old indexes (if any)
if err := dropCollectionIndexes(txApp, oldCollection); err != nil {
return err
}
}
// check for renamed table
if needTableRename {
_, err := txApp.DB().RenameTable("{{"+oldTableName+"}}", "{{"+newTableName+"}}").Execute()
if err != nil {
return err
}
}
// check for deleted columns
for _, oldField := range oldFields {
if f := newFields.GetById(oldField.GetId()); f != nil {
continue // exist
}
_, err := txApp.DB().DropColumn(newTableName, oldField.GetName()).Execute()
if err != nil {
return fmt.Errorf("failed to drop column %s - %w", oldField.GetName(), err)
}
}
// check for new or renamed columns
toRename := map[string]string{}
for _, field := range newFields {
oldField := oldFields.GetById(field.GetId())
// Note:
// We are using a temporary column name when adding or renaming columns
// to ensure that there are no name collisions in case there is
// names switch/reuse of existing columns (eg. name, title -> title, name).
// This way we are always doing 1 more rename operation but it provides better less ambiguous experience.
if oldField == nil {
tempName := field.GetName() + security.PseudorandomString(5)
toRename[tempName] = field.GetName()
// add
_, err := txApp.DB().AddColumn(newTableName, tempName, field.ColumnType(txApp)).Execute()
if err != nil {
return fmt.Errorf("failed to add column %s - %w", field.GetName(), err)
}
} else if oldField.GetName() != field.GetName() {
tempName := field.GetName() + security.PseudorandomString(5)
toRename[tempName] = field.GetName()
// rename
_, err := txApp.DB().RenameColumn(newTableName, oldField.GetName(), tempName).Execute()
if err != nil {
return fmt.Errorf("failed to rename column %s - %w", oldField.GetName(), err)
}
}
}
// set the actual columns name
for tempName, actualName := range toRename {
_, err := txApp.DB().RenameColumn(newTableName, tempName, actualName).Execute()
if err != nil {
return err
}
}
if err := normalizeSingleVsMultipleFieldChanges(txApp, newCollection, oldCollection); err != nil {
return err
}
if needIndexesUpdate {
return createCollectionIndexes(txApp, newCollection)
}
return nil
})
if txErr != nil {
return txErr
}
// run optimize per the SQLite recommendations
// (https://www.sqlite.org/pragma.html#pragma_optimize)
_, optimizeErr := app.NonconcurrentDB().NewQuery("PRAGMA optimize").Execute()
if optimizeErr != nil {
app.Logger().Warn("Failed to run PRAGMA optimize after record table sync", slog.String("error", optimizeErr.Error()))
}
return nil
}
func normalizeSingleVsMultipleFieldChanges(app App, newCollection *Collection, oldCollection *Collection) error {
if newCollection.IsView() || oldCollection == nil {
return nil // view or not an update
}
return app.RunInTransaction(func(txApp App) error {
for _, newField := range newCollection.Fields {
// allow to continue even if there is no old field for the cases
// when a new field is added and there are already inserted data
var isOldMultiple bool
if oldField := oldCollection.Fields.GetById(newField.GetId()); oldField != nil {
if mv, ok := oldField.(MultiValuer); ok {
isOldMultiple = mv.IsMultiple()
}
}
var isNewMultiple bool
if mv, ok := newField.(MultiValuer); ok {
isNewMultiple = mv.IsMultiple()
}
if isOldMultiple == isNewMultiple {
continue // no change
}
// -------------------------------------------------------
// update the field column definition
// -------------------------------------------------------
// temporary drop all views to prevent reference errors during the columns renaming
// (this is used as an "alternative" to the writable_schema PRAGMA)
views := []struct {
Name string `db:"name"`
SQL string `db:"sql"`
}{}
err := txApp.DB().Select("name", "sql").
From("sqlite_master").
AndWhere(dbx.NewExp("sql is not null")).
AndWhere(dbx.HashExp{"type": "view"}).
All(&views)
if err != nil {
return err
}
for _, view := range views {
err = txApp.DeleteView(view.Name)
if err != nil {
return err
}
}
originalName := newField.GetName()
oldTempName := "_" + newField.GetName() + security.PseudorandomString(5)
// rename temporary the original column to something else to allow inserting a new one in its place
_, err = txApp.DB().RenameColumn(newCollection.Name, originalName, oldTempName).Execute()
if err != nil {
return err
}
// reinsert the field column with the new type
_, err = txApp.DB().AddColumn(newCollection.Name, originalName, newField.ColumnType(txApp)).Execute()
if err != nil {
return err
}
var copyQuery *dbx.Query
if !isOldMultiple && isNewMultiple {
// single -> multiple (convert to array)
copyQuery = txApp.DB().NewQuery(fmt.Sprintf(
`UPDATE {{%s}} set [[%s]] = (
CASE
WHEN COALESCE([[%s]], '') = ''
THEN '[]'
ELSE (
CASE
WHEN json_valid([[%s]]) AND json_type([[%s]]) == 'array'
THEN [[%s]]
ELSE json_array([[%s]])
END
)
END
)`,
newCollection.Name,
originalName,
oldTempName,
oldTempName,
oldTempName,
oldTempName,
oldTempName,
))
} else {
// multiple -> single (keep only the last element)
//
// note: for file fields the actual file objects are not
// deleted allowing additional custom handling via migration
copyQuery = txApp.DB().NewQuery(fmt.Sprintf(
`UPDATE {{%s}} set [[%s]] = (
CASE
WHEN COALESCE([[%s]], '[]') = '[]'
THEN ''
ELSE (
CASE
WHEN json_valid([[%s]]) AND json_type([[%s]]) == 'array'
THEN COALESCE(json_extract([[%s]], '$[#-1]'), '')
ELSE [[%s]]
END
)
END
)`,
newCollection.Name,
originalName,
oldTempName,
oldTempName,
oldTempName,
oldTempName,
oldTempName,
))
}
// copy the normalized values
_, err = copyQuery.Execute()
if err != nil {
return err
}
// drop the original column
_, err = txApp.DB().DropColumn(newCollection.Name, oldTempName).Execute()
if err != nil {
return err
}
// restore views
for _, view := range views {
_, err = txApp.DB().NewQuery(view.SQL).Execute()
if err != nil {
return err
}
}
}
return nil
})
}
func dropCollectionIndexes(app App, collection *Collection) error {
if collection.IsView() {
return nil // views don't have indexes
}
return app.RunInTransaction(func(txApp App) error {
for _, raw := range collection.Indexes {
parsed := dbutils.ParseIndex(raw)
if !parsed.IsValid() {
continue
}
_, err := txApp.DB().NewQuery(fmt.Sprintf("DROP INDEX IF EXISTS [[%s]]", parsed.IndexName)).Execute()
if err != nil {
return err
}
}
return nil
})
}
func createCollectionIndexes(app App, collection *Collection) error {
if collection.IsView() {
return nil // views don't have indexes
}
return app.RunInTransaction(func(txApp App) error {
// upsert new indexes
//
// note: we are returning validation errors because the indexes cannot be
// easily validated in a form, aka. before persisting the related
// collection record table changes
errs := validation.Errors{}
for i, idx := range collection.Indexes {
parsed := dbutils.ParseIndex(idx)
// ensure that the index is always for the current collection
parsed.TableName = collection.Name
if !parsed.IsValid() {
errs[strconv.Itoa(i)] = validation.NewError(
"validation_invalid_index_expression",
"Invalid CREATE INDEX expression.",
)
continue
}
if _, err := txApp.DB().NewQuery(parsed.Build()).Execute(); err != nil {
errs[strconv.Itoa(i)] = validation.NewError(
"validation_invalid_index_expression",
fmt.Sprintf("Failed to create index %s - %v.", parsed.IndexName, err.Error()),
)
continue
}
}
if len(errs) > 0 {
return validation.Errors{"indexes": errs}
}
return nil
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/log_printer.go | core/log_printer.go | package core
import (
"fmt"
"log/slog"
"strings"
"github.com/fatih/color"
"github.com/pocketbase/pocketbase/tools/logger"
"github.com/pocketbase/pocketbase/tools/store"
"github.com/spf13/cast"
)
var cachedColors = store.New[string, *color.Color](nil)
// getColor returns [color.Color] object and cache it (if not already).
func getColor(attrs ...color.Attribute) (c *color.Color) {
cacheKey := fmt.Sprint(attrs)
if c = cachedColors.Get(cacheKey); c == nil {
c = color.New(attrs...)
cachedColors.Set(cacheKey, c)
}
return
}
// printLog prints the provided log to the stderr.
// (note: defined as variable to overwriting in the tests)
var printLog = func(log *logger.Log) {
var str strings.Builder
switch log.Level {
case slog.LevelDebug:
str.WriteString(getColor(color.Bold, color.FgHiBlack).Sprint("DEBUG "))
str.WriteString(getColor(color.FgWhite).Sprint(log.Message))
case slog.LevelInfo:
str.WriteString(getColor(color.Bold, color.FgWhite).Sprint("INFO "))
str.WriteString(getColor(color.FgWhite).Sprint(log.Message))
case slog.LevelWarn:
str.WriteString(getColor(color.Bold, color.FgYellow).Sprint("WARN "))
str.WriteString(getColor(color.FgYellow).Sprint(log.Message))
case slog.LevelError:
str.WriteString(getColor(color.Bold, color.FgRed).Sprint("ERROR "))
str.WriteString(getColor(color.FgRed).Sprint(log.Message))
default:
str.WriteString(getColor(color.Bold, color.FgCyan).Sprintf("[%d] ", log.Level))
str.WriteString(getColor(color.FgCyan).Sprint(log.Message))
}
str.WriteString("\n")
if v, ok := log.Data["type"]; ok && cast.ToString(v) == "request" {
padding := 0
keys := []string{"error", "details"}
for _, k := range keys {
if v := log.Data[k]; v != nil {
str.WriteString(getColor(color.FgHiRed).Sprintf("%s└─ %v", strings.Repeat(" ", padding), v))
str.WriteString("\n")
padding += 3
}
}
} else if len(log.Data) > 0 {
str.WriteString(getColor(color.FgHiBlack).Sprintf("└─ %v", log.Data))
str.WriteString("\n")
}
fmt.Print(str.String())
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/record_field_resolver_replace_expr.go | core/record_field_resolver_replace_expr.go | package core
import (
"strings"
"github.com/pocketbase/dbx"
)
var _ dbx.Expression = (*replaceWithExpression)(nil)
// replaceWithExpression defines a custom expression that will replace
// a placeholder identifier found in "old" with the result of "new".
type replaceWithExpression struct {
placeholder string
old dbx.Expression
new dbx.Expression
}
// Build converts the expression into a SQL fragment.
//
// Implements [dbx.Expression] interface.
func (e *replaceWithExpression) Build(db *dbx.DB, params dbx.Params) string {
if e.placeholder == "" || e.old == nil || e.new == nil {
return "0=1"
}
oldResult := e.old.Build(db, params)
newResult := e.new.Build(db, params)
return strings.ReplaceAll(oldResult, e.placeholder, newResult)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/otp_query_test.go | core/otp_query_test.go | package core_test
import (
"fmt"
"slices"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestFindAllOTPsByRecord(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubOTPRecords(app); err != nil {
t.Fatal(err)
}
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
superuser4, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test4@example.com")
if err != nil {
t.Fatal(err)
}
user1, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
expected []string
}{
{demo1, nil},
{superuser2, []string{"superuser2_0", "superuser2_1", "superuser2_3", "superuser2_2", "superuser2_4"}},
{superuser4, nil},
{user1, []string{"user1_0"}},
}
for _, s := range scenarios {
t.Run(s.record.Collection().Name+"_"+s.record.Id, func(t *testing.T) {
result, err := app.FindAllOTPsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total otps %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindAllOTPsByCollection(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubOTPRecords(app); err != nil {
t.Fatal(err)
}
demo1, err := app.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
clients, err := app.FindCollectionByNameOrId("clients")
if err != nil {
t.Fatal(err)
}
users, err := app.FindCollectionByNameOrId("users")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
collection *core.Collection
expected []string
}{
{demo1, nil},
{superusers, []string{
"superuser2_0",
"superuser2_1",
"superuser2_3",
"superuser3_0",
"superuser3_1",
"superuser2_2",
"superuser2_4",
}},
{clients, nil},
{users, []string{"user1_0"}},
}
for _, s := range scenarios {
t.Run(s.collection.Name, func(t *testing.T) {
result, err := app.FindAllOTPsByCollection(s.collection)
if err != nil {
t.Fatal(err)
}
if len(result) != len(s.expected) {
t.Fatalf("Expected total otps %d, got %d", len(s.expected), len(result))
}
for i, id := range s.expected {
if result[i].Id != id {
t.Errorf("[%d] Expected id %q, got %q", i, id, result[i].Id)
}
}
})
}
}
func TestFindOTPById(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubOTPRecords(app); err != nil {
t.Fatal(err)
}
scenarios := []struct {
id string
expectError bool
}{
{"", true},
{"84nmscqy84lsi1t", true}, // non-otp id
{"superuser2_0", false},
{"superuser2_4", false}, // expired
{"user1_0", false},
}
for _, s := range scenarios {
t.Run(s.id, func(t *testing.T) {
result, err := app.FindOTPById(s.id)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr {
return
}
if result.Id != s.id {
t.Fatalf("Expected record with id %q, got %q", s.id, result.Id)
}
})
}
}
func TestDeleteAllOTPsByRecord(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1, err := testApp.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
superuser2, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
superuser4, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test4@example.com")
if err != nil {
t.Fatal(err)
}
user1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
deletedIds []string
}{
{demo1, nil}, // non-auth record
{superuser2, []string{"superuser2_0", "superuser2_1", "superuser2_3", "superuser2_2", "superuser2_4"}},
{superuser4, nil},
{user1, []string{"user1_0"}},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.record.Collection().Name, s.record.Id), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
if err := tests.StubOTPRecords(app); err != nil {
t.Fatal(err)
}
deletedIds := []string{}
app.OnRecordAfterDeleteSuccess().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
err := app.DeleteAllOTPsByRecord(s.record)
if err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(s.deletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", s.deletedIds, deletedIds)
}
for _, id := range s.deletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
})
}
}
func TestDeleteExpiredOTPs(t *testing.T) {
t.Parallel()
checkDeletedIds := func(app core.App, t *testing.T, expectedDeletedIds []string) {
if err := tests.StubOTPRecords(app); err != nil {
t.Fatal(err)
}
deletedIds := []string{}
app.OnRecordAfterDeleteSuccess().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
if err := app.DeleteExpiredOTPs(); err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(expectedDeletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", expectedDeletedIds, deletedIds)
}
for _, id := range expectedDeletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
}
t.Run("default test collections", func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
checkDeletedIds(app, t, []string{
"user1_0",
"superuser2_2",
"superuser2_4",
})
})
t.Run("otp collection duration mock", func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
superusers, err := app.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
superusers.OTP.Duration = 60
if err := app.Save(superusers); err != nil {
t.Fatalf("Failed to mock superusers otp duration: %v", err)
}
checkDeletedIds(app, t, []string{
"user1_0",
"superuser2_2",
"superuser2_4",
"superuser3_1",
})
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_test.go | core/field_test.go | package core_test
import (
"context"
"strings"
"testing"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func testFieldBaseMethods(t *testing.T, fieldType string) {
factory, ok := core.Fields[fieldType]
if !ok {
t.Fatalf("Missing %q field factory", fieldType)
}
f := factory()
if f == nil {
t.Fatal("Expected non-nil Field instance")
}
t.Run("type", func(t *testing.T) {
if v := f.Type(); v != fieldType {
t.Fatalf("Expected type %q, got %q", fieldType, v)
}
})
t.Run("id", func(t *testing.T) {
testValues := []string{"new_id", ""}
for _, expected := range testValues {
f.SetId(expected)
if v := f.GetId(); v != expected {
t.Fatalf("Expected id %q, got %q", expected, v)
}
}
})
t.Run("name", func(t *testing.T) {
testValues := []string{"new_name", ""}
for _, expected := range testValues {
f.SetName(expected)
if v := f.GetName(); v != expected {
t.Fatalf("Expected name %q, got %q", expected, v)
}
}
})
t.Run("system", func(t *testing.T) {
testValues := []bool{false, true}
for _, expected := range testValues {
f.SetSystem(expected)
if v := f.GetSystem(); v != expected {
t.Fatalf("Expected system %v, got %v", expected, v)
}
}
})
t.Run("hidden", func(t *testing.T) {
testValues := []bool{false, true}
for _, expected := range testValues {
f.SetHidden(expected)
if v := f.GetHidden(); v != expected {
t.Fatalf("Expected hidden %v, got %v", expected, v)
}
}
})
}
func testDefaultFieldIdValidation(t *testing.T, fieldType string) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() core.Field
expectError bool
}{
{
"empty value",
func() core.Field {
f := core.Fields[fieldType]()
return f
},
true,
},
{
"invalid length",
func() core.Field {
f := core.Fields[fieldType]()
f.SetId(strings.Repeat("a", 101))
return f
},
true,
},
{
"valid length",
func() core.Field {
f := core.Fields[fieldType]()
f.SetId(strings.Repeat("a", 100))
return f
},
false,
},
}
for _, s := range scenarios {
t.Run("[id] "+s.name, func(t *testing.T) {
errs, _ := s.field().ValidateSettings(context.Background(), app, collection).(validation.Errors)
hasErr := errs["id"] != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v", s.expectError, hasErr)
}
})
}
}
func testDefaultFieldNameValidation(t *testing.T, fieldType string) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
scenarios := []struct {
name string
field func() core.Field
expectError bool
}{
{
"empty value",
func() core.Field {
f := core.Fields[fieldType]()
return f
},
true,
},
{
"invalid length",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName(strings.Repeat("a", 101))
return f
},
true,
},
{
"valid length",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName(strings.Repeat("a", 100))
return f
},
false,
},
{
"invalid regex",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("test(")
return f
},
true,
},
{
"valid regex",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("test_123")
return f
},
false,
},
{
"_via_",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("a_via_b")
return f
},
true,
},
{
"system reserved - null",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("null")
return f
},
true,
},
{
"system reserved - false",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("false")
return f
},
true,
},
{
"system reserved - true",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("true")
return f
},
true,
},
{
"system reserved - _rowid_",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("_rowid_")
return f
},
true,
},
{
"system reserved - expand",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("expand")
return f
},
true,
},
{
"system reserved - collectionId",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("collectionId")
return f
},
true,
},
{
"system reserved - collectionName",
func() core.Field {
f := core.Fields[fieldType]()
f.SetName("collectionName")
return f
},
true,
},
}
for _, s := range scenarios {
t.Run("[name] "+s.name, func(t *testing.T) {
errs, _ := s.field().ValidateSettings(context.Background(), app, collection).(validation.Errors)
hasErr := errs["name"] != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v", s.expectError, hasErr)
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/auth_origin_model_test.go | core/auth_origin_model_test.go | package core_test
import (
"fmt"
"slices"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestNewAuthOrigin(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
origin := core.NewAuthOrigin(app)
if origin.Collection().Name != core.CollectionNameAuthOrigins {
t.Fatalf("Expected record with %q collection, got %q", core.CollectionNameAuthOrigins, origin.Collection().Name)
}
}
func TestAuthOriginProxyRecord(t *testing.T) {
t.Parallel()
record := core.NewRecord(core.NewBaseCollection("test"))
record.Id = "test_id"
origin := core.AuthOrigin{}
origin.SetProxyRecord(record)
if origin.ProxyRecord() == nil || origin.ProxyRecord().Id != record.Id {
t.Fatalf("Expected proxy record with id %q, got %v", record.Id, origin.ProxyRecord())
}
}
func TestAuthOriginRecordRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
origin := core.NewAuthOrigin(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
origin.SetRecordRef(testValue)
if v := origin.RecordRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := origin.GetString("recordRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestAuthOriginCollectionRef(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
origin := core.NewAuthOrigin(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
origin.SetCollectionRef(testValue)
if v := origin.CollectionRef(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := origin.GetString("collectionRef"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestAuthOriginFingerprint(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
origin := core.NewAuthOrigin(app)
testValues := []string{"test_1", "test2", ""}
for i, testValue := range testValues {
t.Run(fmt.Sprintf("%d_%q", i, testValue), func(t *testing.T) {
origin.SetFingerprint(testValue)
if v := origin.Fingerprint(); v != testValue {
t.Fatalf("Expected getter %q, got %q", testValue, v)
}
if v := origin.GetString("fingerprint"); v != testValue {
t.Fatalf("Expected field value %q, got %q", testValue, v)
}
})
}
}
func TestAuthOriginCreated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
origin := core.NewAuthOrigin(app)
if v := origin.Created().String(); v != "" {
t.Fatalf("Expected empty created, got %q", v)
}
now := types.NowDateTime()
origin.SetRaw("created", now)
if v := origin.Created().String(); v != now.String() {
t.Fatalf("Expected %q created, got %q", now.String(), v)
}
}
func TestAuthOriginUpdated(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
origin := core.NewAuthOrigin(app)
if v := origin.Updated().String(); v != "" {
t.Fatalf("Expected empty updated, got %q", v)
}
now := types.NowDateTime()
origin.SetRaw("updated", now)
if v := origin.Updated().String(); v != now.String() {
t.Fatalf("Expected %q updated, got %q", now.String(), v)
}
}
func TestAuthOriginPreValidate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
originsCol, err := app.FindCollectionByNameOrId(core.CollectionNameAuthOrigins)
if err != nil {
t.Fatal(err)
}
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
t.Run("no proxy record", func(t *testing.T) {
origin := &core.AuthOrigin{}
if err := app.Validate(origin); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("non-AuthOrigin collection", func(t *testing.T) {
origin := &core.AuthOrigin{}
origin.SetProxyRecord(core.NewRecord(core.NewBaseCollection("invalid")))
origin.SetRecordRef(user.Id)
origin.SetCollectionRef(user.Collection().Id)
origin.SetFingerprint("abc")
if err := app.Validate(origin); err == nil {
t.Fatal("Expected collection validation error")
}
})
t.Run("AuthOrigin collection", func(t *testing.T) {
origin := &core.AuthOrigin{}
origin.SetProxyRecord(core.NewRecord(originsCol))
origin.SetRecordRef(user.Id)
origin.SetCollectionRef(user.Collection().Id)
origin.SetFingerprint("abc")
if err := app.Validate(origin); err != nil {
t.Fatalf("Expected nil validation error, got %v", err)
}
})
}
func TestAuthOriginValidateHook(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
demo1, err := app.FindRecordById("demo1", "84nmscqy84lsi1t")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
origin func() *core.AuthOrigin
expectErrors []string
}{
{
"empty",
func() *core.AuthOrigin {
return core.NewAuthOrigin(app)
},
[]string{"collectionRef", "recordRef", "fingerprint"},
},
{
"non-auth collection",
func() *core.AuthOrigin {
origin := core.NewAuthOrigin(app)
origin.SetCollectionRef(demo1.Collection().Id)
origin.SetRecordRef(demo1.Id)
origin.SetFingerprint("abc")
return origin
},
[]string{"collectionRef"},
},
{
"missing record id",
func() *core.AuthOrigin {
origin := core.NewAuthOrigin(app)
origin.SetCollectionRef(user.Collection().Id)
origin.SetRecordRef("missing")
origin.SetFingerprint("abc")
return origin
},
[]string{"recordRef"},
},
{
"valid ref",
func() *core.AuthOrigin {
origin := core.NewAuthOrigin(app)
origin.SetCollectionRef(user.Collection().Id)
origin.SetRecordRef(user.Id)
origin.SetFingerprint("abc")
return origin
},
[]string{},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
errs := app.Validate(s.origin())
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestAuthOriginPasswordChangeDeletion(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
// no auth origin associated with it
user1, err := testApp.FindAuthRecordByEmail("users", "test@example.com")
if err != nil {
t.Fatal(err)
}
superuser2, err := testApp.FindAuthRecordByEmail(core.CollectionNameSuperusers, "test2@example.com")
if err != nil {
t.Fatal(err)
}
client1, err := testApp.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
record *core.Record
deletedIds []string
}{
{user1, nil},
{superuser2, []string{"5798yh833k6w6w0", "ic55o70g4f8pcl4", "dmy260k6ksjr4ib"}},
{client1, []string{"9r2j0m74260ur8i"}},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%s_%s", i, s.record.Collection().Name, s.record.Id), func(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
deletedIds := []string{}
app.OnRecordDelete().BindFunc(func(e *core.RecordEvent) error {
deletedIds = append(deletedIds, e.Record.Id)
return e.Next()
})
s.record.SetPassword("new_password")
err := app.Save(s.record)
if err != nil {
t.Fatal(err)
}
if len(deletedIds) != len(s.deletedIds) {
t.Fatalf("Expected deleted ids\n%v\ngot\n%v", s.deletedIds, deletedIds)
}
for _, id := range s.deletedIds {
if !slices.Contains(deletedIds, id) {
t.Errorf("Expected to find deleted id %q in %v", id, deletedIds)
}
}
})
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_file_test.go | core/field_file_test.go | package core_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/types"
)
func TestFileFieldBaseMethods(t *testing.T) {
testFieldBaseMethods(t, core.FieldTypeFile)
}
func TestFileFieldColumnType(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field *core.FileField
expected string
}{
{
"single (zero)",
&core.FileField{},
"TEXT DEFAULT '' NOT NULL",
},
{
"single",
&core.FileField{MaxSelect: 1},
"TEXT DEFAULT '' NOT NULL",
},
{
"multiple",
&core.FileField{MaxSelect: 2},
"JSON DEFAULT '[]' NOT NULL",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
if v := s.field.ColumnType(app); v != s.expected {
t.Fatalf("Expected\n%q\ngot\n%q", s.expected, v)
}
})
}
}
func TestFileFieldIsMultiple(t *testing.T) {
scenarios := []struct {
name string
field *core.FileField
expected bool
}{
{
"zero",
&core.FileField{},
false,
},
{
"single",
&core.FileField{MaxSelect: 1},
false,
},
{
"multiple",
&core.FileField{MaxSelect: 2},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
if v := s.field.IsMultiple(); v != s.expected {
t.Fatalf("Expected %v, got %v", s.expected, v)
}
})
}
}
func TestFileFieldPrepareValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
record := core.NewRecord(core.NewBaseCollection("test"))
f1, err := filesystem.NewFileFromBytes([]byte("test"), "test1.txt")
if err != nil {
t.Fatal(err)
}
f1Raw, err := json.Marshal(f1)
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
raw any
field *core.FileField
expected string
}{
// single
{nil, &core.FileField{MaxSelect: 1}, `""`},
{"", &core.FileField{MaxSelect: 1}, `""`},
{123, &core.FileField{MaxSelect: 1}, `"123"`},
{"a", &core.FileField{MaxSelect: 1}, `"a"`},
{`["a"]`, &core.FileField{MaxSelect: 1}, `"a"`},
{*f1, &core.FileField{MaxSelect: 1}, string(f1Raw)},
{f1, &core.FileField{MaxSelect: 1}, string(f1Raw)},
{[]string{}, &core.FileField{MaxSelect: 1}, `""`},
{[]string{"a", "b"}, &core.FileField{MaxSelect: 1}, `"b"`},
// multiple
{nil, &core.FileField{MaxSelect: 2}, `[]`},
{"", &core.FileField{MaxSelect: 2}, `[]`},
{123, &core.FileField{MaxSelect: 2}, `["123"]`},
{"a", &core.FileField{MaxSelect: 2}, `["a"]`},
{`["a"]`, &core.FileField{MaxSelect: 2}, `["a"]`},
{[]any{f1}, &core.FileField{MaxSelect: 2}, `[` + string(f1Raw) + `]`},
{[]*filesystem.File{f1}, &core.FileField{MaxSelect: 2}, `[` + string(f1Raw) + `]`},
{[]filesystem.File{*f1}, &core.FileField{MaxSelect: 2}, `[` + string(f1Raw) + `]`},
{[]string{}, &core.FileField{MaxSelect: 2}, `[]`},
{[]string{"a", "b", "c"}, &core.FileField{MaxSelect: 2}, `["a","b","c"]`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v_%v", i, s.raw, s.field.IsMultiple()), func(t *testing.T) {
v, err := s.field.PrepareValue(record, s.raw)
if err != nil {
t.Fatal(err)
}
vRaw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if string(vRaw) != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, vRaw)
}
})
}
}
func TestFileFieldDriverValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f1, err := filesystem.NewFileFromBytes([]byte("test"), "test.txt")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
raw any
field *core.FileField
expected string
}{
// single
{nil, &core.FileField{MaxSelect: 1}, `""`},
{"", &core.FileField{MaxSelect: 1}, `""`},
{123, &core.FileField{MaxSelect: 1}, `"123"`},
{"a", &core.FileField{MaxSelect: 1}, `"a"`},
{`["a"]`, &core.FileField{MaxSelect: 1}, `"a"`},
{f1, &core.FileField{MaxSelect: 1}, `"` + f1.Name + `"`},
{[]string{}, &core.FileField{MaxSelect: 1}, `""`},
{[]string{"a", "b"}, &core.FileField{MaxSelect: 1}, `"b"`},
// multiple
{nil, &core.FileField{MaxSelect: 2}, `[]`},
{"", &core.FileField{MaxSelect: 2}, `[]`},
{123, &core.FileField{MaxSelect: 2}, `["123"]`},
{"a", &core.FileField{MaxSelect: 2}, `["a"]`},
{`["a"]`, &core.FileField{MaxSelect: 2}, `["a"]`},
{[]any{"a", f1}, &core.FileField{MaxSelect: 2}, `["a","` + f1.Name + `"]`},
{[]string{}, &core.FileField{MaxSelect: 2}, `[]`},
{[]string{"a", "b", "c"}, &core.FileField{MaxSelect: 2}, `["a","b","c"]`},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%#v_%v", i, s.raw, s.field.IsMultiple()), func(t *testing.T) {
record := core.NewRecord(core.NewBaseCollection("test"))
record.SetRaw(s.field.GetName(), s.raw)
v, err := s.field.DriverValue(record)
if err != nil {
t.Fatal(err)
}
if s.field.IsMultiple() {
_, ok := v.(types.JSONArray[string])
if !ok {
t.Fatalf("Expected types.JSONArray value, got %T", v)
}
} else {
_, ok := v.(string)
if !ok {
t.Fatalf("Expected string value, got %T", v)
}
}
vRaw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if string(vRaw) != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, vRaw)
}
})
}
}
func TestFileFieldValidateValue(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection := core.NewBaseCollection("test_collection")
f1, err := filesystem.NewFileFromBytes([]byte("test"), "test1.txt")
if err != nil {
t.Fatal(err)
}
f2, err := filesystem.NewFileFromBytes([]byte("test"), "test2.txt")
if err != nil {
t.Fatal(err)
}
f3, err := filesystem.NewFileFromBytes([]byte("test_abc"), "test3.txt")
if err != nil {
t.Fatal(err)
}
f4, err := filesystem.NewFileFromBytes(make([]byte, core.DefaultFileFieldMaxSize+1), "test4.txt")
if err != nil {
t.Fatal(err)
}
f5, err := filesystem.NewFileFromBytes(make([]byte, core.DefaultFileFieldMaxSize), "test5.txt")
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
field *core.FileField
record func() *core.Record
expectError bool
}{
// single
{
"zero field value (not required)",
&core.FileField{Name: "test", MaxSize: 9999, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
false,
},
{
"zero field value (required)",
&core.FileField{Name: "test", MaxSize: 9999, MaxSelect: 1, Required: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "")
return record
},
true,
},
{
"new plain filename", // new files must be *filesystem.File
&core.FileField{Name: "test", MaxSize: 9999, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "a")
return record
},
true,
},
{
"new file",
&core.FileField{Name: "test", MaxSize: 9999, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", f1)
return record
},
false,
},
{
"new files > MaxSelect",
&core.FileField{Name: "test", MaxSize: 9999, MaxSelect: 1},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []any{f1, f2})
return record
},
true,
},
{
"new files <= MaxSelect",
&core.FileField{Name: "test", MaxSize: 9999, MaxSelect: 2},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []any{f1, f2})
return record
},
false,
},
{
"> default MaxSize",
&core.FileField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", f4)
return record
},
true,
},
{
"<= default MaxSize",
&core.FileField{Name: "test"},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", f5)
return record
},
false,
},
{
"> MaxSize",
&core.FileField{Name: "test", MaxSize: 4, MaxSelect: 3},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []any{f1, f2, f3}) // f3=8
return record
},
true,
},
{
"<= MaxSize",
&core.FileField{Name: "test", MaxSize: 8, MaxSelect: 3},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []any{f1, f2, f3})
return record
},
false,
},
{
"non-matching MimeType",
&core.FileField{Name: "test", MaxSize: 999, MaxSelect: 3, MimeTypes: []string{"a", "b"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []any{f1, f2})
return record
},
true,
},
{
"matching MimeType",
&core.FileField{Name: "test", MaxSize: 999, MaxSelect: 3, MimeTypes: []string{"text/plain", "b"}},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", []any{f1, f2})
return record
},
false,
},
{
"existing files > MaxSelect",
&core.FileField{Name: "file_many", MaxSize: 999, MaxSelect: 2},
func() *core.Record {
record, _ := app.FindRecordById("demo1", "84nmscqy84lsi1t") // 5 files
return record
},
true,
},
{
"existing files should ignore the MaxSize and Mimetypes checks",
&core.FileField{Name: "file_many", MaxSize: 1, MaxSelect: 5, MimeTypes: []string{"a", "b"}},
func() *core.Record {
record, _ := app.FindRecordById("demo1", "84nmscqy84lsi1t")
return record
},
false,
},
{
"existing + new file > MaxSelect (5+2)",
&core.FileField{Name: "file_many", MaxSize: 999, MaxSelect: 6},
func() *core.Record {
record, _ := app.FindRecordById("demo1", "84nmscqy84lsi1t")
record.Set("file_many+", []any{f1, f2})
return record
},
true,
},
{
"existing + new file <= MaxSelect (5+2)",
&core.FileField{Name: "file_many", MaxSize: 999, MaxSelect: 7},
func() *core.Record {
record, _ := app.FindRecordById("demo1", "84nmscqy84lsi1t")
record.Set("file_many+", []any{f1, f2})
return record
},
false,
},
{
"existing + new filename",
&core.FileField{Name: "file_many", MaxSize: 999, MaxSelect: 99},
func() *core.Record {
record, _ := app.FindRecordById("demo1", "84nmscqy84lsi1t")
record.Set("file_many+", "test123.png")
return record
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := s.field.ValidateValue(context.Background(), app, s.record())
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
func TestFileFieldValidateSettings(t *testing.T) {
testDefaultFieldIdValidation(t, core.FieldTypeFile)
testDefaultFieldNameValidation(t, core.FieldTypeFile)
app, _ := tests.NewTestApp()
defer app.Cleanup()
scenarios := []struct {
name string
field func() *core.FileField
expectErrors []string
}{
{
"zero minimal",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
}
},
[]string{},
},
{
"0x0 thumb",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSelect: 1,
Thumbs: []string{"100x200", "0x0"},
}
},
[]string{"thumbs"},
},
{
"0x0t thumb",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: 1,
MaxSelect: 1,
Thumbs: []string{"100x200", "0x0t"},
}
},
[]string{"thumbs"},
},
{
"0x0b thumb",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: 1,
MaxSelect: 1,
Thumbs: []string{"100x200", "0x0b"},
}
},
[]string{"thumbs"},
},
{
"0x0f thumb",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: 1,
MaxSelect: 1,
Thumbs: []string{"100x200", "0x0f"},
}
},
[]string{"thumbs"},
},
{
"invalid format",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: 1,
MaxSelect: 1,
Thumbs: []string{"100x200", "100x"},
}
},
[]string{"thumbs"},
},
{
"valid thumbs",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: 1,
MaxSelect: 1,
Thumbs: []string{"100x200", "100x40", "100x200"},
}
},
[]string{},
},
{
"MaxSize > safe json int",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: 1 << 53,
}
},
[]string{"maxSize"},
},
{
"MaxSize < 0",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSize: -1,
}
},
[]string{"maxSize"},
},
{
"MaxSelect > safe json int",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSelect: 1 << 53,
}
},
[]string{"maxSelect"},
},
{
"MaxSelect < 0",
func() *core.FileField {
return &core.FileField{
Id: "test",
Name: "test",
MaxSelect: -1,
}
},
[]string{"maxSelect"},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
field := s.field()
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(field)
errs := field.ValidateSettings(context.Background(), app, collection)
tests.TestValidationErrors(t, errs, s.expectErrors)
})
}
}
func TestFileFieldCalculateMaxBodySize(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
scenarios := []struct {
field *core.FileField
expected int64
}{
{&core.FileField{}, core.DefaultFileFieldMaxSize},
{&core.FileField{MaxSelect: 2}, 2 * core.DefaultFileFieldMaxSize},
{&core.FileField{MaxSize: 10}, 10},
{&core.FileField{MaxSize: 10, MaxSelect: 1}, 10},
{&core.FileField{MaxSize: 10, MaxSelect: 2}, 20},
}
for i, s := range scenarios {
t.Run(fmt.Sprintf("%d_%d_%d", i, s.field.MaxSelect, s.field.MaxSize), func(t *testing.T) {
result := s.field.CalculateMaxBodySize()
if result != s.expected {
t.Fatalf("Expected %d, got %d", s.expected, result)
}
})
}
}
func TestFileFieldFindGetter(t *testing.T) {
app, _ := tests.NewTestApp()
defer app.Cleanup()
f1, err := filesystem.NewFileFromBytes([]byte("test"), "f1")
if err != nil {
t.Fatal(err)
}
f1.Name = "f1"
f2, err := filesystem.NewFileFromBytes([]byte("test"), "f2")
if err != nil {
t.Fatal(err)
}
f2.Name = "f2"
record, err := app.FindRecordById("demo3", "lcl9d87w22ml6jy")
if err != nil {
t.Fatal(err)
}
record.Set("files+", []any{f1, f2})
record.Set("files-", "test_FLurQTgrY8.txt")
field, ok := record.Collection().Fields.GetByName("files").(*core.FileField)
if !ok {
t.Fatalf("Expected *core.FileField, got %T", record.Collection().Fields.GetByName("files"))
}
scenarios := []struct {
name string
key string
hasGetter bool
expected string
}{
{
"no match",
"example",
false,
"",
},
{
"exact match",
field.GetName(),
true,
`["300_UhLKX91HVb.png",{"name":"f1","originalName":"f1","size":4},{"name":"f2","originalName":"f2","size":4}]`,
},
{
"unsaved",
field.GetName() + ":unsaved",
true,
`[{"name":"f1","originalName":"f1","size":4},{"name":"f2","originalName":"f2","size":4}]`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
getter := field.FindGetter(s.key)
hasGetter := getter != nil
if hasGetter != s.hasGetter {
t.Fatalf("Expected hasGetter %v, got %v", s.hasGetter, hasGetter)
}
if !hasGetter {
return
}
v := getter(record)
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected\n%v\ngot\n%v", s.expected, rawStr)
}
})
}
}
func TestFileFieldFindSetter(t *testing.T) {
scenarios := []struct {
name string
key string
value any
field *core.FileField
hasSetter bool
expected string
}{
{
"no match",
"example",
"b",
&core.FileField{Name: "test", MaxSelect: 1},
false,
"",
},
{
"exact match (single)",
"test",
"b",
&core.FileField{Name: "test", MaxSelect: 1},
true,
`"b"`,
},
{
"exact match (multiple)",
"test",
[]string{"a", "b", "b"},
&core.FileField{Name: "test", MaxSelect: 2},
true,
`["a","b"]`,
},
{
"append (single)",
"test+",
"b",
&core.FileField{Name: "test", MaxSelect: 1},
true,
`"b"`,
},
{
"append (multiple)",
"test+",
[]string{"a"},
&core.FileField{Name: "test", MaxSelect: 2},
true,
`["c","d","a"]`,
},
{
"prepend (single)",
"+test",
"b",
&core.FileField{Name: "test", MaxSelect: 1},
true,
`"d"`, // the last of the existing values
},
{
"prepend (multiple)",
"+test",
[]string{"a"},
&core.FileField{Name: "test", MaxSelect: 2},
true,
`["a","c","d"]`,
},
{
"subtract (single)",
"test-",
"d",
&core.FileField{Name: "test", MaxSelect: 1},
true,
`"c"`,
},
{
"subtract (multiple)",
"test-",
[]string{"unknown", "c"},
&core.FileField{Name: "test", MaxSelect: 2},
true,
`["d"]`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
collection := core.NewBaseCollection("test_collection")
collection.Fields.Add(s.field)
setter := s.field.FindSetter(s.key)
hasSetter := setter != nil
if hasSetter != s.hasSetter {
t.Fatalf("Expected hasSetter %v, got %v", s.hasSetter, hasSetter)
}
if !hasSetter {
return
}
record := core.NewRecord(collection)
record.SetRaw(s.field.GetName(), []string{"c", "d"})
setter(record, s.value)
raw, err := json.Marshal(record.Get(s.field.GetName()))
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
if rawStr != s.expected {
t.Fatalf("Expected %q, got %q", s.expected, rawStr)
}
})
}
}
func TestFileFieldIntercept(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
demo1.Fields.GetByName("text").(*core.TextField).Required = true // trigger validation error
f1, err := filesystem.NewFileFromBytes([]byte("test"), "new1.txt")
if err != nil {
t.Fatal(err)
}
f2, err := filesystem.NewFileFromBytes([]byte("test"), "new2.txt")
if err != nil {
t.Fatal(err)
}
f3, err := filesystem.NewFileFromBytes([]byte("test"), "new3.txt")
if err != nil {
t.Fatal(err)
}
f4, err := filesystem.NewFileFromBytes([]byte("test"), "new4.txt")
if err != nil {
t.Fatal(err)
}
record := core.NewRecord(demo1)
ok := t.Run("1. create - with validation error", func(t *testing.T) {
record.Set("file_many", []any{f1, f2})
err := testApp.Save(record)
tests.TestValidationErrors(t, err, []string{"text"})
value, _ := record.GetRaw("file_many").([]any)
if len(value) != 2 {
t.Fatalf("Expected the file field value to be unchanged, got %v", value)
}
})
if !ok {
return
}
ok = t.Run("2. create - fixing the validation error", func(t *testing.T) {
record.Set("text", "abc")
err := testApp.Save(record)
if err != nil {
t.Fatalf("Expected save to succeed, got %v", err)
}
expectedKeys := []string{f1.Name, f2.Name}
raw := record.GetRaw("file_many")
// ensure that the value was replaced with the file names
value := list.ToUniqueStringSlice(raw)
if len(value) != len(expectedKeys) {
t.Fatalf("Expected the file field to be updated with the %d file names, got\n%v", len(expectedKeys), raw)
}
for _, name := range expectedKeys {
if !slices.Contains(value, name) {
t.Fatalf("Missing file %q in %v", name, value)
}
}
checkRecordFiles(t, testApp, record, expectedKeys)
})
if !ok {
return
}
ok = t.Run("3. update - validation error", func(t *testing.T) {
record.Set("text", "")
record.Set("file_many+", f3)
record.Set("file_many-", f2.Name)
err := testApp.Save(record)
tests.TestValidationErrors(t, err, []string{"text"})
raw, _ := json.Marshal(record.GetRaw("file_many"))
expectedRaw, _ := json.Marshal([]any{f1.Name, f3})
if !bytes.Equal(expectedRaw, raw) {
t.Fatalf("Expected file field value\n%s\ngot\n%s", expectedRaw, raw)
}
checkRecordFiles(t, testApp, record, []string{f1.Name, f2.Name})
})
if !ok {
return
}
ok = t.Run("4. update - fixing the validation error", func(t *testing.T) {
record.Set("text", "abc2")
err := testApp.Save(record)
if err != nil {
t.Fatalf("Expected save to succeed, got %v", err)
}
raw, _ := json.Marshal(record.GetRaw("file_many"))
expectedRaw, _ := json.Marshal([]any{f1.Name, f3.Name})
if !bytes.Equal(expectedRaw, raw) {
t.Fatalf("Expected file field value\n%s\ngot\n%s", expectedRaw, raw)
}
checkRecordFiles(t, testApp, record, []string{f1.Name, f3.Name})
})
if !ok {
return
}
t.Run("5. update - second time update", func(t *testing.T) {
record.Set("file_many-", f1.Name)
record.Set("file_many+", f4)
err := testApp.Save(record)
if err != nil {
t.Fatalf("Expected save to succeed, got %v", err)
}
raw, _ := json.Marshal(record.GetRaw("file_many"))
expectedRaw, _ := json.Marshal([]any{f3.Name, f4.Name})
if !bytes.Equal(expectedRaw, raw) {
t.Fatalf("Expected file field value\n%s\ngot\n%s", expectedRaw, raw)
}
checkRecordFiles(t, testApp, record, []string{f3.Name, f4.Name})
})
}
func TestFileFieldInterceptTx(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
demo1, err := testApp.FindCollectionByNameOrId("demo1")
if err != nil {
t.Fatal(err)
}
demo1.Fields.GetByName("text").(*core.TextField).Required = true // trigger validation error
f1, err := filesystem.NewFileFromBytes([]byte("test"), "new1.txt")
if err != nil {
t.Fatal(err)
}
f2, err := filesystem.NewFileFromBytes([]byte("test"), "new2.txt")
if err != nil {
t.Fatal(err)
}
f3, err := filesystem.NewFileFromBytes([]byte("test"), "new3.txt")
if err != nil {
t.Fatal(err)
}
f4, err := filesystem.NewFileFromBytes([]byte("test"), "new4.txt")
if err != nil {
t.Fatal(err)
}
var record *core.Record
tx := func(succeed bool) func(txApp core.App) error {
var txErr error
if !succeed {
txErr = errors.New("tx error")
}
return func(txApp core.App) error {
record = core.NewRecord(demo1)
ok := t.Run(fmt.Sprintf("[tx_%v] create with validation error", succeed), func(t *testing.T) {
record.Set("text", "")
record.Set("file_many", []any{f1, f2})
err := txApp.Save(record)
tests.TestValidationErrors(t, err, []string{"text"})
checkRecordFiles(t, txApp, record, []string{}) // no uploaded files
})
if !ok {
return txErr
}
// ---
ok = t.Run(fmt.Sprintf("[tx_%v] create with fixed validation error", succeed), func(t *testing.T) {
record.Set("text", "abc")
err = txApp.Save(record)
if err != nil {
t.Fatalf("Expected save to succeed, got %v", err)
}
checkRecordFiles(t, txApp, record, []string{f1.Name, f2.Name})
})
if !ok {
return txErr
}
// ---
ok = t.Run(fmt.Sprintf("[tx_%v] update with validation error", succeed), func(t *testing.T) {
record.Set("text", "")
record.Set("file_many+", f3)
record.Set("file_many-", f2.Name)
err = txApp.Save(record)
tests.TestValidationErrors(t, err, []string{"text"})
raw, _ := json.Marshal(record.GetRaw("file_many"))
expectedRaw, _ := json.Marshal([]any{f1.Name, f3})
if !bytes.Equal(expectedRaw, raw) {
t.Fatalf("Expected file field value\n%s\ngot\n%s", expectedRaw, raw)
}
checkRecordFiles(t, txApp, record, []string{f1.Name, f2.Name}) // no file changes
})
if !ok {
return txErr
}
// ---
ok = t.Run(fmt.Sprintf("[tx_%v] update with fixed validation error", succeed), func(t *testing.T) {
record.Set("text", "abc2")
err = txApp.Save(record)
if err != nil {
t.Fatalf("Expected save to succeed, got %v", err)
}
raw, _ := json.Marshal(record.GetRaw("file_many"))
expectedRaw, _ := json.Marshal([]any{f1.Name, f3.Name})
if !bytes.Equal(expectedRaw, raw) {
t.Fatalf("Expected file field value\n%s\ngot\n%s", expectedRaw, raw)
}
checkRecordFiles(t, txApp, record, []string{f1.Name, f3.Name, f2.Name}) // f2 shouldn't be deleted yet
})
if !ok {
return txErr
}
// ---
ok = t.Run(fmt.Sprintf("[tx_%v] second time update", succeed), func(t *testing.T) {
record.Set("file_many-", f1.Name)
record.Set("file_many+", f4)
err := txApp.Save(record)
if err != nil {
t.Fatalf("Expected save to succeed, got %v", err)
}
raw, _ := json.Marshal(record.GetRaw("file_many"))
expectedRaw, _ := json.Marshal([]any{f3.Name, f4.Name})
if !bytes.Equal(expectedRaw, raw) {
t.Fatalf("Expected file field value\n%s\ngot\n%s", expectedRaw, raw)
}
checkRecordFiles(t, txApp, record, []string{f3.Name, f4.Name, f1.Name, f2.Name}) // f1 and f2 shouldn't be deleted yet
})
if !ok {
return txErr
}
// ---
return txErr
}
}
// failed transaction
txErr := testApp.RunInTransaction(tx(false))
if txErr == nil {
t.Fatal("Expected transaction error")
}
// there shouldn't be any fails associated with the record id
checkRecordFiles(t, testApp, record, []string{})
txErr = testApp.RunInTransaction(tx(true))
if txErr != nil {
t.Fatalf("Expected transaction to succeed, got %v", txErr)
}
// only the last updated files should remain
checkRecordFiles(t, testApp, record, []string{f3.Name, f4.Name})
}
// -------------------------------------------------------------------
func checkRecordFiles(t *testing.T, testApp core.App, record *core.Record, expectedKeys []string) {
fsys, err := testApp.NewFilesystem()
if err != nil {
t.Fatal(err)
}
defer fsys.Close()
objects, err := fsys.List(record.BaseFilesPath() + "/")
if err != nil {
t.Fatal(err)
}
objectKeys := make([]string, 0, len(objects))
for _, obj := range objects {
// exclude thumbs
if !strings.Contains(obj.Key, "/thumbs_") {
objectKeys = append(objectKeys, obj.Key)
}
}
if len(objectKeys) != len(expectedKeys) {
t.Fatalf("Expected files:\n%v\ngot\n%v", expectedKeys, objectKeys)
}
for _, key := range expectedKeys {
fullKey := record.BaseFilesPath() + "/" + key
if !slices.Contains(objectKeys, fullKey) {
t.Fatalf("Missing expected file key\n%q\nin\n%v", fullKey, objectKeys)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_model_view_options.go | core/collection_model_view_options.go | package core
import (
validation "github.com/go-ozzo/ozzo-validation/v4"
)
var _ optionsValidator = (*collectionViewOptions)(nil)
// collectionViewOptions defines the options for the "view" type collection.
type collectionViewOptions struct {
ViewQuery string `form:"viewQuery" json:"viewQuery"`
}
func (o *collectionViewOptions) validate(cv *collectionValidator) error {
return validation.ValidateStruct(o,
validation.Field(&o.ViewQuery, validation.Required, validation.By(cv.checkViewQuery)),
)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/field_editor.go | core/field_editor.go | package core
import (
"context"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/core/validators"
"github.com/spf13/cast"
)
func init() {
Fields[FieldTypeEditor] = func() Field {
return &EditorField{}
}
}
const FieldTypeEditor = "editor"
const DefaultEditorFieldMaxSize int64 = 5 << 20
var (
_ Field = (*EditorField)(nil)
_ MaxBodySizeCalculator = (*EditorField)(nil)
)
// EditorField defines "editor" type field to store HTML formatted text.
//
// The respective zero record field value is empty string.
type EditorField struct {
// Name (required) is the unique name of the field.
Name string `form:"name" json:"name"`
// Id is the unique stable field identifier.
//
// It is automatically generated from the name when adding to a collection FieldsList.
Id string `form:"id" json:"id"`
// System prevents the renaming and removal of the field.
System bool `form:"system" json:"system"`
// Hidden hides the field from the API response.
Hidden bool `form:"hidden" json:"hidden"`
// Presentable hints the Dashboard UI to use the underlying
// field record value in the relation preview label.
Presentable bool `form:"presentable" json:"presentable"`
// ---
// MaxSize specifies the maximum size of the allowed field value (in bytes and up to 2^53-1).
//
// If zero, a default limit of ~5MB is applied.
MaxSize int64 `form:"maxSize" json:"maxSize"`
// ConvertURLs is usually used to instruct the editor whether to
// apply url conversion (eg. stripping the domain name in case the
// urls are using the same domain as the one where the editor is loaded).
//
// (see also https://www.tiny.cloud/docs/tinymce/6/url-handling/#convert_urls)
ConvertURLs bool `form:"convertURLs" json:"convertURLs"`
// Required will require the field value to be non-empty string.
Required bool `form:"required" json:"required"`
}
// Type implements [Field.Type] interface method.
func (f *EditorField) Type() string {
return FieldTypeEditor
}
// GetId implements [Field.GetId] interface method.
func (f *EditorField) GetId() string {
return f.Id
}
// SetId implements [Field.SetId] interface method.
func (f *EditorField) SetId(id string) {
f.Id = id
}
// GetName implements [Field.GetName] interface method.
func (f *EditorField) GetName() string {
return f.Name
}
// SetName implements [Field.SetName] interface method.
func (f *EditorField) SetName(name string) {
f.Name = name
}
// GetSystem implements [Field.GetSystem] interface method.
func (f *EditorField) GetSystem() bool {
return f.System
}
// SetSystem implements [Field.SetSystem] interface method.
func (f *EditorField) SetSystem(system bool) {
f.System = system
}
// GetHidden implements [Field.GetHidden] interface method.
func (f *EditorField) GetHidden() bool {
return f.Hidden
}
// SetHidden implements [Field.SetHidden] interface method.
func (f *EditorField) SetHidden(hidden bool) {
f.Hidden = hidden
}
// ColumnType implements [Field.ColumnType] interface method.
func (f *EditorField) ColumnType(app App) string {
return "TEXT DEFAULT '' NOT NULL"
}
// PrepareValue implements [Field.PrepareValue] interface method.
func (f *EditorField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToString(raw), nil
}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *EditorField) ValidateValue(ctx context.Context, app App, record *Record) error {
val, ok := record.GetRaw(f.Name).(string)
if !ok {
return validators.ErrUnsupportedValueType
}
if f.Required {
if err := validation.Required.Validate(val); err != nil {
return err
}
}
maxSize := f.CalculateMaxBodySize()
if int64(len(val)) > maxSize {
return validation.NewError(
"validation_content_size_limit",
"The maximum allowed content size is {{.maxSize}} bytes",
).SetParams(map[string]any{"maxSize": maxSize})
}
return nil
}
// ValidateSettings implements [Field.ValidateSettings] interface method.
func (f *EditorField) ValidateSettings(ctx context.Context, app App, collection *Collection) error {
return validation.ValidateStruct(f,
validation.Field(&f.Id, validation.By(DefaultFieldIdValidationRule)),
validation.Field(&f.Name, validation.By(DefaultFieldNameValidationRule)),
validation.Field(&f.MaxSize, validation.Min(0), validation.Max(maxSafeJSONInt)),
)
}
// CalculateMaxBodySize implements the [MaxBodySizeCalculator] interface.
func (f *EditorField) CalculateMaxBodySize() int64 {
if f.MaxSize <= 0 {
return DefaultEditorFieldMaxSize
}
return f.MaxSize
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/otp_query.go | core/otp_query.go | package core
import (
"errors"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/types"
)
// FindAllOTPsByRecord returns all OTP models linked to the provided auth record.
func (app *BaseApp) FindAllOTPsByRecord(authRecord *Record) ([]*OTP, error) {
result := []*OTP{}
err := app.RecordQuery(CollectionNameOTPs).
AndWhere(dbx.HashExp{
"collectionRef": authRecord.Collection().Id,
"recordRef": authRecord.Id,
}).
OrderBy("created DESC").
All(&result)
if err != nil {
return nil, err
}
return result, nil
}
// FindAllOTPsByCollection returns all OTP models linked to the provided collection.
func (app *BaseApp) FindAllOTPsByCollection(collection *Collection) ([]*OTP, error) {
result := []*OTP{}
err := app.RecordQuery(CollectionNameOTPs).
AndWhere(dbx.HashExp{"collectionRef": collection.Id}).
OrderBy("created DESC").
All(&result)
if err != nil {
return nil, err
}
return result, nil
}
// FindOTPById returns a single OTP model by its id.
func (app *BaseApp) FindOTPById(id string) (*OTP, error) {
result := &OTP{}
err := app.RecordQuery(CollectionNameOTPs).
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
One(result)
if err != nil {
return nil, err
}
return result, nil
}
// DeleteAllOTPsByRecord deletes all OTP models associated with the provided record.
//
// Returns a combined error with the failed deletes.
func (app *BaseApp) DeleteAllOTPsByRecord(authRecord *Record) error {
models, err := app.FindAllOTPsByRecord(authRecord)
if err != nil {
return err
}
var errs []error
for _, m := range models {
if err := app.Delete(m); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// DeleteExpiredOTPs deletes the expired OTPs for all auth collections.
func (app *BaseApp) DeleteExpiredOTPs() error {
authCollections, err := app.FindAllCollections(CollectionTypeAuth)
if err != nil {
return err
}
// note: perform even if OTP is disabled to ensure that there are no dangling old records
for _, collection := range authCollections {
minValidDate, err := types.ParseDateTime(time.Now().Add(-1 * collection.OTP.DurationTime()))
if err != nil {
return err
}
items := []*Record{}
err = app.RecordQuery(CollectionNameOTPs).
AndWhere(dbx.HashExp{"collectionRef": collection.Id}).
AndWhere(dbx.NewExp("[[created]] < {:date}", dbx.Params{"date": minValidDate})).
All(&items)
if err != nil {
return err
}
for _, item := range items {
err = app.Delete(item)
if err != nil {
return err
}
}
}
return nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/collection_import_test.go | core/collection_import_test.go | package core_test
import (
"encoding/json"
"strings"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
)
func TestImportCollections(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
var regularCollections []*core.Collection
err := testApp.CollectionQuery().AndWhere(dbx.HashExp{"system": false}).All(®ularCollections)
if err != nil {
t.Fatal(err)
}
var systemCollections []*core.Collection
err = testApp.CollectionQuery().AndWhere(dbx.HashExp{"system": true}).All(&systemCollections)
if err != nil {
t.Fatal(err)
}
totalRegularCollections := len(regularCollections)
totalSystemCollections := len(systemCollections)
totalCollections := totalRegularCollections + totalSystemCollections
scenarios := []struct {
name string
data []map[string]any
deleteMissing bool
expectError bool
expectCollectionsCount int
afterTestFunc func(testApp *tests.TestApp, resultCollections []*core.Collection)
}{
{
name: "empty collections",
data: []map[string]any{},
expectError: true,
expectCollectionsCount: totalCollections,
},
{
name: "minimal collection import (with missing system fields)",
data: []map[string]any{
{"name": "import_test1", "type": "auth"},
{
"name": "import_test2", "fields": []map[string]any{
{"name": "test", "type": "text"},
},
},
},
deleteMissing: false,
expectError: false,
expectCollectionsCount: totalCollections + 2,
},
{
name: "minimal collection import (trigger collection model validations)",
data: []map[string]any{
{"name": ""},
{
"name": "import_test2", "fields": []map[string]any{
{"name": "test", "type": "text"},
},
},
},
deleteMissing: false,
expectError: true,
expectCollectionsCount: totalCollections,
},
{
name: "minimal collection import (trigger field settings validation)",
data: []map[string]any{
{"name": "import_test", "fields": []map[string]any{{"name": "test", "type": "text", "min": -1}}},
},
deleteMissing: false,
expectError: true,
expectCollectionsCount: totalCollections,
},
{
name: "new + update + delete (system collections delete should be ignored)",
data: []map[string]any{
{
"id": "wsmn24bux7wo113",
"name": "demo",
"fields": []map[string]any{
{
"id": "_2hlxbmp",
"name": "title",
"type": "text",
"system": false,
"required": true,
"min": 3,
"max": nil,
"pattern": "",
},
},
"indexes": []string{},
},
{
"name": "import1",
"fields": []map[string]any{
{
"name": "active",
"type": "bool",
},
},
},
},
deleteMissing: true,
expectError: false,
expectCollectionsCount: totalSystemCollections + 2,
},
{
name: "test with deleteMissing: false",
data: []map[string]any{
{
// "id": "wsmn24bux7wo113", // test update with only name as identifier
"name": "demo1",
"fields": []map[string]any{
{
"id": "_2hlxbmp",
"name": "title",
"type": "text",
"system": false,
"required": true,
"min": 3,
"max": nil,
"pattern": "",
},
{
"id": "_2hlxbmp",
"name": "field_with_duplicate_id",
"type": "text",
"system": false,
"required": true,
"unique": false,
"min": 4,
"max": nil,
"pattern": "",
},
{
"id": "abcd_import",
"name": "new_field",
"type": "text",
},
},
},
{
"name": "new_import",
"fields": []map[string]any{
{
"id": "abcd_import",
"name": "active",
"type": "bool",
},
},
},
},
deleteMissing: false,
expectError: false,
expectCollectionsCount: totalCollections + 1,
afterTestFunc: func(testApp *tests.TestApp, resultCollections []*core.Collection) {
expectedCollectionFields := map[string]int{
core.CollectionNameAuthOrigins: 6,
"nologin": 10,
"demo1": 19,
"demo2": 5,
"demo3": 5,
"demo4": 16,
"demo5": 9,
"new_import": 2,
}
for name, expectedCount := range expectedCollectionFields {
collection, err := testApp.FindCollectionByNameOrId(name)
if err != nil {
t.Fatal(err)
}
if totalFields := len(collection.Fields); totalFields != expectedCount {
t.Errorf("Expected %d %q fields, got %d", expectedCount, collection.Name, totalFields)
}
}
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
err := testApp.ImportCollections(s.data, s.deleteMissing)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
// check collections count
collections := []*core.Collection{}
if err := testApp.CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != s.expectCollectionsCount {
t.Fatalf("Expected %d collections, got %d", s.expectCollectionsCount, len(collections))
}
if s.afterTestFunc != nil {
s.afterTestFunc(testApp, collections)
}
})
}
}
func TestImportCollectionsByMarshaledJSON(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
var regularCollections []*core.Collection
err := testApp.CollectionQuery().AndWhere(dbx.HashExp{"system": false}).All(®ularCollections)
if err != nil {
t.Fatal(err)
}
var systemCollections []*core.Collection
err = testApp.CollectionQuery().AndWhere(dbx.HashExp{"system": true}).All(&systemCollections)
if err != nil {
t.Fatal(err)
}
totalRegularCollections := len(regularCollections)
totalSystemCollections := len(systemCollections)
totalCollections := totalRegularCollections + totalSystemCollections
scenarios := []struct {
name string
data string
deleteMissing bool
expectError bool
expectCollectionsCount int
afterTestFunc func(testApp *tests.TestApp, resultCollections []*core.Collection)
}{
{
name: "invalid json array",
data: `{"test":123}`,
expectError: true,
expectCollectionsCount: totalCollections,
},
{
name: "new + update + delete (system collections delete should be ignored)",
data: `[
{
"id": "wsmn24bux7wo113",
"name": "demo",
"fields": [
{
"id": "_2hlxbmp",
"name": "title",
"type": "text",
"system": false,
"required": true,
"min": 3,
"max": null,
"pattern": ""
}
],
"indexes": []
},
{
"name": "import1",
"fields": [
{
"name": "active",
"type": "bool"
}
]
}
]`,
deleteMissing: true,
expectError: false,
expectCollectionsCount: totalSystemCollections + 2,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
err := testApp.ImportCollectionsByMarshaledJSON([]byte(s.data), s.deleteMissing)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr to be %v, got %v (%v)", s.expectError, hasErr, err)
}
// check collections count
collections := []*core.Collection{}
if err := testApp.CollectionQuery().All(&collections); err != nil {
t.Fatal(err)
}
if len(collections) != s.expectCollectionsCount {
t.Fatalf("Expected %d collections, got %d", s.expectCollectionsCount, len(collections))
}
if s.afterTestFunc != nil {
s.afterTestFunc(testApp, collections)
}
})
}
}
func TestImportCollectionsUpdateRules(t *testing.T) {
t.Parallel()
scenarios := []struct {
name string
data map[string]any
deleteMissing bool
}{
{
"extend existing by name (without deleteMissing)",
map[string]any{"name": "clients", "authToken": map[string]any{"duration": 100}, "fields": []map[string]any{{"name": "test", "type": "text"}}},
false,
},
{
"extend existing by id (without deleteMissing)",
map[string]any{"id": "v851q4r790rhknl", "authToken": map[string]any{"duration": 100}, "fields": []map[string]any{{"name": "test", "type": "text"}}},
false,
},
{
"extend with delete missing",
map[string]any{
"id": "v851q4r790rhknl",
"authToken": map[string]any{"duration": 100},
"fields": []map[string]any{{"name": "test", "type": "text"}},
"passwordAuth": map[string]any{"identityFields": []string{"email"}},
"indexes": []string{
// min required system fields indexes
"CREATE UNIQUE INDEX `_v851q4r790rhknl_email_idx` ON `clients` (email) WHERE email != ''",
"CREATE UNIQUE INDEX `_v851q4r790rhknl_tokenKey_idx` ON `clients` (tokenKey)",
},
},
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
beforeCollection, err := testApp.FindCollectionByNameOrId("clients")
if err != nil {
t.Fatal(err)
}
err = testApp.ImportCollections([]map[string]any{s.data}, s.deleteMissing)
if err != nil {
t.Fatal(err)
}
afterCollection, err := testApp.FindCollectionByNameOrId("clients")
if err != nil {
t.Fatal(err)
}
if afterCollection.AuthToken.Duration != 100 {
t.Fatalf("Expected AuthToken duration to be %d, got %d", 100, afterCollection.AuthToken.Duration)
}
if beforeCollection.AuthToken.Secret != afterCollection.AuthToken.Secret {
t.Fatalf("Expected AuthToken secrets to remain the same, got\n%q\nVS\n%q", beforeCollection.AuthToken.Secret, afterCollection.AuthToken.Secret)
}
if beforeCollection.Name != afterCollection.Name {
t.Fatalf("Expected Name to remain the same, got\n%q\nVS\n%q", beforeCollection.Name, afterCollection.Name)
}
if beforeCollection.Id != afterCollection.Id {
t.Fatalf("Expected Id to remain the same, got\n%q\nVS\n%q", beforeCollection.Id, afterCollection.Id)
}
if !s.deleteMissing {
totalExpectedFields := len(beforeCollection.Fields) + 1
if v := len(afterCollection.Fields); v != totalExpectedFields {
t.Fatalf("Expected %d total fields, got %d", totalExpectedFields, v)
}
if afterCollection.Fields.GetByName("test") == nil {
t.Fatalf("Missing new field %q", "test")
}
// ensure that the old fields still exist
oldFields := beforeCollection.Fields.FieldNames()
for _, name := range oldFields {
if afterCollection.Fields.GetByName(name) == nil {
t.Fatalf("Missing expected old field %q", name)
}
}
} else {
totalExpectedFields := 1
for _, f := range beforeCollection.Fields {
if f.GetSystem() {
totalExpectedFields++
}
}
if v := len(afterCollection.Fields); v != totalExpectedFields {
t.Fatalf("Expected %d total fields, got %d", totalExpectedFields, v)
}
if afterCollection.Fields.GetByName("test") == nil {
t.Fatalf("Missing new field %q", "test")
}
// ensure that the old system fields still exist
for _, f := range beforeCollection.Fields {
if f.GetSystem() && afterCollection.Fields.GetByName(f.GetName()) == nil {
t.Fatalf("Missing expected old field %q", f.GetName())
}
}
}
})
}
}
func TestImportCollectionsCreateRules(t *testing.T) {
t.Parallel()
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
err := testApp.ImportCollections([]map[string]any{
{"name": "new_test", "type": "auth", "authToken": map[string]any{"duration": 123}, "fields": []map[string]any{{"name": "test", "type": "text"}}},
}, false)
if err != nil {
t.Fatal(err)
}
collection, err := testApp.FindCollectionByNameOrId("new_test")
if err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(collection)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
expectedParts := []string{
`"name":"new_test"`,
`"fields":[`,
`"name":"id"`,
`"name":"email"`,
`"name":"tokenKey"`,
`"name":"password"`,
`"name":"test"`,
`"indexes":[`,
`CREATE UNIQUE INDEX`,
`"duration":123`,
}
for _, part := range expectedParts {
if !strings.Contains(rawStr, part) {
t.Errorf("Missing %q in\n%s", part, rawStr)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/db_connect.go | core/db_connect.go | //go:build !no_default_driver
package core
import (
"github.com/pocketbase/dbx"
_ "modernc.org/sqlite"
)
func DefaultDBConnect(dbPath string) (*dbx.DB, error) {
// Note: the busy_timeout pragma must be first because
// the connection needs to be set to block on busy before WAL mode
// is set in case it hasn't been already set by another connection.
pragmas := "?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=journal_size_limit(200000000)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(ON)&_pragma=temp_store(MEMORY)&_pragma=cache_size(-32000)"
db, err := dbx.Open("sqlite", dbPath+pragmas)
if err != nil {
return nil, err
}
return db, nil
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/base_test.go | core/base_test.go | package core_test
import (
"context"
"database/sql"
"log/slog"
"os"
"slices"
"testing"
"time"
_ "unsafe"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/logger"
"github.com/pocketbase/pocketbase/tools/mailer"
)
func TestNewBaseApp(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
EncryptionEnv: "test_env",
IsDev: true,
})
if app.DataDir() != testDataDir {
t.Fatalf("expected DataDir %q, got %q", testDataDir, app.DataDir())
}
if app.EncryptionEnv() != "test_env" {
t.Fatalf("expected EncryptionEnv test_env, got %q", app.EncryptionEnv())
}
if !app.IsDev() {
t.Fatalf("expected IsDev true, got %v", app.IsDev())
}
if app.Store() == nil {
t.Fatal("expected Store to be set, got nil")
}
if app.Settings() == nil {
t.Fatal("expected Settings to be set, got nil")
}
if app.SubscriptionsBroker() == nil {
t.Fatal("expected SubscriptionsBroker to be set, got nil")
}
if app.Cron() == nil {
t.Fatal("expected Cron to be set, got nil")
}
}
func TestBaseAppBootstrap(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
})
defer app.ResetBootstrapState()
if app.IsBootstrapped() {
t.Fatal("Didn't expect the application to be bootstrapped.")
}
if err := app.Bootstrap(); err != nil {
t.Fatal(err)
}
if !app.IsBootstrapped() {
t.Fatal("Expected the application to be bootstrapped.")
}
if stat, err := os.Stat(testDataDir); err != nil || !stat.IsDir() {
t.Fatal("Expected test data directory to be created.")
}
type nilCheck struct {
name string
value any
expectNil bool
}
runNilChecks := func(checks []nilCheck) {
for _, check := range checks {
t.Run(check.name, func(t *testing.T) {
isNil := check.value == nil
if isNil != check.expectNil {
t.Fatalf("Expected isNil %v, got %v", check.expectNil, isNil)
}
})
}
}
nilChecksBeforeReset := []nilCheck{
{"[before] db", app.DB(), false},
{"[before] concurrentDB", app.ConcurrentDB(), false},
{"[before] nonconcurrentDB", app.NonconcurrentDB(), false},
{"[before] auxDB", app.AuxDB(), false},
{"[before] auxConcurrentDB", app.AuxConcurrentDB(), false},
{"[before] auxNonconcurrentDB", app.AuxNonconcurrentDB(), false},
{"[before] settings", app.Settings(), false},
{"[before] logger", app.Logger(), false},
{"[before] cached collections", app.Store().Get(core.StoreKeyCachedCollections), false},
}
runNilChecks(nilChecksBeforeReset)
// reset
if err := app.ResetBootstrapState(); err != nil {
t.Fatal(err)
}
nilChecksAfterReset := []nilCheck{
{"[after] db", app.DB(), true},
{"[after] concurrentDB", app.ConcurrentDB(), true},
{"[after] nonconcurrentDB", app.NonconcurrentDB(), true},
{"[after] auxDB", app.AuxDB(), true},
{"[after] auxConcurrentDB", app.AuxConcurrentDB(), true},
{"[after] auxNonconcurrentDB", app.AuxNonconcurrentDB(), true},
{"[after] settings", app.Settings(), false},
{"[after] logger", app.Logger(), false},
{"[after] cached collections", app.Store().Get(core.StoreKeyCachedCollections), false},
}
runNilChecks(nilChecksAfterReset)
}
func TestNewBaseAppTx(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
})
defer app.ResetBootstrapState()
if err := app.Bootstrap(); err != nil {
t.Fatal(err)
}
mustNotHaveTx := func(app core.App) {
if app.IsTransactional() {
t.Fatalf("Didn't expect the app to be transactional")
}
if app.TxInfo() != nil {
t.Fatalf("Didn't expect the app.txInfo to be loaded")
}
}
mustHaveTx := func(app core.App) {
if !app.IsTransactional() {
t.Fatalf("Expected the app to be transactional")
}
if app.TxInfo() == nil {
t.Fatalf("Expected the app.txInfo to be loaded")
}
}
mustNotHaveTx(app)
app.RunInTransaction(func(txApp core.App) error {
mustHaveTx(txApp)
return nil
})
mustNotHaveTx(app)
}
func TestBaseAppNewMailClient(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
EncryptionEnv: "pb_test_env",
})
defer app.ResetBootstrapState()
client1 := app.NewMailClient()
m1, ok := client1.(*mailer.Sendmail)
if !ok {
t.Fatalf("Expected mailer.Sendmail instance, got %v", m1)
}
if m1.OnSend() == nil || m1.OnSend().Length() == 0 {
t.Fatal("Expected OnSend hook to be registered")
}
app.Settings().SMTP.Enabled = true
client2 := app.NewMailClient()
m2, ok := client2.(*mailer.SMTPClient)
if !ok {
t.Fatalf("Expected mailer.SMTPClient instance, got %v", m2)
}
if m2.OnSend() == nil || m2.OnSend().Length() == 0 {
t.Fatal("Expected OnSend hook to be registered")
}
}
func TestBaseAppNewFilesystem(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
})
defer app.ResetBootstrapState()
// local
local, localErr := app.NewFilesystem()
if localErr != nil {
t.Fatal(localErr)
}
if local == nil {
t.Fatal("Expected local filesystem instance, got nil")
}
// misconfigured s3
app.Settings().S3.Enabled = true
s3, s3Err := app.NewFilesystem()
if s3Err == nil {
t.Fatal("Expected S3 error, got nil")
}
if s3 != nil {
t.Fatalf("Expected nil s3 filesystem, got %v", s3)
}
}
func TestBaseAppNewBackupsFilesystem(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
})
defer app.ResetBootstrapState()
// local
local, localErr := app.NewBackupsFilesystem()
if localErr != nil {
t.Fatal(localErr)
}
if local == nil {
t.Fatal("Expected local backups filesystem instance, got nil")
}
// misconfigured s3
app.Settings().Backups.S3.Enabled = true
s3, s3Err := app.NewBackupsFilesystem()
if s3Err == nil {
t.Fatal("Expected S3 error, got nil")
}
if s3 != nil {
t.Fatalf("Expected nil s3 backups filesystem, got %v", s3)
}
}
func TestBaseAppLoggerWrites(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
// reset
if err := app.DeleteOldLogs(time.Now()); err != nil {
t.Fatal(err)
}
const logsThreshold = 200
totalLogs := func(app core.App, t *testing.T) int {
var total int
err := app.LogQuery().Select("count(*)").Row(&total)
if err != nil {
t.Fatalf("Failed to fetch total logs: %v", err)
}
return total
}
t.Run("disabled logs retention", func(t *testing.T) {
app.Settings().Logs.MaxDays = 0
for i := 0; i < logsThreshold+1; i++ {
app.Logger().Error("test")
}
if total := totalLogs(app, t); total != 0 {
t.Fatalf("Expected no logs, got %d", total)
}
})
t.Run("test batch logs writes", func(t *testing.T) {
app.Settings().Logs.MaxDays = 1
for i := 0; i < logsThreshold-1; i++ {
app.Logger().Error("test")
}
if total := totalLogs(app, t); total != 0 {
t.Fatalf("Expected no logs, got %d", total)
}
// should trigger batch write
app.Logger().Error("test")
// should be added for the next batch write
app.Logger().Error("test")
if total := totalLogs(app, t); total != logsThreshold {
t.Fatalf("Expected %d logs, got %d", logsThreshold, total)
}
// wait for ~3 secs to check the timer trigger
time.Sleep(3200 * time.Millisecond)
if total := totalLogs(app, t); total != logsThreshold+1 {
t.Fatalf("Expected %d logs, got %d", logsThreshold+1, total)
}
})
}
func TestBaseAppRefreshSettingsLoggerMinLevelEnabled(t *testing.T) {
scenarios := []struct {
name string
isDev bool
level int
// level->enabled map
expectations map[int]bool
}{
{
"dev mode",
true,
4,
map[int]bool{
3: true,
4: true,
5: true,
},
},
{
"nondev mode",
false,
4,
map[int]bool{
3: false,
4: true,
5: true,
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
const testDataDir = "./pb_base_app_test_data_dir/"
defer os.RemoveAll(testDataDir)
app := core.NewBaseApp(core.BaseAppConfig{
DataDir: testDataDir,
IsDev: s.isDev,
})
defer app.ResetBootstrapState()
if err := app.Bootstrap(); err != nil {
t.Fatal(err)
}
// silence query logs
app.ConcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {}
app.ConcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {}
app.NonconcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {}
app.NonconcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {}
handler, ok := app.Logger().Handler().(*logger.BatchHandler)
if !ok {
t.Fatalf("Expected BatchHandler, got %v", app.Logger().Handler())
}
app.Settings().Logs.MinLevel = s.level
if err := app.Save(app.Settings()); err != nil {
t.Fatalf("Failed to save settings: %v", err)
}
for level, enabled := range s.expectations {
if v := handler.Enabled(context.Background(), slog.Level(level)); v != enabled {
t.Fatalf("Expected level %d Enabled() to be %v, got %v", level, enabled, v)
}
}
})
}
}
func TestBaseAppDBDualBuilder(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
concurrentQueries := []string{}
nonconcurrentQueries := []string{}
app.ConcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
concurrentQueries = append(concurrentQueries, sql)
}
app.ConcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {
concurrentQueries = append(concurrentQueries, sql)
}
app.NonconcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
nonconcurrentQueries = append(nonconcurrentQueries, sql)
}
app.NonconcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {
nonconcurrentQueries = append(nonconcurrentQueries, sql)
}
type testQuery struct {
query string
isConcurrent bool
}
regularTests := []testQuery{
{" \n sEleCt 1", true},
{"With abc(x) AS (select 2) SELECT x FROM abc", true},
{"create table t1(x int)", false},
{"insert into t1(x) values(1)", false},
{"update t1 set x = 2", false},
{"delete from t1", false},
}
txTests := []testQuery{
{"select 3", false},
{" \n WITH abc(x) AS (select 4) SELECT x FROM abc", false},
{"create table t2(x int)", false},
{"insert into t2(x) values(1)", false},
{"update t2 set x = 2", false},
{"delete from t2", false},
}
for _, item := range regularTests {
_, err := app.DB().NewQuery(item.query).Execute()
if err != nil {
t.Fatalf("Failed to execute query %q error: %v", item.query, err)
}
}
app.RunInTransaction(func(txApp core.App) error {
for _, item := range txTests {
_, err := txApp.DB().NewQuery(item.query).Execute()
if err != nil {
t.Fatalf("Failed to execute query %q error: %v", item.query, err)
}
}
return nil
})
allTests := append(regularTests, txTests...)
for _, item := range allTests {
if item.isConcurrent {
if !slices.Contains(concurrentQueries, item.query) {
t.Fatalf("Expected concurrent query\n%q\ngot\nconcurrent:%v\nnonconcurrent:%v", item.query, concurrentQueries, nonconcurrentQueries)
}
} else {
if !slices.Contains(nonconcurrentQueries, item.query) {
t.Fatalf("Expected nonconcurrent query\n%q\ngot\nconcurrent:%v\nnonconcurrent:%v", item.query, concurrentQueries, nonconcurrentQueries)
}
}
}
}
func TestBaseAppAuxDBDualBuilder(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
concurrentQueries := []string{}
nonconcurrentQueries := []string{}
app.AuxConcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
concurrentQueries = append(concurrentQueries, sql)
}
app.AuxConcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {
concurrentQueries = append(concurrentQueries, sql)
}
app.AuxNonconcurrentDB().(*dbx.DB).QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
nonconcurrentQueries = append(nonconcurrentQueries, sql)
}
app.AuxNonconcurrentDB().(*dbx.DB).ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) {
nonconcurrentQueries = append(nonconcurrentQueries, sql)
}
type testQuery struct {
query string
isConcurrent bool
}
regularTests := []testQuery{
{" \n sEleCt 1", true},
{"With abc(x) AS (select 2) SELECT x FROM abc", true},
{"create table t1(x int)", false},
{"insert into t1(x) values(1)", false},
{"update t1 set x = 2", false},
{"delete from t1", false},
}
txTests := []testQuery{
{"select 3", false},
{" \n WITH abc(x) AS (select 4) SELECT x FROM abc", false},
{"create table t2(x int)", false},
{"insert into t2(x) values(1)", false},
{"update t2 set x = 2", false},
{"delete from t2", false},
}
for _, item := range regularTests {
_, err := app.AuxDB().NewQuery(item.query).Execute()
if err != nil {
t.Fatalf("Failed to execute query %q error: %v", item.query, err)
}
}
app.AuxRunInTransaction(func(txApp core.App) error {
for _, item := range txTests {
_, err := txApp.AuxDB().NewQuery(item.query).Execute()
if err != nil {
t.Fatalf("Failed to execute query %q error: %v", item.query, err)
}
}
return nil
})
allTests := append(regularTests, txTests...)
for _, item := range allTests {
if item.isConcurrent {
if !slices.Contains(concurrentQueries, item.query) {
t.Fatalf("Expected concurrent query\n%q\ngot\nconcurrent:%v\nnonconcurrent:%v", item.query, concurrentQueries, nonconcurrentQueries)
}
} else {
if !slices.Contains(nonconcurrentQueries, item.query) {
t.Fatalf("Expected nonconcurrent query\n%q\ngot\nconcurrent:%v\nnonconcurrent:%v", item.query, concurrentQueries, nonconcurrentQueries)
}
}
}
}
func TestBaseAppTriggerOnTerminate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
event := new(core.TerminateEvent)
event.App = app
// trigger OnTerminate multiple times to ensure that it doesn't deadlock
// https://github.com/pocketbase/pocketbase/pull/7305
app.OnTerminate().Trigger(event)
app.OnTerminate().Trigger(event)
app.OnTerminate().Trigger(event)
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/external_auth_model.go | core/external_auth_model.go | package core
import (
"context"
"errors"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/auth"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/types"
)
var (
_ Model = (*ExternalAuth)(nil)
_ PreValidator = (*ExternalAuth)(nil)
_ RecordProxy = (*ExternalAuth)(nil)
)
const CollectionNameExternalAuths = "_externalAuths"
// ExternalAuth defines a Record proxy for working with the externalAuths collection.
type ExternalAuth struct {
*Record
}
// NewExternalAuth instantiates and returns a new blank *ExternalAuth model.
//
// Example usage:
//
// ea := core.NewExternalAuth(app)
// ea.SetRecordRef(user.Id)
// ea.SetCollectionRef(user.Collection().Id)
// ea.SetProvider("google")
// ea.SetProviderId("...")
// app.Save(ea)
func NewExternalAuth(app App) *ExternalAuth {
m := &ExternalAuth{}
c, err := app.FindCachedCollectionByNameOrId(CollectionNameExternalAuths)
if err != nil {
// this is just to make tests easier since it is a system collection and it is expected to be always accessible
// (note: the loaded record is further checked on ExternalAuth.PreValidate())
c = NewBaseCollection("@__invalid__")
}
m.Record = NewRecord(c)
return m
}
// PreValidate implements the [PreValidator] interface and checks
// whether the proxy is properly loaded.
func (m *ExternalAuth) PreValidate(ctx context.Context, app App) error {
if m.Record == nil || m.Record.Collection().Name != CollectionNameExternalAuths {
return errors.New("missing or invalid ExternalAuth ProxyRecord")
}
return nil
}
// ProxyRecord returns the proxied Record model.
func (m *ExternalAuth) ProxyRecord() *Record {
return m.Record
}
// SetProxyRecord loads the specified record model into the current proxy.
func (m *ExternalAuth) SetProxyRecord(record *Record) {
m.Record = record
}
// CollectionRef returns the "collectionRef" field value.
func (m *ExternalAuth) CollectionRef() string {
return m.GetString("collectionRef")
}
// SetCollectionRef updates the "collectionRef" record field value.
func (m *ExternalAuth) SetCollectionRef(collectionId string) {
m.Set("collectionRef", collectionId)
}
// RecordRef returns the "recordRef" record field value.
func (m *ExternalAuth) RecordRef() string {
return m.GetString("recordRef")
}
// SetRecordRef updates the "recordRef" record field value.
func (m *ExternalAuth) SetRecordRef(recordId string) {
m.Set("recordRef", recordId)
}
// Provider returns the "provider" record field value.
func (m *ExternalAuth) Provider() string {
return m.GetString("provider")
}
// SetProvider updates the "provider" record field value.
func (m *ExternalAuth) SetProvider(provider string) {
m.Set("provider", provider)
}
// Provider returns the "providerId" record field value.
func (m *ExternalAuth) ProviderId() string {
return m.GetString("providerId")
}
// SetProvider updates the "providerId" record field value.
func (m *ExternalAuth) SetProviderId(providerId string) {
m.Set("providerId", providerId)
}
// Created returns the "created" record field value.
func (m *ExternalAuth) Created() types.DateTime {
return m.GetDateTime("created")
}
// Updated returns the "updated" record field value.
func (m *ExternalAuth) Updated() types.DateTime {
return m.GetDateTime("updated")
}
func (app *BaseApp) registerExternalAuthHooks() {
recordRefHooks[*ExternalAuth](app, CollectionNameExternalAuths, CollectionTypeAuth)
app.OnRecordValidate(CollectionNameExternalAuths).Bind(&hook.Handler[*RecordEvent]{
Func: func(e *RecordEvent) error {
providerNames := make([]any, 0, len(auth.Providers))
for name := range auth.Providers {
providerNames = append(providerNames, name)
}
provider := e.Record.GetString("provider")
if err := validation.Validate(provider, validation.Required, validation.In(providerNames...)); err != nil {
return validation.Errors{"provider": err}
}
return e.Next()
},
Priority: 99,
})
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
pocketbase/pocketbase | https://github.com/pocketbase/pocketbase/blob/b1da83e5165f938453fbb21e748bca317b08239d/core/migrations_list_test.go | core/migrations_list_test.go | package core_test
import (
"testing"
"github.com/pocketbase/pocketbase/core"
)
func TestMigrationsList(t *testing.T) {
l1 := core.MigrationsList{}
l1.Add(&core.Migration{File: "5_test.go"})
l1.Add(&core.Migration{ /* auto detect file name */ })
l1.Register(nil, nil, "3_test.go")
l1.Register(nil, nil, "1_test.go")
l1.Register(nil, nil, "2_test.go")
l1.Register(nil, nil /* auto detect file name */)
l2 := core.MigrationsList{}
l2.Register(nil, nil, "4_test.go")
l2.Copy(l1)
expected := []string{
"1_test.go",
"2_test.go",
"3_test.go",
"4_test.go",
"5_test.go",
// twice because there 2 test migrations with auto filename
"migrations_list_test.go",
"migrations_list_test.go",
}
items := l2.Items()
if len(items) != len(expected) {
names := make([]string, len(items))
for i, item := range items {
names[i] = item.File
}
t.Fatalf("Expected %d items, got %d:\n%v", len(expected), len(names), names)
}
for i, name := range expected {
item := l2.Item(i)
if item.File != name {
t.Fatalf("Expected name %s for index %d, got %s", name, i, item.File)
}
}
}
| go | MIT | b1da83e5165f938453fbb21e748bca317b08239d | 2026-01-07T08:35:43.517402Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.