Class Reference
IRIS for UNIX 2019.1
InterSystems: The power behind what matters   
Documentation  Search
  [%SYS] >  [%DocDB] >  [Database]
Private  Storage   

persistent class %DocDB.Database extends %Library.Persistent

%DocDB.Database implements the DocDB ObjectScript User Database API.


DocDB ObjectScript User Database API

This class implements the public DocDB ObjectScript User Database API.

A Database is a set of Documents, implemented by a objects persistent class that extends %DocDB.Document.

Databases are explicitly created by calling %CreateDatabase. A previously created Database can be retrieved by calling the %GetDatabase.

A Document is inserted into a Database by executing %SaveDocument, passing in the document value as a string containing a valid serialized document, or an instance of the type class. The default type class is %Library.DynamicAbstractObject and the default serialization is JSON. An existing Document can be replaced by passing in the documentID. If a documentID is provided and that document does not exist then an exception is thrown.

%SaveDocument() returns an oref referencing the newly created document. If an error is encountered by %SaveDocument() an exception is thrown.

Other methods to access documents are %GetDocument and %DeleteDocument. There are also ByKey versions of %GetDocument, %DeleteDocument and %SaveDocument.

Database Functions to be implemented: FindDocuments Return a set of all Documents from the Database that match the provided selection criteria. The form of the selection criteria is a list of simple predicates applied to defined properties joined with AND (we may need OR but IN is probably sufficient). The set of predicates supported initially includes Equal, GT, LT, GTE, LTE, and IN. Accepts Database Name, a definition of the structure of the returned documents, and the selection criteria. QueryDatabase(sql-like query spec) Add a new function to allow for SQL-like SELECT query.


Parameters Properties Methods Queries Indices ForeignKeys Triggers
1 5 39 1


ClassName DocumentType Name Resource

%AddToSaveSet %AddToSyncSet %BMEBuilt %CheckConstraints
%CheckConstraintsForExtent %ClassIsLatestVersion %ClassName %Clear
%ComposeOid %ConstructClone %CreateDatabase %CreateProperty
%Delete %DeleteDocument %DeleteDocumentByKey %DeleteExtent
%DeleteId %DispatchClassMethod %DispatchGetModified %DispatchGetProperty
%DispatchMethod %DispatchSetModified %DispatchSetMultidimProperty %DispatchSetProperty
%DropAllDatabases %DropDatabase %DropProperty %ExecuteQuery
%Exists %ExistsId %Extends %FindDocuments
%FromJSON %GUID %GUIDSet %GetAllDatabases
%GetDatabase %GetDatabaseDefinition %GetDocument %GetDocumentByKey
%GetLock %GetParameter %GetPropertyDefinition %GetSwizzleObject
%Id %InsertBatch %IsA %IsModified
%IsNull %KillExtent %KillExtentData %LoadFromMemory
%LockExtent %LockId %New %NormalizeObject
%ObjectIsNull %ObjectModified %Oid %OnBeforeAddToSync
%OnDetermineClass %Open %OpenId %OriginalNamespace
%PackageName %PhysicalAddress %PurgeIndices %Reload
%RemoveFromSaveSet %ResolveConcurrencyConflict %RollBack %Save
%SaveDirect %SaveDocument %SaveDocumentByKey %SaveIndices
%SerializeObject %SetModified %Size %SortBegin
%SortEnd %SyncObjectIn %SyncTransport %ToJSON
%UnlockExtent %UnlockId %ValidateIndices %ValidateObject


• parameter USEEXTENTSET = 1;

If a persistent class uses %Storage.Persistent then the USEEXTENTSET parameter is used to specify the global naming strategy used by the default storage class (%Storage.Persistent). If TRUE, then global names are generated for each index that is not already allocated a LOCATION in the active storage definition.

If the storage definition specifies EXTENTLOCATION then that value is used as the base reference for all globals assigned to indices that do not have an explicit LOCATION assigned.

The global name generator for USEEXTENTSET = TRUE honors the package prefix defined in the Package Definition. If none is defined then the package prefix is generated using a based-62 encoded integer produced from CRC32 of the package name. The specific class identifier is generated from the unqualified class name using the same hash (class->crc32->base62) to form EXTENTLOCATION. Specific index suffixes are produced using a generated offset that is local to the first persistent class with an enumerated extent in which the index appears (either defined or inherited).

There are several factors that influence the generation of EXTENTLOCATION:

  1. If the EXTENTLOCATION keyword is defined then its value is used,
  2. If the DEFAULTGLOBAL class parameter is defined then its value is used,
  3. otherwise, the value is generated as two dot delimited segments. The first segment is either the defined package prefix retrieved from the package definition global or, if none is defined, a hash of the package name. The second segment is generated by a hash of the unqualified class name. The hash used is a base 62 encoded CRC32 of the value. For example, Sample.Person produces ^EW3K.wPC9 if no package prefix is defined.
