added iOS source code
[wl-app.git] / iOS / Pods / RealmSwift / RealmSwift / Migration.swift
1 ////////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright 2014 Realm Inc.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 ////////////////////////////////////////////////////////////////////////////
18
19 import Foundation
20 import Realm
21 import Realm.Private
22
23 /**
24  The type of a migration block used to migrate a Realm.
25
26  - parameter migration:  A `Migration` object used to perform the migration. The migration object allows you to
27                          enumerate and alter any existing objects which require migration.
28
29  - parameter oldSchemaVersion: The schema version of the Realm being migrated.
30  */
31 public typealias MigrationBlock = (_ migration: Migration, _ oldSchemaVersion: UInt64) -> Void
32
33 /// An object class used during migrations.
34 public typealias MigrationObject = DynamicObject
35
36 /**
37  A block type which provides both the old and new versions of an object in the Realm. Object
38  properties can only be accessed using subscripting.
39
40  - parameter oldObject: The object from the original Realm (read-only).
41  - parameter newObject: The object from the migrated Realm (read-write).
42  */
43 public typealias MigrationObjectEnumerateBlock = (_ oldObject: MigrationObject?, _ newObject: MigrationObject?) -> Void
44
45 /**
46  Returns the schema version for a Realm at a given local URL.
47
48  - parameter fileURL:       Local URL to a Realm file.
49  - parameter encryptionKey: 64-byte key used to encrypt the file, or `nil` if it is unencrypted.
50
51  - throws: An `NSError` that describes the problem.
52  */
53 public func schemaVersionAtURL(_ fileURL: URL, encryptionKey: Data? = nil) throws -> UInt64 {
54     var error: NSError?
55     let version = RLMRealm.__schemaVersion(at: fileURL, encryptionKey: encryptionKey, error: &error)
56     guard version != RLMNotVersioned else {
57         throw error!
58     }
59     return version
60 }
61
62 extension Realm {
63     /**
64      Performs the given Realm configuration's migration block on a Realm at the given path.
65
66      This method is called automatically when opening a Realm for the first time and does not need to be called
67      explicitly. You can choose to call this method to control exactly when and how migrations are performed.
68
69      - parameter configuration: The Realm configuration used to open and migrate the Realm.
70      */
71     public static func performMigration(for configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration) throws {
72         try RLMRealm.performMigration(for: configuration.rlmConfiguration)
73     }
74 }
75
76 /**
77  `Migration` instances encapsulate information intended to facilitate a schema migration.
78
79  A `Migration` instance is passed into a user-defined `MigrationBlock` block when updating the version of a Realm. This
80  instance provides access to the old and new database schemas, the objects in the Realm, and provides functionality for
81  modifying the Realm during the migration.
82  */
83 public struct Migration {
84
85     // MARK: Properties
86
87     /// The old schema, describing the Realm before applying a migration.
88     public var oldSchema: Schema { return Schema(rlmMigration.oldSchema) }
89
90     /// The new schema, describing the Realm after applying a migration.
91     public var newSchema: Schema { return Schema(rlmMigration.newSchema) }
92
93     internal var rlmMigration: RLMMigration
94
95     // MARK: Altering Objects During a Migration
96
97     /**
98      Enumerates all the objects of a given type in this Realm, providing both the old and new versions of each object.
99      Properties on an object can be accessed using subscripting.
100
101      - parameter objectClassName: The name of the `Object` class to enumerate.
102      - parameter block:           The block providing both the old and new versions of an object in this Realm.
103      */
104     public func enumerateObjects(ofType typeName: String, _ block: MigrationObjectEnumerateBlock) {
105         rlmMigration.enumerateObjects(typeName) { oldObject, newObject in
106             block(unsafeBitCast(oldObject, to: MigrationObject.self),
107                   unsafeBitCast(newObject, to: MigrationObject.self))
108         }
109     }
110
111     /**
112      Creates and returns an `Object` of type `className` in the Realm being migrated.
113
114      The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
115      dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
116      managed property. An exception will be thrown if any required properties are not present and those properties were
117      not defined with default values.
118
119      When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
120      the properties defined in the model.
121
122      - parameter className: The name of the `Object` class to create.
123      - parameter value:     The value used to populate the created object.
124
125      - returns: The newly created object.
126      */
127     @discardableResult
128     public func create(_ typeName: String, value: Any = [:]) -> MigrationObject {
129         return unsafeBitCast(rlmMigration.createObject(typeName, withValue: value), to: MigrationObject.self)
130     }
131
132     /**
133      Deletes an object from a Realm during a migration.
134
135      It is permitted to call this method from within the block passed to `enumerate(_:block:)`.
136
137      - parameter object: An object to be deleted from the Realm being migrated.
138      */
139     public func delete(_ object: MigrationObject) {
140         rlmMigration.delete(object.unsafeCastToRLMObject())
141     }
142
143     /**
144      Deletes the data for the class with the given name.
145
146      All objects of the given class will be deleted. If the `Object` subclass no longer exists in your program, any
147      remaining metadata for the class will be removed from the Realm file.
148
149      - parameter objectClassName: The name of the `Object` class to delete.
150
151      - returns: A Boolean value indicating whether there was any data to delete.
152      */
153     @discardableResult
154     public func deleteData(forType typeName: String) -> Bool {
155         return rlmMigration.deleteData(forClassName: typeName)
156     }
157
158     /**
159      Renames a property of the given class from `oldName` to `newName`.
160
161      - parameter className:  The name of the class whose property should be renamed. This class must be present
162                              in both the old and new Realm schemas.
163      - parameter oldName:    The old name for the property to be renamed. There must not be a property with this name in
164                              the class as defined by the new Realm schema.
165      - parameter newName:    The new name for the property to be renamed. There must not be a property with this name in
166                              the class as defined by the old Realm schema.
167      */
168     public func renameProperty(onType typeName: String, from oldName: String, to newName: String) {
169         rlmMigration.renameProperty(forClass: typeName, oldName: oldName, newName: newName)
170     }
171
172     internal init(_ rlmMigration: RLMMigration) {
173         self.rlmMigration = rlmMigration
174     }
175 }
176
177
178 // MARK: Private Helpers
179
180 internal func accessorMigrationBlock(_ migrationBlock: @escaping MigrationBlock) -> RLMMigrationBlock {
181     return { migration, oldVersion in
182         // set all accessor classes to MigrationObject
183         for objectSchema in migration.oldSchema.objectSchema {
184             objectSchema.accessorClass = MigrationObject.self
185             // isSwiftClass is always `false` for object schema generated
186             // from the table, but we need to pretend it's from a swift class
187             // (even if it isn't) for the accessors to be initialized correctly.
188             objectSchema.isSwiftClass = true
189         }
190         for objectSchema in migration.newSchema.objectSchema {
191             objectSchema.accessorClass = MigrationObject.self
192         }
193
194         // run migration
195         migrationBlock(Migration(migration), oldVersion)
196     }
197 }