Database
public class Database
Predix Sync on-device non-relational database storage
-
Closes all open databases, and releases all resources
Declaration
Swift
public static func prepareForShutdown() -
Initializes a Database structure for interacting with a Predix Sync on-device database, using the provided database name.
Databases consist of documents, which are name/value dictionaries of JSON-compatible data.
Documents may also be related to binary attachments such as images, ZIP files, videos, etc.
Data may be indexed, and then queried.
Multiple calls to
openwith equivalent configurations will return the same Database object instance.Important
On tvOS persistent storage is limited. On tvOS the default location for databases will be the cache directory, which may be wiped when the application is not running. It is advised if using PredixSDK databases on tvOS, to always replicate data to PredixSync.Example
let config = Database.OpenDatabaseConfiguration.default do { let database = try Database.open(with: config, create: true) if let database = database { // ... the database is now open, and ready for interactions } } catch let error { // ... handle error... }Throws
Throws if the if the configuration is invalid, for example an illegal database name is provided, or the file location could not be written to.Declaration
Swift
public static func open(with configuration: OpenDatabaseConfiguration = OpenDatabaseConfiguration.default, create: Bool = false) throws -> Database?Parameters
configurationConfiguration of database.
createIf true and the database does not exist on the file system it will be created. Defaults to false.
Return Value
Returns a reference to a Database object with the indicated configuration, or nil if the provided database name does not exist on the device and the create parameter is false.
-
Returns an open database object for the matching configuration, if a database matching the configuration has already been opened.
If no database matching the configuration is open, then the
Database.open(with: )must first be called to open the database.Declaration
Swift
public static func openedWith(_ configuration: Configuration) -> Database? -
Deletes the database with the given configuration, removing all associated files from the file system. If the specified database is open, it will first be closed before being deleted. Does nothing if no database with the provided name exists.
Declaration
Swift
public static func delete(_ configuration: Configuration)Parameters
configurationConfiguration of database to delete.
-
Returns an array of the names of databases already created on the current device under the provided file location
Declaration
Swift
public static func allDatabaseNames(underLocation: URL) -> [String]Parameters
underLocationFile location URL under which to search for existing databases
-
Returns the total number of documents currently stored in the local database.
If the number of documents is greater than Int.max, will return Int.max
Declaration
Swift
public var totalDocumentCount: Int -
Closes the database, stopping all replications, and releasing all resources used by the Database instance.
Once closed, the
Databaseinstance is no longer valid; no methods should be called on the Database object.Declaration
Swift
public func close() -
Closes, then deletes the database, removing all associated files from the file system.
Once deleted, the
Databaseinstance is no longer valid; no methods should be called on the Database object.Declaration
Swift
public func delete() -
The configuration for this Database
Declaration
Swift
public var configuration: Configuration -
Delegate to monitor database change events
Declaration
Swift
public weak var databaseChangeDelegate: DatabaseChangeDelegate? -
Delegate to monitor replication status events
Declaration
Swift
public weak var replicationStatusDelegate: ReplicationStatusDelegate? -
Delegate to exclude documents from being sent to the server during replication
Declaration
Swift
public weak var replicationFilterDelegate: ReplicationFilterDelegate?
-
Result enumeration for Database update operations
See moreDeclaration
Swift
public enum UpdateResult<T> -
Declaration
Swift
open class Configuration -
Database configuration class used when opening a database
See moreDeclaration
Swift
open class OpenDatabaseConfiguration: Configuration -
Structure defining a Replication Configuration, to establish data syncing between an on-device database and a Predix Sync offline database service instance.
See moreDeclaration
Swift
public struct ReplicationConfiguration: ReplicationDetails
-
Indexer implemenation to define a Database index used to query the database
Example:
See morelet index = Database.Index(name: "myView", version: "1.0", map: { (document, addRow) in if let type = document["type"] { addRow(type, nil) } }) let config = Database.OpenDatabaseConfiguration(indexes: [index])Declaration
Swift
public struct Index: Indexer -
Used to add and remove observers to queries.
See Also:
observeQuery(on: with: changeHandler:)removeObserver(_ observer:)
Declaration
Swift
public typealias QueryObserver = NSObjectProtocol -
Runs a query on a defined index
Example:
var parameters = QueryByKeyList() parameters.keyList = ["a", "b", "c"] myDatabase.runQuery(on: "MyView", with: parameters) { queryResult in // do something with query results }See Also:
QueryResultsQueryByKeyList
Declaration
Swift
public func runQuery(on index: String, with parameters: QueryParameters, completionHandler: @escaping (_ queryResult: QueryResultEnumerator) -> Void)Parameters
indexName of index. See
IndexDefinitionparametersQueryParameters-based protocol implementer defining the query to run.completionHandlerCompletion handler which will be called when the query has completed.
queryResultResults of the query
-
Runs and observes a query on a defined index. The provided changeHandler closure will be called after the query is first run, then anytime the query results change.
When a query is observed, the index will continued to be monitored, and if any changes to the database occur that result in changes to the query results, the associated changeHandler will be called.
Changes will continue to be monitored until the returned QueryObserver is passed to the
removeQueryObservermethod.Example:
var parameters = QueryByKeyList() parameters.keyList = ["a", "b", "c"] let observer = myDatabase.observeQuery(on: "MyView", with: parameters) { queryResult in // do something with query results }See Also:
removeObserver
Declaration
Swift
public func observeQuery(on index: String, with parameters: QueryParameters, changeHandler: @escaping (_ queryResult: QueryResultEnumerator) -> Void) -> QueryObserver?Parameters
indexName of index. See
IndexparametersQueryParameters-based protocol implementer defining the query to run.changeHandlerChange handler which will be called when the query results have been updated.
queryResultResults of the query
-
Stops observing the query established with a
observeQuery(on: with: changeHandler:)call.See Also:
observeQuery(on: with: changeHandler:)
Declaration
Swift
public func removeObserver(_ observer: QueryObserver)Parameters
observerQueryObserver returned from
observeQuery(on: with: changeHandler:)
-
Starts data replication for this Database between the client and server based on the provided
ReplicationConfigurationReplaces (and stops) any previously existing replication for this Database before starting replication based on the provided configuration.
Declaration
Swift
public func startReplication(with configuration: ReplicationConfiguration)Parameters
configurationa
ReplicationConfigurationstructure defining the replication type, location and other properties. -
Stops the replication for this Database. Does nothing if no replication is currently configured for this Database.
Declaration
Swift
public func stopReplication() -
Configuration details for the active replication, or nil if there is no active replication.
Will be nil if a non-repeating replication has completed, or failed, or if a repeating replication has been stopped.
Declaration
Swift
public var replicationDetails: ReplicationDetails? -
Downloads attachments for documents that were sync’d without their attachments (
downloadsAttachmentswas false)If called on a document that already has it’s attachment data, the attachment will not be redownloaded.
Declaration
Swift
public func downloadAttachments(for document: Document, with configuration: ReplicationSource, completionHandler: @escaping (_ result: UpdateResult<Document>) -> Void)Parameters
documentThe Document to for which to download attachments
configurationThe ReplicationSource from which to retrieve the attachments.
completionHandlerclosure that will be called when all the attachments for the provided Document have been retrieved.
resultUpdateResultof the operation containing the updated Document, with it’s attachments if successful, or if unsuccessful an Error describing the failure.
-
Retrieve a document from the database.
Example:
myDatabase.fetchDocument("document1") { document in print("Document retrieved") }Declaration
Swift
public func fetchDocument(_ withId: String, completionHandler: @escaping (_ document: Document?) -> Void)Parameters
withIdId of the document to retrieve
completionHandlercalled on the database’s callback queue when the document has been retrieved
documentthe retrieved document, or nil if no document existed with the given Id
-
Retrieves multiple documents from the database.
Example:
let idList = ["document1", "document2", "document3"] myDatabase.fetchDocuments(idList) { documents in print("Document retrieved \(documents.count) documents") }Declaration
Swift
public func fetchDocuments(_ withIds: [String], completionHandler: @escaping (_ documents: [String: Document]) -> Void)Parameters
withIdsAn array of document Ids to retrieve
completionHandlercalled when the documents have been retrieved
documentsA dictionary, keyed by document id of retrieved documents
-
Adds a document to the database.
If a document with the same Id already exists in the database the operation will fail.
Example:
let myDocument = Document() myDocument["someKey"] = "someValue" myDatabase.add(myDocument) { result in switch result { case .success(let addedDocument): print("added document with id: \(addedDocument.id)") case .failed(let error): print("encountered error adding document: \(error)") } }Declaration
Swift
public func add(_ document: Document, completionHandler: @escaping (_ result: UpdateResult<Document>) -> Void)Parameters
documentThe
Documentto addcompletionHandlercalled when the operation has completed
resultUpdateResultof the operation containing the added Document if successful, or if unsuccessful an Error describing the failure -
Updates an existing document in the database.
If there is no document with the same Id in the database, the operation fails.
Example:
myDocument["someKey"] = "someNewValue" myDatabase.update(myDocument) { result in switch result { case .success(let updatedDocument): print("updated document with id: \(updatedDocument.id)") case .failed(let error): print("encountered error updating the document: \(error)") } }Declaration
Swift
public func update(_ document: Document, completionHandler: @escaping (_ result: UpdateResult<Document>) -> Void)Parameters
documentThe
Documentto updatecompletionHandlercalled when the operation has completed
resultUpdateResultof the operation containing the updated Document if successful, or if unsuccessful an Error describing the failure. -
Saves a document to the database.
If a document with the same Id already exists in the database, the existing document will be replaced. If no previous document exists, the document will be created.
Example:
let myDocument = Document() myDocument["someKey"] = "someValue" myDatabase.save(myDocument) { result in switch result { case .success(let savedDocument): print("saved document with id: \(savedDocument)") case .failed(let error): print("encountered error saving document: \(error)") } }Declaration
Swift
public func save(_ document: Document, completionHandler: @escaping (_ result: UpdateResult<Document>) -> Void)Parameters
documentThe
Documentto savecompletionHandlercalled when the operation has completed
resultUpdateResultof the operation containing the saved Document if successful, or if unsuccessful an Error describing the failure -
Deletes a document in the database with the given Id.
Does nothing if no document with the provided Id exists.
Example:
myDatabase.delete(documentWithId: "document1") { result in switch result { case .success(let documentId): print("deleted document with id: \(documentId)") case .failed(let error): print("encountered error deleting the document: \(error)") } }Declaration
Swift
public func delete(documentWithId: String, completionHandler: @escaping (UpdateResult<String>) -> Void)Parameters
documentWithIdId of the document to delete
completionHandlercalled when the operation has completed
resultUpdateResultof the operation containing the id of the deleted document if successful, or if unsuccessful an Error describing the failure.
View on GitHub
Database Class Reference