MCPcopy
hub / github.com/pocketbase/pocketbase / deleteRefRecords

Function deleteRefRecords

core/record_model.go:1581–1621  ·  view source on GitHub ↗

deleteRefRecords checks if related records has to be deleted (if `CascadeDelete` is set) OR just unset the record id from any relation field values (if they are not required). NB! This method is expected to be called from inside of a transaction.

(app App, mainRecord *Record, refRecords []*Record, field Field)

Source from the content-addressed store, hash-verified

1579//
1580// NB! This method is expected to be called from inside of a transaction.
1581func deleteRefRecords(app App, mainRecord *Record, refRecords []*Record, field Field) error {
1582 relField, _ := field.(*RelationField)
1583 if relField == nil {
1584 return errors.New("only RelationField is supported at the moment, got " + field.Type())
1585 }
1586
1587 for _, refRecord := range refRecords {
1588 ids := refRecord.GetStringSlice(relField.Name)
1589
1590 // unset the record id
1591 for i := len(ids) - 1; i >= 0; i-- {
1592 if ids[i] == mainRecord.Id {
1593 ids = append(ids[:i], ids[i+1:]...)
1594 break
1595 }
1596 }
1597
1598 // cascade delete the reference
1599 // (only if there are no other active references in case of multiple select)
1600 if relField.CascadeDelete && len(ids) == 0 {
1601 if err := app.Delete(refRecord); err != nil {
1602 return err
1603 }
1604 // no further actions are needed (the reference is deleted)
1605 continue
1606 }
1607
1608 if relField.Required && len(ids) == 0 {
1609 return fmt.Errorf("the record cannot be deleted because it is part of a required reference in record %s (%s collection)", refRecord.Id, refRecord.Collection().Name)
1610 }
1611
1612 // save the reference changes
1613 // (without validation because it is possible that another relation field to have a reference to a previous deleted record)
1614 refRecord.Set(relField.Name, ids)
1615 if err := app.SaveNoValidate(refRecord); err != nil {
1616 return err
1617 }
1618 }
1619
1620 return nil
1621}

Callers 1

cascadeRecordDeleteFunction · 0.85

Calls 6

GetStringSliceMethod · 0.80
CollectionMethod · 0.80
TypeMethod · 0.65
DeleteMethod · 0.65
SetMethod · 0.65
SaveNoValidateMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…