The EXTENTLOCATION value is used as the base for specific globals allocated to indices. Each index is assigned an offset that is incremented from 1 by 1, offset = 1 is reserved for the IDKEY index.

EXTENTLOCATION is specific to each class. When a persistent class extends another persistent class, forming a subextent, then the subclass's EXTENTLOCATION is specific to that subclass. The index location for any inherited index is already defined specifically in the super class so the subclass's EXTENTLOCATION will only be used as the base for any index that originates in the subclass. For example, Sample.Employee extends Sample.Person. The EXTENTLOCATION generated for Sample.Person is ^EW3K.wPC9 and the EXTENTLOCATION for Sample.Employee is ^EW3K.D1Ex. Since Sample.Employee inherits several indices from Sample.Person, the global name assigned to each of those indices is already defined and inherited by Sample.Employee. However, any index defined in Sample.Employee and not inherited from Sample.Person will be assigned a global name based on Sample.Employee's EXTENTLOCATION, not on Sample.Person's EXTENTLOCATION. In other words, the EXTENTLOCATION storage keyword is not inherited.

The following tables show the indices and locations for Sample.Person and Sample.Employee. Notice the last index in the Sample.Employee table:
Class = Sample.Person
Class = Sample.Employee extends Sample.Person

Any generated global index locations and EXTENTLOCATION are updated back into the active storage definition after the class is compiled.

If USEEXTENTSET is FALSE, then global names are generated using the package-hash.class-hashSuffix strategy. For example, ^Sample.PersonD and ^Sample.PersonI("SSNKey") are globals used by Sample.Person and specific index structures are all stored in ^Sample.PersonI with the index name used as the first subscript.


• property ClassName as %String(MAXLEN=220);
The name of the class that implements the Database.
• property DocumentType as %String(MAXLEN="");
DocumentType is the type class of the %Doc property or one of (JSON, XML). JSON is the default DocumentType.
• property Name as %String(MAXLEN="");
The name of the database. This value must be a valid class name but it does not need to be package-qualified. If no package qualifier is present then a system default package, 'ISC.DM', will be used.
• property Resource as %String(MAXLEN="");
The Resource required to access this Database.
• property SqlNameQualified as %String(MAXLEN=220);
This is the SQL Schema.Table name as constructed during class compile. If the class is edited directly and later recompiled then this value could be stale. Perhaps add a projection to the %DocDB.Document class to verify this.


• method %Clear(databaseName) as %DocDB.Database
%Clear() - Remove all documents from the current Database. The current Database oref is returned to allow chaining.
• classmethod %CreateDatabase(databaseName As %String(MAXLEN=220)="", documentType As %String = "%Library.DynamicAbstractObject", resource As %String = "") as %DocDB.Database
Create a new database. If a database with the name databaseName already exists then an exception is thrown. The return value is an OREF referencing the newly created Database instance in memory.
• method %CreateProperty(propertyName As %String(MAXLEN=220), propertyType As %String(MAXLEN=220), propertyExpression As %String(MAXLEN="")="", unique=0)
CreateProperty Add a new property to the Database class. Accepts Database Name, Property Name, Property Type, an optional Expression used to derive the property value and an optional UNIQUE indicator. If UNIQUE is specified, then an index to support uniqueness is automatically created if one does not already exist. All properties created through this function will be implicitly indexed.
• method %DeleteDocument(documentID As %Integer)
DeleteDocument Remove a document from the currently visible extent of the Database class. Accepts Database Name, Document ID. Returns the deleted Document.
• method %DeleteDocumentByKey(keyName As %String(MAXLEN=220), keyValue As %String(MAXLEN=""))
DeleteDocumentByKey Remove a document identified by KeyPropertyName = KeyValue from the currently visible extent of the Database class. Accepts Database Name, KeyPropertyName and KeyValue. Returns the deleted Document.
• classmethod %DropAllDatabases() as %Library.DynamicArray

WARNING!! This is a destructive call.

Drop all Databases defined in the current namespace. User data is deleted.

• classmethod %DropDatabase(databaseName As %Library.String(MAXLEN=220)) as %Library.Boolean

WARNING!! This is a destructive call.

Drop the Database and remove its extent. User data is deleted.

• method %DropProperty(propertyName As %String(MAXLEN=220)) as %DocDB.Database
DropProperty Remove a property from the Database class. Accepts a Property Name. The current Database oref is returned to allow chaining.
• classmethod %ExecuteQuery(ByRef sql As %RawString = "", ByRef parameter... As %RawString) as %SQL.StatementResult
Accepts an SQL statement and a variable number of parameter values. Returns a %SQL.StatementResult.
• method %FindDocuments(restrictionRequest As %DynamicAbstractObject = "", projectionRequest As %DynamicAbstractObject = "", optionsRequest As %DynamicObject = "") as %Library.DynamicAbstractObject

