package core
import (
"bytes"
"database/sql"
"encoding/json/v2"
"errors"
"fmt"
"slices"
"strings"
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase/tools/list"
)
const StoreKeyCachedCollections = "pbAppCachedCollections"
func (app *BaseApp) CollectionQuery() *dbx.SelectQuery {
return app.ModelQuery(&Collection{})
}
func (app *BaseApp) FindAllCollections(collectionTypes ...string) ([]*Collection, error) {
collections := []*Collection{}
q := app.CollectionQuery()
types := list.NonzeroUniques(collectionTypes)
if len(types) > 0 {
q.AndWhere(dbx.In("type", list.ToInterfaceSlice(types)...))
}
err := q.OrderBy("rowid ASC").All(&collections)
if err != nil {
return nil, err
}
return collections, nil
}
func (app *BaseApp) ReloadCachedCollections() error {
collections, err := app.FindAllCollections()
if err != nil {
return err
}
app.Store().Set(StoreKeyCachedCollections, collections)
return nil
}
func (app *BaseApp) FindCollectionByNameOrId(nameOrId string) (*Collection, error) {
m := &Collection{}
err := app.CollectionQuery().
AndWhere(dbx.NewExp("[[id]]={:id} OR LOWER([[name]])={:name}", dbx.Params{
"id": nameOrId,
"name": strings.ToLower(nameOrId),
})).
Limit(1).
One(m)
if err != nil {
return nil, err
}
return m, nil
}
func (app *BaseApp) FindCachedCollectionByNameOrId(nameOrId string) (*Collection, error) {
collections, _ := app.Store().Get(StoreKeyCachedCollections).([]*Collection)
if collections == nil {
return app.FindCollectionByNameOrId(nameOrId)
}
for _, c := range collections {
if strings.EqualFold(c.Name, nameOrId) || c.Id == nameOrId {
return c, nil
}
}
return nil, sql.ErrNoRows
}
func (app *BaseApp) FindCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error) {
collections := []*Collection{}
query := app.CollectionQuery()
if uniqueExcludeIds := list.NonzeroUniques(excludeIds); len(uniqueExcludeIds) > 0 {
query.AndWhere(dbx.NotIn("id", list.ToInterfaceSlice(uniqueExcludeIds)...))
}
if err := query.All(&collections); err != nil {
return nil, err
}
result := map[*Collection][]Field{}
for _, c := range collections {
for _, rawField := range c.Fields {
f, ok := rawField.(*RelationField)
if ok && f.CollectionId == collection.Id {
result[c] = append(result[c], f)
}
}
}
return result, nil
}
func (app *BaseApp) FindCachedCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error) {
collections, _ := app.Store().Get(StoreKeyCachedCollections).([]*Collection)
if collections == nil {
return app.FindCollectionReferences(collection, excludeIds...)
}
result := map[*Collection][]Field{}
for _, c := range collections {
if slices.Contains(excludeIds, c.Id) {
continue
}
for _, rawField := range c.Fields {
f, ok := rawField.(*RelationField)
if ok && f.CollectionId == collection.Id {
result[c] = append(result[c], f)
}
}
}
return result, nil
}
func (app *BaseApp) IsCollectionNameUnique(name string, excludeIds ...string) bool {
if name == "" {
return false
}
query := app.CollectionQuery().
Select("count(*)").
AndWhere(dbx.NewExp("LOWER([[name]])={:name}", dbx.Params{"name": strings.ToLower(name)})).
Limit(1)
if uniqueExcludeIds := list.NonzeroUniques(excludeIds); len(uniqueExcludeIds) > 0 {
query.AndWhere(dbx.NotIn("id", list.ToInterfaceSlice(uniqueExcludeIds)...))
}
var total int
return query.Row(&total) == nil && total == 0
}
func (app *BaseApp) TruncateCollection(collection *Collection) error {
if collection.IsView() {
return errors.New("view collections cannot be truncated since they don't store their own records")
}
return app.RunInTransaction(func(txApp App) error {
records := make([]*Record, 0, 500)
for {
err := txApp.RecordQuery(collection).Limit(500).All(&records)
if err != nil {
return err
}
if len(records) == 0 {
return nil
}
for _, record := range records {
err = txApp.Delete(record)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
}
records = records[:0]
}
})
}
func normalizeViewQueryId(app App, query string) (string, error) {
query = strings.Trim(strings.TrimSpace(query), ";")
info, err := getQueryTableInfo(app, query)
if err != nil {
return "", err
}
for _, row := range info {
if strings.EqualFold(row.Name, FieldNameId) && strings.EqualFold(row.Type, "TEXT") {
return query, nil
}
}
rawParsed := new(identifiersParser)
if err := rawParsed.parse(query); err != nil {
return "", err
}
columns := make([]string, 0, len(rawParsed.columns))
for _, col := range rawParsed.columns {
if col.alias == FieldNameId {
columns = append(columns, fmt.Sprintf("CAST([[%s]] as TEXT) [[%s]]", col.alias, col.alias))
} else {
columns = append(columns, "[["+col.alias+"]]")
}
}
query = fmt.Sprintf("SELECT %s FROM (%s)", strings.Join(columns, ","), query)
return query, nil
}
func resaveViewsWithChangedFields(app App, excludeIds ...string) error {
collections, err := app.FindAllCollections(CollectionTypeView)
if err != nil {
return err
}
return app.RunInTransaction(func(txApp App) error {
var collectionErrors []error
for _, collection := range collections {
if len(excludeIds) > 0 && list.ExistInSlice(collection.Id, excludeIds) {
continue
}
check := func() error {
oldFields, err := collection.Fields.Clone()
if err != nil {
return err
}
newFields, err := txApp.CreateViewFields(collection.ViewQuery)
if err != nil {
return err
}
for _, f := range oldFields {
f.SetId("")
}
for _, f := range newFields {
f.SetId("")
}
encodedNewFields, err := json.Marshal(newFields, json.Deterministic(true))
if err != nil {
return err
}
encodedOldFields, err := json.Marshal(oldFields, json.Deterministic(true))
if err != nil {
return err
}
if bytes.EqualFold(encodedNewFields, encodedOldFields) {
return nil
}
return txApp.Save(collection)
}
if err := check(); err != nil {
collectionErrors = append(
collectionErrors,
fmt.Errorf("[%s] %w", collection.Name, err),
)
}
}
return errors.Join(collectionErrors...)
})
}