ImportCollections imports the provided collections data in a single transaction. For existing matching collections, the imported data is unmarshaled on top of the existing model. NB! If deleteMissing is true, ALL NON-SYSTEM COLLECTIONS AND SCHEMA FIELDS, that are not present in the imported config
(toImport []map[string]any, deleteMissing bool)
| 34 | // that are not present in the imported configuration, WILL BE DELETED |
| 35 | // (this includes their related records data). |
| 36 | func (app *BaseApp) ImportCollections(toImport []map[string]any, deleteMissing bool) error { |
| 37 | if len(toImport) == 0 { |
| 38 | // prevent accidentally deleting all collections |
| 39 | return errors.New("no collections to import") |
| 40 | } |
| 41 | |
| 42 | importedCollections := make([]*Collection, len(toImport)) |
| 43 | mappedImported := make(map[string]*Collection, len(toImport)) |
| 44 | |
| 45 | // normalize imported collections data to ensure that all |
| 46 | // collection fields are present and properly initialized |
| 47 | for i, data := range toImport { |
| 48 | var imported *Collection |
| 49 | |
| 50 | identifier := cast.ToString(data["id"]) |
| 51 | if identifier == "" { |
| 52 | identifier = cast.ToString(data["name"]) |
| 53 | } |
| 54 | |
| 55 | existing, err := app.FindCollectionByNameOrId(identifier) |
| 56 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 57 | return err |
| 58 | } |
| 59 | |
| 60 | if existing != nil { |
| 61 | // refetch for deep copy |
| 62 | imported, err = app.FindCollectionByNameOrId(existing.Id) |
| 63 | if err != nil { |
| 64 | return err |
| 65 | } |
| 66 | |
| 67 | // ensure that the fields will be cleared |
| 68 | if data["fields"] == nil && deleteMissing { |
| 69 | data["fields"] = []map[string]any{} |
| 70 | } |
| 71 | |
| 72 | rawData, err := json.Marshal(data) |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | |
| 77 | // load the imported data |
| 78 | err = json.Unmarshal(rawData, imported) |
| 79 | if err != nil { |
| 80 | return err |
| 81 | } |
| 82 | |
| 83 | // extend with the existing fields if necessary |
| 84 | for _, f := range existing.Fields { |
| 85 | if !f.GetSystem() && deleteMissing { |
| 86 | continue |
| 87 | } |
| 88 | if imported.Fields.GetById(f.GetId()) == nil { |
| 89 | // replace with the existing id to prevent accidental column deletion |
| 90 | // since otherwise the imported field will be treated as a new one |
| 91 | found := imported.Fields.GetByName(f.GetName()) |
| 92 | if found != nil && found.Type() == f.Type() { |
| 93 | found.SetId(f.GetId()) |
no test coverage detected