Retrieve documents that match the restrictionRequest restriction. The set of properties included in the result is defined by projectionRequest. Find options can be specified in the optionsRequest argument. The format of these arguments is either a %DynamicAbstractObject oref or a string containing JSON.

restrictionRequest - This can be either a predicate or an array of predicates. A predicate is an array with three elements, the first is the property to be restricted, the second is the value the property is compared to and an optional third element is the comparison operator. The comparison operator defaults to "=". The list of supported comparison operators includes =, !=, <, >, <=, >=, <>, %STARTSWITH, NULL, and NOT NULL. When multiple predicates are specified they are combined using AND. Properties included in the restriction must be defined in the Database.

projectionRequest - an array of properties to select from the Database. If not specified then the projection will include %DocumentId, %LastModified and %Doc. The properties included in the projectionRequest must be explicitly defined in the Database.

optionsRequest - is an object containing the requested options. At this time, the only option supported is limit. If options.limit is specified then it is the maximum number of matching documents retrieved from the database.

The return value is a %Library.DynamicArray whose elements correspond to objects as defined by projectionRequest.

	SAMPLES>set result = db.%FindDocuments(["Name","N","%STARTSWITH"],["Name"],{"limit":5})             

	SAMPLES>w result.%ToJSON()                                                                          
	{"sqlcode":100,"message":null,"content":[{"Name":"Nebraska"},{"Name":"Nevada"},{"Name":"New Hampshire"},{"Name":"New Jersey"},{"Name":"New Mexico"}]}

• method %FromJSON(jsonValue As %RawString) as %DocDB.Database

%FromJSON() - accepts a stream, a string containing JSON, a stream oref or a string containing a file URI. The contents of jsonValue are then inserted into the current database. This method return an oref referencing the database to support stringing method calls.

If a file URI is passed then a file stream is instantiated and the translation table set to UTF-8. If the file is not encoded as UTF-8 then the user must instantiate a stream object before calling $fromJSON() and set the translation table to the appropriate value.

• classmethod %GetAllDatabases() as %Library.DynamicArray
Return an array (%Library.DynamicArray) containing the names of all of the Databases defined in the current namespace.
• classmethod %GetDatabase(databaseName) as %DocDB.Database
Retrieve the Database whose name is databaseName. If a Database identified by that name does not exist then an exception is thrown. The return value is an oref referencing the Database object in memory.
• method %GetDatabaseDefinition() as %Library.DynamicAbstractObject
• method %GetDocument(documentID As %Integer = "") as %Library.DynamicAbstractObject
GetDocument Return the Document from the Database with the specified ID. If no document with that ID is found then an exception is thrown.
• method %GetDocumentByKey(keyName As %String(MAXLEN=220), keyValue As %String(MAXLEN=""))
GetDocumentByKey Return the Document from the Database that matches the key value provided. Key Property Name, Key Property Value. Returns Document.
• method %GetPropertyDefinition(propertyName As %String(MAXLEN=220)) as %Library.DynamicObject
• method %SaveDocument(request As %RawString, documentID As %Integer = "") as %Library.DynamicAbstractObject

SaveDocument() accepts a document value and an optional documentID. The document value is either an instance of the DocumentType class or a serialized value in the format expected by the DocumentType class. The default serial format is JSON. If documentID is specified then the document identified by that value is replaced by the provided document value. If a document with that ID does not exist then an exception is thrown. If no documentID then the provided document value is inserted into the Database. This method returns the instance of the Database class that was inserted or replaced.

USER>set car = cars.%SaveDocument({"make":"Ford","model":"Flatbed","year":"1938","location":{"city":"Winslow","state":"Arizona"})

This method throws an exception if an error is encountered.

• method %SaveDocumentByKey(request As %RawString, keyName As %String(MAXLEN=220), keyValue As %String(MAXLEN="")) as %Library.DynamicAbstractObject


• method %Size() as %Integer
Return the size of the database where size is the number of documents.
• method %ToJSON(destination As %Stream.Object) as %RawString
Serialize the database and its content as JSON. If destination is not passed then the output is either sent to the current device or returned as a string.

destination is optional. There are a number of possibilities:
(1) Parameter destination is not defined and the method is called via 'DO'. In this case the JSON string is written to the current output device.
(2) Parameter destination is not defined and the method is called as an expression. In this case the JSON string becomes the value of the expression.
(3) Parameter destination is defined. If it is %Stream object then the JSON string will be written to the stream. If destination is not an object and is not null then it is presumed to be a fully qualified file specification. In that case, a %Stream.FileCharacter stream is created, linked to that file and the JSON string is written to that stream. On completion, this stream is saved. The full path to the file must be defined. If destination is an object but is not an instance of %Stream.Object then an exception will be thrown.


•index (xN on Name) [Unique];

Copyright (c) 2019 by InterSystems Corporation. Cambridge, Massachusetts, U.S.A. All rights reserved. Confidential property of InterSystems Corporation.