@itwin/core-backend 4.0.0-dev.85 → 4.0.0-dev.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/lib/cjs/BackendHubAccess.d.ts +3 -1
  2. package/lib/cjs/BackendHubAccess.d.ts.map +1 -1
  3. package/lib/cjs/BackendHubAccess.js.map +1 -1
  4. package/lib/cjs/BackendLoggerCategory.js.map +1 -1
  5. package/lib/cjs/BisCoreSchema.js.map +1 -1
  6. package/lib/cjs/BriefcaseManager.js.map +1 -1
  7. package/lib/cjs/Category.js.map +1 -1
  8. package/lib/cjs/ChangeSummaryManager.js +2 -2
  9. package/lib/cjs/ChangeSummaryManager.js.map +1 -1
  10. package/lib/cjs/ChangedElementsDb.js.map +1 -1
  11. package/lib/cjs/ChangedElementsManager.js.map +1 -1
  12. package/lib/cjs/ChannelControl.js.map +1 -1
  13. package/lib/cjs/CheckpointManager.js.map +1 -1
  14. package/lib/cjs/ClassRegistry.js +5 -5
  15. package/lib/cjs/ClassRegistry.js.map +1 -1
  16. package/lib/cjs/CloudSqlite.js.map +1 -1
  17. package/lib/cjs/CodeService.js.map +1 -1
  18. package/lib/cjs/CodeSpecs.js.map +1 -1
  19. package/lib/cjs/ConcurrentQuery.js.map +1 -1
  20. package/lib/cjs/CustomViewState3dCreator.js.map +1 -1
  21. package/lib/cjs/DevTools.js.map +1 -1
  22. package/lib/cjs/DisplayStyle.js.map +1 -1
  23. package/lib/cjs/ECDb.js.map +1 -1
  24. package/lib/cjs/ECSchemaXmlContext.js.map +1 -1
  25. package/lib/cjs/ECSqlStatement.js.map +1 -1
  26. package/lib/cjs/Element.js.map +1 -1
  27. package/lib/cjs/ElementAspect.js.map +1 -1
  28. package/lib/cjs/ElementGraphics.js.map +1 -1
  29. package/lib/cjs/ElementTreeWalker.js.map +1 -1
  30. package/lib/cjs/Entity.js.map +1 -1
  31. package/lib/cjs/EntityReferences.js.map +1 -1
  32. package/lib/cjs/ExportGraphics.js.map +1 -1
  33. package/lib/cjs/ExternalSource.js.map +1 -1
  34. package/lib/cjs/GeoCoordConfig.js.map +1 -1
  35. package/lib/cjs/GeometrySummary.js +47 -47
  36. package/lib/cjs/GeometrySummary.js.map +1 -1
  37. package/lib/cjs/HubMock.js.map +1 -1
  38. package/lib/cjs/IModelCloneContext.js.map +1 -1
  39. package/lib/cjs/IModelDb.js.map +1 -1
  40. package/lib/cjs/IModelElementCloneContext.js.map +1 -1
  41. package/lib/cjs/IModelHost.d.ts +4 -4
  42. package/lib/cjs/IModelHost.d.ts.map +1 -1
  43. package/lib/cjs/IModelHost.js +2 -2
  44. package/lib/cjs/IModelHost.js.map +1 -1
  45. package/lib/cjs/IModelJsFs.js.map +1 -1
  46. package/lib/cjs/IpcHost.js.map +1 -1
  47. package/lib/cjs/LineStyle.js.map +1 -1
  48. package/lib/cjs/LocalHub.js +1 -1
  49. package/lib/cjs/LocalHub.js.map +1 -1
  50. package/lib/cjs/LocalhostIpcHost.js.map +1 -1
  51. package/lib/cjs/Material.d.ts.map +1 -1
  52. package/lib/cjs/Material.js +5 -0
  53. package/lib/cjs/Material.js.map +1 -1
  54. package/lib/cjs/Model.js.map +1 -1
  55. package/lib/cjs/NativeAppStorage.js.map +1 -1
  56. package/lib/cjs/NativeHost.js.map +1 -1
  57. package/lib/cjs/NavigationRelationship.js.map +1 -1
  58. package/lib/cjs/PromiseMemoizer.js.map +1 -1
  59. package/lib/cjs/PropertyStore.js.map +1 -1
  60. package/lib/cjs/Relationship.js.map +1 -1
  61. package/lib/cjs/RpcBackend.js.map +1 -1
  62. package/lib/cjs/SQLiteDb.js.map +1 -1
  63. package/lib/cjs/Schema.js.map +1 -1
  64. package/lib/cjs/ServerBasedLocks.js.map +1 -1
  65. package/lib/cjs/SqliteStatement.js.map +1 -1
  66. package/lib/cjs/Texture.js.map +1 -1
  67. package/lib/cjs/TileStorage.js.map +1 -1
  68. package/lib/cjs/TxnManager.js.map +1 -1
  69. package/lib/cjs/ViewDefinition.js.map +1 -1
  70. package/lib/cjs/ViewStateHydrator.js.map +1 -1
  71. package/lib/cjs/assets/IModelChange.02.00.00.ecschema.xml +90 -90
  72. package/lib/cjs/assets/Settings/Schemas/Cloud.Schema.json +67 -67
  73. package/lib/cjs/assets/Settings/Schemas/Gcs.schema.json +31 -31
  74. package/lib/cjs/assets/Settings/Schemas/Workspace.Schema.json +52 -52
  75. package/lib/cjs/assets/Settings/backend.setting.json5 +138 -138
  76. package/lib/cjs/core-backend.js.map +1 -1
  77. package/lib/cjs/domains/FunctionalElements.js.map +1 -1
  78. package/lib/cjs/domains/FunctionalSchema.js.map +1 -1
  79. package/lib/cjs/domains/GenericElements.js.map +1 -1
  80. package/lib/cjs/domains/GenericSchema.js.map +1 -1
  81. package/lib/cjs/rpc/multipart.js.map +1 -1
  82. package/lib/cjs/rpc/tracing.js.map +1 -1
  83. package/lib/cjs/rpc/web/logging.js.map +1 -1
  84. package/lib/cjs/rpc/web/request.js.map +1 -1
  85. package/lib/cjs/rpc/web/response.js.map +1 -1
  86. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js.map +1 -1
  87. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js.map +1 -1
  88. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js.map +1 -1
  89. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js.map +1 -1
  90. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js.map +1 -1
  91. package/lib/cjs/rpc-impl/WipRpcImpl.js.map +1 -1
  92. package/lib/cjs/workspace/Settings.js.map +1 -1
  93. package/lib/cjs/workspace/SettingsSchemas.js.map +1 -1
  94. package/lib/cjs/workspace/Workspace.js.map +1 -1
  95. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"Relationship.js","sourceRoot":"","sources":["../../src/Relationship.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAAiE;AACjE,oDAAuH;AAEvH,qC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AAC,IAAoB,EAAE,EAAE;gBAC3J,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC;gBAClC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC;gBAClC,OAAO,uBAAQ,CAAC,aAAa,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAO,CAAC,CAAC,CAAC,SAAS,CAAC;YACjF,CAAC,CAAC,CAAC;SACJ;QACD,IAAI,SAAS,KAAK,KAAK,EAAE;YACvB,KAAK,CAAC,aAAa,GAAI,KAAa,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;SAClE;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;OAKG;IACI,WAAW,CAAyB,eAAuB,EAAE,QAAsC;QACxG,OAAO,IAAI,CAAC,OAAO,CAAC,eAAe,CAAI,IAAI,CAAC,gBAAgB,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC3F,CAAC;IAED;;;;;;OAMG;IACI,cAAc,CAAyB,gBAAwB,EAAE,QAAsC;QAC5G,MAAM,iBAAiB,GAAG,IAAI,CAAC,mBAAmB,CAAoB,gBAAgB,EAAE,QAAQ,CAAC,CAAC;QAClG,OAAO,SAAS,KAAK,iBAAiB,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,CAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1G,CAAC;CACF;AAvGD,sCAuGC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Relationships\r\n */\r\n\r\nimport { DbResult, Id64, Id64String } from \"@itwin/core-bentley\";\r\nimport { EntityReferenceSet, IModelError, IModelStatus, RelationshipProps, SourceAndTarget } from \"@itwin/core-common\";\r\nimport { ECSqlStatement } from \"./ECSqlStatement\";\r\nimport { Entity } from \"./Entity\";\r\nimport { IModelDb } from \"./IModelDb\";\r\n\r\nexport type { SourceAndTarget, RelationshipProps } from \"@itwin/core-common\"; // for backwards compatibility\r\n\r\n/** Base class for all link table ECRelationships\r\n * @public\r\n */\r\nexport class Relationship extends Entity {\r\n /** @internal */\r\n public static override get className(): string { return \"Relationship\"; }\r\n public readonly sourceId: Id64String;\r\n public readonly targetId: Id64String;\r\n\r\n /** @internal */\r\n constructor(props: RelationshipProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.sourceId = Id64.fromJSON(props.sourceId);\r\n this.targetId = Id64.fromJSON(props.targetId);\r\n }\r\n\r\n /** @internal */\r\n public override toJSON(): RelationshipProps {\r\n const val = super.toJSON() as RelationshipProps;\r\n val.sourceId = this.sourceId;\r\n val.targetId = this.targetId;\r\n return val;\r\n }\r\n\r\n /**\r\n * Callback invoked by saveChanges on an ElementDrivesElement relationship when its input has changed or is the output of some upstream relationship whose input has changed.\r\n * This callback is invoked after the input element has been processed by upstream relationships.\r\n * A subclass of ElementDrivesElement can re-implement this static method to take some action. onRootChanged may modify the output element only.\r\n * @param _props The ElementDrivesElement relationship instance.\r\n * @param _iModel The iModel\r\n */\r\n public static onRootChanged(_props: RelationshipProps, _iModel: IModelDb): void { }\r\n\r\n /**\r\n * Callback invoked by saveChanges on an ElementDrivesElement relationship when the relationship instance has been deleted.\r\n * A subclass of ElementDrivesElement can re-implement this static method to take some action.\r\n * @param _props The deleted ElementDrivesElement relationship instance.\r\n * @param _iModel The iModel\r\n */\r\n public static onDeletedDependency(_props: RelationshipProps, _iModel: IModelDb): void { }\r\n\r\n /** Insert this Relationship into the iModel. */\r\n public insert(): Id64String { return this.id = this.iModel.relationships.insertInstance(this.toJSON()); }\r\n /** Update this Relationship in the iModel. */\r\n public update() { this.iModel.relationships.updateInstance(this.toJSON()); }\r\n /** Delete this Relationship from the iModel. */\r\n public delete() { this.iModel.relationships.deleteInstance(this.toJSON()); }\r\n\r\n public static getInstance<T extends Relationship>(iModel: IModelDb, criteria: Id64String | SourceAndTarget): T { return iModel.relationships.getInstance(this.classFullName, criteria); }\r\n}\r\n\r\n/** A Relationship where one Element refers to another Element\r\n * @public\r\n */\r\nexport class ElementRefersToElements extends Relationship {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementRefersToElements\"; }\r\n /** Create an instance of the Relationship.\r\n * @param iModel The iModel that will contain the relationship\r\n * @param sourceId The sourceId of the relationship, that is, the driver element\r\n * @param targetId The targetId of the relationship, that is, the driven element\r\n * @return an instance of the specified class.\r\n */\r\n public static create<T extends ElementRefersToElements>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String): T {\r\n return iModel.relationships.createInstance({ sourceId, targetId, classFullName: this.classFullName }) as T;\r\n }\r\n /** Insert a new instance of the Relationship.\r\n * @param iModel The iModel that will contain the relationship\r\n * @param sourceId The sourceId of the relationship, that is, the driver element\r\n * @param targetId The targetId of the relationship, that is, the driven element\r\n * @return The Id of the inserted Relationship.\r\n */\r\n public static insert<T extends ElementRefersToElements>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String): Id64String {\r\n const relationship: T = this.create(iModel, sourceId, targetId);\r\n return iModel.relationships.insertInstance(relationship.toJSON());\r\n }\r\n\r\n /** @internal */\r\n protected override collectReferenceConcreteIds(referenceIds: EntityReferenceSet,): void {\r\n super.collectReferenceConcreteIds(referenceIds);\r\n referenceIds.addElement(this.sourceId);\r\n referenceIds.addElement(this.targetId);\r\n }\r\n}\r\n\r\n/** Relates a [[DrawingGraphic]] to the [[Element]] that it represents\r\n * @public\r\n */\r\nexport class DrawingGraphicRepresentsElement extends ElementRefersToElements {\r\n /** @internal */\r\n public static override get className(): string { return \"DrawingGraphicRepresentsElement\"; }\r\n}\r\n\r\n/** Relates a [[GraphicalElement3d]] to the [[Element]] that it represents\r\n * @public\r\n */\r\nexport class GraphicalElement3dRepresentsElement extends ElementRefersToElements {\r\n /** @internal */\r\n public static override get className(): string { return \"GraphicalElement3dRepresentsElement\"; }\r\n}\r\n\r\n/** Relates a [[SynchronizationConfigLink]] to N [[ExternalSource]] instances.\r\n * Each relationship instance represents an external source processed by the synchronization configuration.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.13\r\n * @beta\r\n */\r\nexport class SynchronizationConfigProcessesSources extends ElementRefersToElements {\r\n /** @internal */\r\n public static override get className(): string { return \"SynchronizationConfigProcessesSources\"; }\r\n}\r\n\r\n/** Relates a [[SynchronizationConfigLink]] to *root* [[ExternalSource]] instances.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.13\r\n * @beta\r\n */\r\nexport class SynchronizationConfigSpecifiesRootSources extends SynchronizationConfigProcessesSources {\r\n /** @internal */\r\n public static override get className(): string { return \"SynchronizationConfigSpecifiesRootSources\"; }\r\n}\r\n\r\n/** Properties that are common to all types of link table ECRelationships\r\n * @public\r\n */\r\nexport interface ElementGroupsMembersProps extends RelationshipProps {\r\n memberPriority: number;\r\n}\r\n\r\n/** An ElementRefersToElements relationship where one Element *groups* a set of other Elements.\r\n * @public\r\n */\r\nexport class ElementGroupsMembers extends ElementRefersToElements {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementGroupsMembers\"; }\r\n public memberPriority: number;\r\n\r\n constructor(props: ElementGroupsMembersProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.memberPriority = props.memberPriority;\r\n }\r\n\r\n public static override create<T extends ElementRefersToElements>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String, memberPriority: number = 0): T {\r\n const props: ElementGroupsMembersProps = { sourceId, targetId, memberPriority, classFullName: this.classFullName };\r\n return iModel.relationships.createInstance(props) as T;\r\n }\r\n}\r\n\r\n/** Relates a [[DefinitionGroup]] to its [[DefinitionElement]] members.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.10\r\n * @public\r\n */\r\nexport class DefinitionGroupGroupsDefinitions extends ElementGroupsMembers {\r\n /** @internal */\r\n public static override get className(): string { return \"DefinitionGroupGroupsDefinitions\"; }\r\n}\r\n\r\n/** Represents group membership where the group Element (and its properties) impart information about the member Elements above mere membership.\r\n * Implies that properties of the group should be considered as properties of its members.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.11\r\n * @public\r\n */\r\nexport class GroupImpartsToMembers extends ElementGroupsMembers {\r\n /** @internal */\r\n public static override get className(): string { return \"GroupImpartsToMembers\"; }\r\n}\r\n\r\n/** Relates an [[ExternalSourceGroup]] to its [[ExternalSource]] members.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.13\r\n * @beta\r\n */\r\nexport class ExternalSourceGroupGroupsSources extends ElementGroupsMembers {\r\n /** @internal */\r\n public static override get className(): string { return \"ExternalSourceGroupGroupsSources\"; }\r\n}\r\n\r\n/** Properties that are common to all types of ElementDrivesElements\r\n * @beta\r\n */\r\nexport interface ElementDrivesElementProps extends RelationshipProps {\r\n status: number;\r\n priority: number;\r\n}\r\n\r\n/** A Relationship indicating that one Element *drives* another Element.\r\n * An ElementDrivesElement relationship defines a one-way \"driving\" relationship from the source to the target.\r\n * When the source of an ElementDrivesElement relationship changes, the ElementDrivesElement itself can get a callback, and both the source and target elements can get callbacks.\r\n * By inserting ElementDrivesElement relationships, an app can create and store an acyclic directed graph of dependencies between elements.\r\n *\r\n * # Defining dependencies\r\n * Create an ElementDrivesElement relationship to specify that the source element drives the target element.\r\n * For example, to specify that element e1 drives element e2, create a relationship between them like this:\r\n * ```ts\r\n * const ede = ElementDrivesElement.create(iModel, e1id, e2id);\r\n * ede.insert();\r\n * ```\r\n * This creates a persistent relationship. The fact that e1 drives e2 is persisted in the iModel.\r\n *\r\n * # Defining dependency graphs\r\n * When you create multiple ElementDrivesElement relationships, you create a network of dependencies. The target of one may be the source of another.\r\n * A change in the content of an DgnElement can therefore trigger changes to many downstream elements.\r\n *\r\n * For example, to make element e1 drive element e2 and e2 drive another element, e3, create two relationships like this:\r\n * ```ts\r\n * const ede12 = ElementDrivesElement.create(iModel, e1id, e2id);\r\n * const ede23 = ElementDrivesElement.create(iModel, e2id, e3id);\r\n * ede12.insert();\r\n * ede23.insert();\r\n * ```\r\n * Those two relationships create this graph:\r\n * ```\r\n * e1 --> e2 --> e3\r\n * ```\r\n * Where the \"-->\" is meant to represent a driving relationship.\r\n *\r\n * The order in which you create the relationships does not matter.\r\n * The graph indicates that e3 depends on e2 and e2 depends on e1.\r\n *\r\n * An ElementDrivesElement relationship is between one source element and one target element.\r\n * Many ElementDrivesElement relationships can point to a given element, and many can point out of it.\r\n * Thus, you can define many:many relationships.\r\n * For example:\r\n * ```ts\r\n * const ede12 = ElementDrivesElement.create(iModel, e1id, e2id);\r\n * const ede112 = ElementDrivesElement.create(iModel, e11id, e2id);\r\n * const ede23 = ElementDrivesElement.create(iModel, e2id, e3id);\r\n * const ede231 = ElementDrivesElement.create(iModel, e2id, e31id);\r\n * ede12.insert();\r\n * ede112.insert();\r\n * ede23.insert();\r\n * ede231.insert();\r\n * ```\r\n * Creates this graph:\r\n * ```\r\n * e1 e3\r\n * \\ /\r\n * e2\r\n * / \\\r\n * e11 e31\r\n * ```\r\n * e2 depends on both e1 and e11. e2 then drives e3 and e31.\r\n *\r\n * In an ElementDrivesElement dependency graph, the relationships are the \"edges\" and the Elements are the \"nodes\".\r\n * The following terms are used when referring to the elements (nodes) in a dependency graph:\r\n * * Inputs - The sources of all edges that point to the element. This includes all upstream elements that flow into the element.\r\n * * Outputs - The targets of all edges that point out of the element. This includes all downstream elements.\r\n *\r\n * # Subgraph Processing\r\n * When changes are made, only the part of the overall graph that is affected will be processed. So, for example,\r\n * suppose we have this graph:\r\n * ```\r\n * e1 --> e2 --> e3\r\n * ```\r\n * If e1 changes, then the subgraph to be processed is equal to the full graph, as shown.\r\n *\r\n * If only e2 changes, then the subgraph to be processed is just:\r\n * ```\r\n * e2 --> e3\r\n * ```\r\n * If only e3 changes, then the subgraph consists of e3 by itself.\r\n *\r\n * Returning to the second example above, suppose we have this graph:\r\n * ```\r\n * e1 e3\r\n * \\ /\r\n * e2\r\n * / \\\r\n * e11 e31\r\n * ```\r\n * If e1 is changed, the affected subgraph is:\r\n * ```\r\n * e1 e3\r\n * \\ /\r\n * e2\r\n * \\\r\n * e31\r\n * ```\r\n * If e2 is changed, the affected subgraph is:\r\n * ```\r\n * e3\r\n * /\r\n * e2\r\n * \\\r\n * e31\r\n * ```\r\n * # Callbacks\r\n * Once the affected subgraph to process is found, it propagates changes through it by making callbacks.\r\n * Classes for both elements (nodes) and ElementDrivesElements relationships (edges) can receive callbacks.\r\n *\r\n * ## ElementDrivesElement Callbacks\r\n * The following callbacks are invoked on ElementDrivesElement relationship classes (edges):\r\n * * onRootChanged\r\n * * onDeletedDependency\r\n *\r\n * Note that these are static methods. Their default implementations do nothing.\r\n * To receive and act on these callbacks, a domain should define a subclass of ElementDrivesElement and use that to create relationships.\r\n * The subclass should then implement the callbacks that it would like to act on.\r\n *\r\n * A ElementDrivesElement subclass callback is expected to make changes to the output element only!\r\n *\r\n * ## Element Callbacks\r\n * The following callbacks are invoked on Element classes (nodes):\r\n * * Element.onBeforeOutputsHandled\r\n * * Element.onAllInputsHandled\r\n *\r\n * ## Order\r\n * Callbacks are invoked by BriefcaseDb.saveChanges.\r\n * They are invoked in dependency (topological) order: driving elements first, then driven elements.\r\n *\r\n * Each callback is invoked only once. No matter how many times a given element was changed during the transaction,\r\n * a callback such as ElementDrivesElement.onRootChanged will be invoked only once.\r\n * In the same way, no matter how many of its inputs were changed, a callback such as Element.onAllInputsHandled will be\r\n * invoked only once.\r\n *\r\n * For example, suppose we have a graph:\r\n * ```\r\n * e1 --> e2 --> e3\r\n * ```\r\n *\r\n * Suppose that e1 is directly modified. No callbacks are made at that time.\r\n * Later, when BriefcaseDb.saveChanges is called, the following callbacks are made, in order:\r\n * 1. Element.onBeforeOutputsHandled e1\r\n * 1. ElementDrivesElement.onRootChanged e1->e2\r\n * 1. Element.onAllInputsHandled e2\r\n * 1. ElementDrivesElement.onRootChanged e2->e3\r\n * 1. Element.onAllInputsHandled e3\r\n *\r\n * Suppose that e3 is modified directly and BriefcaseDb.saveChanges is called.\r\n * Since no input to a relationship was changed, the sub-graph will be empty, and no callbacks will be made.\r\n *\r\n * Returning to the second example above, suppose we have this graph:\r\n * ```\r\n * e1 e3\r\n * \\ /\r\n * e2\r\n * / \\\r\n * e11 e31\r\n * ```\r\n * If e1 is changed and BriefcaseDb.saveChanges is called, the subgraph is:\r\n * ```\r\n * e1 e3\r\n * \\ /\r\n * e2\r\n * \\\r\n * e31\r\n * ```\r\n * The callbacks are:\r\n * 1. Element.onBeforeOutputsHandled e1\r\n * 1. ElementDrivesElement.onRootChanged e1->e2\r\n * 1. Element.onAllInputsHandled e2\r\n * 1. ElementDrivesElement.onRootChanged e2->e3\r\n * 1. Element.onAllInputsHandled e3\r\n * 1. ElementDrivesElement.onRootChanged e2->e31\r\n * 1. Element.onAllInputsHandled e31\r\n *\r\n * (The ElementDrivesElement.)\r\n *\r\n * #Errors\r\n * Circular dependencies are not permitted. If a cycle is detected, that is treated as a fatal error. All ElementDrivesElement relationships\r\n * involved in a cycle will have their status set to 1, indicating a failure.\r\n *\r\n * A callback may call txnManager.reportError to reject an invalid change. It can classify the error as fatal or just a warning.\r\n * A callback make set the status value of an ElementDrivesElement instance to 1 to indicate a processing failure in that edge.\r\n *\r\n * After BriefcaseDb.saveChanges is called, an app should check db.txns.validationErrors and db.txns.hasFatalError to find out if graph-evaluation failed.\r\n *\r\n * @beta\r\n */\r\nexport class ElementDrivesElement extends Relationship {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementDrivesElement\"; }\r\n /** Relationship status\r\n * * 0 indicates no errors. Set after a successful evaluation.\r\n * * 1 indicates that this driving relationship could not be evaluated. The callback itself can set this to indicate that it failed to process the input changes. Also, it is set if the relationship is part of a circular dependency.\r\n * * 0x80 The app or callback can set this to indicate to not propagate changes through this relationship.\r\n */\r\n public status: number;\r\n /** Affects the order in which relationships are processed in the case where two relationships have the same output. */\r\n public priority: number;\r\n\r\n /** @internal */\r\n constructor(props: ElementDrivesElementProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.status = props.status;\r\n this.priority = props.priority;\r\n }\r\n\r\n public static create<T extends ElementDrivesElement>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String, priority: number = 0): T {\r\n const props: ElementDrivesElementProps = { sourceId, targetId, priority, status: 0, classFullName: this.classFullName };\r\n return iModel.relationships.createInstance(props) as T;\r\n }\r\n\r\n public override toJSON(): ElementDrivesElementProps {\r\n const props = super.toJSON() as ElementDrivesElementProps;\r\n props.status = this.status;\r\n props.priority = this.priority;\r\n return props;\r\n }\r\n\r\n /** @internal */\r\n protected override collectReferenceConcreteIds(referenceIds: EntityReferenceSet,): void {\r\n super.collectReferenceConcreteIds(referenceIds);\r\n referenceIds.addElement(this.sourceId);\r\n referenceIds.addElement(this.targetId);\r\n }\r\n}\r\n\r\n/** The third (and last) possible link-table relationship base class in an iModel.\r\n * Has no external use, but is included for completeness of the [Entity.collectReferenceConcreteIds]($backend)\r\n * implementations for link-table relationships. Generating the types of the source and target automatically would require\r\n * coupling this package with ecschema-metadata which we do not want to do.\r\n * @internal\r\n */\r\nexport class ModelSelectorRefersToModels extends Relationship {\r\n /** @internal */\r\n public static override get className(): string { return \"ModelSelectorRefersToModels\"; }\r\n /** @internal */\r\n protected override collectReferenceConcreteIds(referenceIds: EntityReferenceSet): void {\r\n super.collectReferenceConcreteIds(referenceIds);\r\n referenceIds.addElement(this.sourceId);\r\n referenceIds.addModel(this.targetId);\r\n }\r\n}\r\n\r\n/** Manages [[Relationship]]s.\r\n * @public\r\n */\r\nexport class Relationships {\r\n private _iModel: IModelDb;\r\n\r\n /** @internal */\r\n constructor(iModel: IModelDb) { this._iModel = iModel; }\r\n\r\n /** Create a new instance of a Relationship.\r\n * @param props The properties of the new Relationship.\r\n * @throws [[IModelError]] if there is a problem creating the Relationship.\r\n */\r\n public createInstance(props: RelationshipProps): Relationship { return this._iModel.constructEntity<Relationship>(props); }\r\n\r\n /** Check classFullName to ensure it is a link table relationship class. */\r\n private checkRelationshipClass(classFullName: string) {\r\n if (!this._iModel.nativeDb.isLinkTableRelationship(classFullName.replace(\".\", \":\"))) {\r\n throw new IModelError(DbResult.BE_SQLITE_ERROR, `Class '${classFullName}' must be a relationship class and it should be subclass of BisCore:ElementRefersToElements or BisCore:ElementDrivesElement.`);\r\n }\r\n }\r\n\r\n /** Insert a new relationship instance into the iModel. The relationship provided must be subclass of BisCore:ElementRefersToElements or BisCore:ElementDrivesElement.\r\n * @param props The properties of the new relationship.\r\n * @returns The Id of the newly inserted relationship.\r\n * @note The id property of the props object is set as a side effect of this function.\r\n */\r\n public insertInstance(props: RelationshipProps): Id64String {\r\n this.checkRelationshipClass(props.classFullName);\r\n return props.id = this._iModel.nativeDb.insertLinkTableRelationship(props);\r\n }\r\n\r\n /** Update the properties of an existing relationship instance in the iModel.\r\n * @param props the properties of the relationship instance to update. Any properties that are not present will be left unchanged.\r\n */\r\n public updateInstance(props: RelationshipProps): void {\r\n this._iModel.nativeDb.updateLinkTableRelationship(props);\r\n }\r\n\r\n /** Delete an Relationship instance from this iModel. */\r\n public deleteInstance(props: RelationshipProps): void {\r\n this._iModel.nativeDb.deleteLinkTableRelationship(props);\r\n }\r\n\r\n /** Get the props of a Relationship instance\r\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\r\n * @param criteria Either the relationship instanceId or the source and target Ids\r\n * @throws [IModelError]($common) if the relationship is not found or cannot be loaded.\r\n * @see tryGetInstanceProps\r\n */\r\n public getInstanceProps<T extends RelationshipProps>(relClassFullName: string, criteria: Id64String | SourceAndTarget): T {\r\n const relationshipProps = this.tryGetInstanceProps<T>(relClassFullName, criteria);\r\n if (undefined === relationshipProps) {\r\n throw new IModelError(IModelStatus.NotFound, \"Relationship not found\");\r\n }\r\n return relationshipProps;\r\n }\r\n\r\n /** Get the props of a Relationship instance\r\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\r\n * @param criteria Either the relationship instanceId or the source and target Ids\r\n * @returns The RelationshipProps or `undefined` if the relationship is not found.\r\n * @note Useful for cases when a relationship may or may not exist and throwing an `Error` would be overkill.\r\n * @see getInstanceProps\r\n */\r\n public tryGetInstanceProps<T extends RelationshipProps>(relClassFullName: string, criteria: Id64String | SourceAndTarget): T | undefined {\r\n let props: T | undefined;\r\n if (typeof criteria === \"string\") {\r\n props = this._iModel.withPreparedStatement(`SELECT * FROM ${relClassFullName} WHERE ecinstanceid=?`, (stmt: ECSqlStatement) => {\r\n stmt.bindId(1, criteria);\r\n return DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getRow() as T : undefined;\r\n });\r\n } else {\r\n props = this._iModel.withPreparedStatement(`SELECT * FROM ${relClassFullName} WHERE SourceECInstanceId=? AND TargetECInstanceId=?`, (stmt: ECSqlStatement) => {\r\n stmt.bindId(1, criteria.sourceId);\r\n stmt.bindId(2, criteria.targetId);\r\n return DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getRow() as T : undefined;\r\n });\r\n }\r\n if (undefined !== props) {\r\n props.classFullName = (props as any).className.replace(\".\", \":\");\r\n }\r\n return props;\r\n }\r\n\r\n /** Get a Relationship instance\r\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\r\n * @param criteria Either the relationship instanceId or the source and target Ids\r\n * @throws [IModelError]($common) if the relationship is not found or cannot be loaded.\r\n * @see tryGetInstance\r\n */\r\n public getInstance<T extends Relationship>(relClassSqlName: string, criteria: Id64String | SourceAndTarget): T {\r\n return this._iModel.constructEntity<T>(this.getInstanceProps(relClassSqlName, criteria));\r\n }\r\n\r\n /** Get a Relationship instance\r\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\r\n * @param criteria Either the relationship instanceId or the source and target Ids\r\n * @returns The relationship or `undefined` if the relationship is not found.\r\n * @note Useful for cases when a relationship may or may not exist and throwing an `Error` would be overkill.\r\n * @see getInstance\r\n */\r\n public tryGetInstance<T extends Relationship>(relClassFullName: string, criteria: Id64String | SourceAndTarget): T | undefined {\r\n const relationshipProps = this.tryGetInstanceProps<RelationshipProps>(relClassFullName, criteria);\r\n return undefined !== relationshipProps ? this._iModel.constructEntity<T>(relationshipProps) : undefined;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"Relationship.js","sourceRoot":"","sources":["../../src/Relationship.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAAiE;AACjE,oDAAuH;AAEvH,qCAAkC;AAKlC;;GAEG;AACH,MAAa,YAAa,SAAQ,eAAM;IACtC,gBAAgB;IACT,MAAM,KAAc,SAAS,KAAa,OAAO,cAAc,CAAC,CAAC,CAAC;IAIzE,gBAAgB;IAChB,YAAY,KAAwB,EAAE,MAAgB;QACpD,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,mBAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC9C,IAAI,CAAC,QAAQ,GAAG,mBAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED,gBAAgB;IACA,MAAM;QACpB,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,EAAuB,CAAC;QAChD,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC7B,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC7B,OAAO,GAAG,CAAC;IACb,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,aAAa,CAAC,MAAyB,EAAE,OAAiB,IAAU,CAAC;IAEnF;;;;;OAKG;IACI,MAAM,CAAC,mBAAmB,CAAC,MAAyB,EAAE,OAAiB,IAAU,CAAC;IAEzF,gDAAgD;IACzC,MAAM,KAAiB,OAAO,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,cA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O,CAAC,eAAe,CAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1G,CAAC;CACF;AAvGD,sCAuGC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Relationships\n */\n\nimport { DbResult, Id64, Id64String } from \"@itwin/core-bentley\";\nimport { EntityReferenceSet, IModelError, IModelStatus, RelationshipProps, SourceAndTarget } from \"@itwin/core-common\";\nimport { ECSqlStatement } from \"./ECSqlStatement\";\nimport { Entity } from \"./Entity\";\nimport { IModelDb } from \"./IModelDb\";\n\nexport type { SourceAndTarget, RelationshipProps } from \"@itwin/core-common\"; // for backwards compatibility\n\n/** Base class for all link table ECRelationships\n * @public\n */\nexport class Relationship extends Entity {\n /** @internal */\n public static override get className(): string { return \"Relationship\"; }\n public readonly sourceId: Id64String;\n public readonly targetId: Id64String;\n\n /** @internal */\n constructor(props: RelationshipProps, iModel: IModelDb) {\n super(props, iModel);\n this.sourceId = Id64.fromJSON(props.sourceId);\n this.targetId = Id64.fromJSON(props.targetId);\n }\n\n /** @internal */\n public override toJSON(): RelationshipProps {\n const val = super.toJSON() as RelationshipProps;\n val.sourceId = this.sourceId;\n val.targetId = this.targetId;\n return val;\n }\n\n /**\n * Callback invoked by saveChanges on an ElementDrivesElement relationship when its input has changed or is the output of some upstream relationship whose input has changed.\n * This callback is invoked after the input element has been processed by upstream relationships.\n * A subclass of ElementDrivesElement can re-implement this static method to take some action. onRootChanged may modify the output element only.\n * @param _props The ElementDrivesElement relationship instance.\n * @param _iModel The iModel\n */\n public static onRootChanged(_props: RelationshipProps, _iModel: IModelDb): void { }\n\n /**\n * Callback invoked by saveChanges on an ElementDrivesElement relationship when the relationship instance has been deleted.\n * A subclass of ElementDrivesElement can re-implement this static method to take some action.\n * @param _props The deleted ElementDrivesElement relationship instance.\n * @param _iModel The iModel\n */\n public static onDeletedDependency(_props: RelationshipProps, _iModel: IModelDb): void { }\n\n /** Insert this Relationship into the iModel. */\n public insert(): Id64String { return this.id = this.iModel.relationships.insertInstance(this.toJSON()); }\n /** Update this Relationship in the iModel. */\n public update() { this.iModel.relationships.updateInstance(this.toJSON()); }\n /** Delete this Relationship from the iModel. */\n public delete() { this.iModel.relationships.deleteInstance(this.toJSON()); }\n\n public static getInstance<T extends Relationship>(iModel: IModelDb, criteria: Id64String | SourceAndTarget): T { return iModel.relationships.getInstance(this.classFullName, criteria); }\n}\n\n/** A Relationship where one Element refers to another Element\n * @public\n */\nexport class ElementRefersToElements extends Relationship {\n /** @internal */\n public static override get className(): string { return \"ElementRefersToElements\"; }\n /** Create an instance of the Relationship.\n * @param iModel The iModel that will contain the relationship\n * @param sourceId The sourceId of the relationship, that is, the driver element\n * @param targetId The targetId of the relationship, that is, the driven element\n * @return an instance of the specified class.\n */\n public static create<T extends ElementRefersToElements>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String): T {\n return iModel.relationships.createInstance({ sourceId, targetId, classFullName: this.classFullName }) as T;\n }\n /** Insert a new instance of the Relationship.\n * @param iModel The iModel that will contain the relationship\n * @param sourceId The sourceId of the relationship, that is, the driver element\n * @param targetId The targetId of the relationship, that is, the driven element\n * @return The Id of the inserted Relationship.\n */\n public static insert<T extends ElementRefersToElements>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String): Id64String {\n const relationship: T = this.create(iModel, sourceId, targetId);\n return iModel.relationships.insertInstance(relationship.toJSON());\n }\n\n /** @internal */\n protected override collectReferenceConcreteIds(referenceIds: EntityReferenceSet,): void {\n super.collectReferenceConcreteIds(referenceIds);\n referenceIds.addElement(this.sourceId);\n referenceIds.addElement(this.targetId);\n }\n}\n\n/** Relates a [[DrawingGraphic]] to the [[Element]] that it represents\n * @public\n */\nexport class DrawingGraphicRepresentsElement extends ElementRefersToElements {\n /** @internal */\n public static override get className(): string { return \"DrawingGraphicRepresentsElement\"; }\n}\n\n/** Relates a [[GraphicalElement3d]] to the [[Element]] that it represents\n * @public\n */\nexport class GraphicalElement3dRepresentsElement extends ElementRefersToElements {\n /** @internal */\n public static override get className(): string { return \"GraphicalElement3dRepresentsElement\"; }\n}\n\n/** Relates a [[SynchronizationConfigLink]] to N [[ExternalSource]] instances.\n * Each relationship instance represents an external source processed by the synchronization configuration.\n * @note The associated ECClass was added to the BisCore schema in version 1.0.13\n * @beta\n */\nexport class SynchronizationConfigProcessesSources extends ElementRefersToElements {\n /** @internal */\n public static override get className(): string { return \"SynchronizationConfigProcessesSources\"; }\n}\n\n/** Relates a [[SynchronizationConfigLink]] to *root* [[ExternalSource]] instances.\n * @note The associated ECClass was added to the BisCore schema in version 1.0.13\n * @beta\n */\nexport class SynchronizationConfigSpecifiesRootSources extends SynchronizationConfigProcessesSources {\n /** @internal */\n public static override get className(): string { return \"SynchronizationConfigSpecifiesRootSources\"; }\n}\n\n/** Properties that are common to all types of link table ECRelationships\n * @public\n */\nexport interface ElementGroupsMembersProps extends RelationshipProps {\n memberPriority: number;\n}\n\n/** An ElementRefersToElements relationship where one Element *groups* a set of other Elements.\n * @public\n */\nexport class ElementGroupsMembers extends ElementRefersToElements {\n /** @internal */\n public static override get className(): string { return \"ElementGroupsMembers\"; }\n public memberPriority: number;\n\n constructor(props: ElementGroupsMembersProps, iModel: IModelDb) {\n super(props, iModel);\n this.memberPriority = props.memberPriority;\n }\n\n public static override create<T extends ElementRefersToElements>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String, memberPriority: number = 0): T {\n const props: ElementGroupsMembersProps = { sourceId, targetId, memberPriority, classFullName: this.classFullName };\n return iModel.relationships.createInstance(props) as T;\n }\n}\n\n/** Relates a [[DefinitionGroup]] to its [[DefinitionElement]] members.\n * @note The associated ECClass was added to the BisCore schema in version 1.0.10\n * @public\n */\nexport class DefinitionGroupGroupsDefinitions extends ElementGroupsMembers {\n /** @internal */\n public static override get className(): string { return \"DefinitionGroupGroupsDefinitions\"; }\n}\n\n/** Represents group membership where the group Element (and its properties) impart information about the member Elements above mere membership.\n * Implies that properties of the group should be considered as properties of its members.\n * @note The associated ECClass was added to the BisCore schema in version 1.0.11\n * @public\n */\nexport class GroupImpartsToMembers extends ElementGroupsMembers {\n /** @internal */\n public static override get className(): string { return \"GroupImpartsToMembers\"; }\n}\n\n/** Relates an [[ExternalSourceGroup]] to its [[ExternalSource]] members.\n * @note The associated ECClass was added to the BisCore schema in version 1.0.13\n * @beta\n */\nexport class ExternalSourceGroupGroupsSources extends ElementGroupsMembers {\n /** @internal */\n public static override get className(): string { return \"ExternalSourceGroupGroupsSources\"; }\n}\n\n/** Properties that are common to all types of ElementDrivesElements\n * @beta\n */\nexport interface ElementDrivesElementProps extends RelationshipProps {\n status: number;\n priority: number;\n}\n\n/** A Relationship indicating that one Element *drives* another Element.\n * An ElementDrivesElement relationship defines a one-way \"driving\" relationship from the source to the target.\n * When the source of an ElementDrivesElement relationship changes, the ElementDrivesElement itself can get a callback, and both the source and target elements can get callbacks.\n * By inserting ElementDrivesElement relationships, an app can create and store an acyclic directed graph of dependencies between elements.\n *\n * # Defining dependencies\n * Create an ElementDrivesElement relationship to specify that the source element drives the target element.\n * For example, to specify that element e1 drives element e2, create a relationship between them like this:\n * ```ts\n * const ede = ElementDrivesElement.create(iModel, e1id, e2id);\n * ede.insert();\n * ```\n * This creates a persistent relationship. The fact that e1 drives e2 is persisted in the iModel.\n *\n * # Defining dependency graphs\n * When you create multiple ElementDrivesElement relationships, you create a network of dependencies. The target of one may be the source of another.\n * A change in the content of an DgnElement can therefore trigger changes to many downstream elements.\n *\n * For example, to make element e1 drive element e2 and e2 drive another element, e3, create two relationships like this:\n * ```ts\n * const ede12 = ElementDrivesElement.create(iModel, e1id, e2id);\n * const ede23 = ElementDrivesElement.create(iModel, e2id, e3id);\n * ede12.insert();\n * ede23.insert();\n * ```\n * Those two relationships create this graph:\n * ```\n * e1 --> e2 --> e3\n * ```\n * Where the \"-->\" is meant to represent a driving relationship.\n *\n * The order in which you create the relationships does not matter.\n * The graph indicates that e3 depends on e2 and e2 depends on e1.\n *\n * An ElementDrivesElement relationship is between one source element and one target element.\n * Many ElementDrivesElement relationships can point to a given element, and many can point out of it.\n * Thus, you can define many:many relationships.\n * For example:\n * ```ts\n * const ede12 = ElementDrivesElement.create(iModel, e1id, e2id);\n * const ede112 = ElementDrivesElement.create(iModel, e11id, e2id);\n * const ede23 = ElementDrivesElement.create(iModel, e2id, e3id);\n * const ede231 = ElementDrivesElement.create(iModel, e2id, e31id);\n * ede12.insert();\n * ede112.insert();\n * ede23.insert();\n * ede231.insert();\n * ```\n * Creates this graph:\n * ```\n * e1 e3\n * \\ /\n * e2\n * / \\\n * e11 e31\n * ```\n * e2 depends on both e1 and e11. e2 then drives e3 and e31.\n *\n * In an ElementDrivesElement dependency graph, the relationships are the \"edges\" and the Elements are the \"nodes\".\n * The following terms are used when referring to the elements (nodes) in a dependency graph:\n * * Inputs - The sources of all edges that point to the element. This includes all upstream elements that flow into the element.\n * * Outputs - The targets of all edges that point out of the element. This includes all downstream elements.\n *\n * # Subgraph Processing\n * When changes are made, only the part of the overall graph that is affected will be processed. So, for example,\n * suppose we have this graph:\n * ```\n * e1 --> e2 --> e3\n * ```\n * If e1 changes, then the subgraph to be processed is equal to the full graph, as shown.\n *\n * If only e2 changes, then the subgraph to be processed is just:\n * ```\n * e2 --> e3\n * ```\n * If only e3 changes, then the subgraph consists of e3 by itself.\n *\n * Returning to the second example above, suppose we have this graph:\n * ```\n * e1 e3\n * \\ /\n * e2\n * / \\\n * e11 e31\n * ```\n * If e1 is changed, the affected subgraph is:\n * ```\n * e1 e3\n * \\ /\n * e2\n * \\\n * e31\n * ```\n * If e2 is changed, the affected subgraph is:\n * ```\n * e3\n * /\n * e2\n * \\\n * e31\n * ```\n * # Callbacks\n * Once the affected subgraph to process is found, it propagates changes through it by making callbacks.\n * Classes for both elements (nodes) and ElementDrivesElements relationships (edges) can receive callbacks.\n *\n * ## ElementDrivesElement Callbacks\n * The following callbacks are invoked on ElementDrivesElement relationship classes (edges):\n * * onRootChanged\n * * onDeletedDependency\n *\n * Note that these are static methods. Their default implementations do nothing.\n * To receive and act on these callbacks, a domain should define a subclass of ElementDrivesElement and use that to create relationships.\n * The subclass should then implement the callbacks that it would like to act on.\n *\n * A ElementDrivesElement subclass callback is expected to make changes to the output element only!\n *\n * ## Element Callbacks\n * The following callbacks are invoked on Element classes (nodes):\n * * Element.onBeforeOutputsHandled\n * * Element.onAllInputsHandled\n *\n * ## Order\n * Callbacks are invoked by BriefcaseDb.saveChanges.\n * They are invoked in dependency (topological) order: driving elements first, then driven elements.\n *\n * Each callback is invoked only once. No matter how many times a given element was changed during the transaction,\n * a callback such as ElementDrivesElement.onRootChanged will be invoked only once.\n * In the same way, no matter how many of its inputs were changed, a callback such as Element.onAllInputsHandled will be\n * invoked only once.\n *\n * For example, suppose we have a graph:\n * ```\n * e1 --> e2 --> e3\n * ```\n *\n * Suppose that e1 is directly modified. No callbacks are made at that time.\n * Later, when BriefcaseDb.saveChanges is called, the following callbacks are made, in order:\n * 1. Element.onBeforeOutputsHandled e1\n * 1. ElementDrivesElement.onRootChanged e1->e2\n * 1. Element.onAllInputsHandled e2\n * 1. ElementDrivesElement.onRootChanged e2->e3\n * 1. Element.onAllInputsHandled e3\n *\n * Suppose that e3 is modified directly and BriefcaseDb.saveChanges is called.\n * Since no input to a relationship was changed, the sub-graph will be empty, and no callbacks will be made.\n *\n * Returning to the second example above, suppose we have this graph:\n * ```\n * e1 e3\n * \\ /\n * e2\n * / \\\n * e11 e31\n * ```\n * If e1 is changed and BriefcaseDb.saveChanges is called, the subgraph is:\n * ```\n * e1 e3\n * \\ /\n * e2\n * \\\n * e31\n * ```\n * The callbacks are:\n * 1. Element.onBeforeOutputsHandled e1\n * 1. ElementDrivesElement.onRootChanged e1->e2\n * 1. Element.onAllInputsHandled e2\n * 1. ElementDrivesElement.onRootChanged e2->e3\n * 1. Element.onAllInputsHandled e3\n * 1. ElementDrivesElement.onRootChanged e2->e31\n * 1. Element.onAllInputsHandled e31\n *\n * (The ElementDrivesElement.)\n *\n * #Errors\n * Circular dependencies are not permitted. If a cycle is detected, that is treated as a fatal error. All ElementDrivesElement relationships\n * involved in a cycle will have their status set to 1, indicating a failure.\n *\n * A callback may call txnManager.reportError to reject an invalid change. It can classify the error as fatal or just a warning.\n * A callback make set the status value of an ElementDrivesElement instance to 1 to indicate a processing failure in that edge.\n *\n * After BriefcaseDb.saveChanges is called, an app should check db.txns.validationErrors and db.txns.hasFatalError to find out if graph-evaluation failed.\n *\n * @beta\n */\nexport class ElementDrivesElement extends Relationship {\n /** @internal */\n public static override get className(): string { return \"ElementDrivesElement\"; }\n /** Relationship status\n * * 0 indicates no errors. Set after a successful evaluation.\n * * 1 indicates that this driving relationship could not be evaluated. The callback itself can set this to indicate that it failed to process the input changes. Also, it is set if the relationship is part of a circular dependency.\n * * 0x80 The app or callback can set this to indicate to not propagate changes through this relationship.\n */\n public status: number;\n /** Affects the order in which relationships are processed in the case where two relationships have the same output. */\n public priority: number;\n\n /** @internal */\n constructor(props: ElementDrivesElementProps, iModel: IModelDb) {\n super(props, iModel);\n this.status = props.status;\n this.priority = props.priority;\n }\n\n public static create<T extends ElementDrivesElement>(iModel: IModelDb, sourceId: Id64String, targetId: Id64String, priority: number = 0): T {\n const props: ElementDrivesElementProps = { sourceId, targetId, priority, status: 0, classFullName: this.classFullName };\n return iModel.relationships.createInstance(props) as T;\n }\n\n public override toJSON(): ElementDrivesElementProps {\n const props = super.toJSON() as ElementDrivesElementProps;\n props.status = this.status;\n props.priority = this.priority;\n return props;\n }\n\n /** @internal */\n protected override collectReferenceConcreteIds(referenceIds: EntityReferenceSet,): void {\n super.collectReferenceConcreteIds(referenceIds);\n referenceIds.addElement(this.sourceId);\n referenceIds.addElement(this.targetId);\n }\n}\n\n/** The third (and last) possible link-table relationship base class in an iModel.\n * Has no external use, but is included for completeness of the [Entity.collectReferenceConcreteIds]($backend)\n * implementations for link-table relationships. Generating the types of the source and target automatically would require\n * coupling this package with ecschema-metadata which we do not want to do.\n * @internal\n */\nexport class ModelSelectorRefersToModels extends Relationship {\n /** @internal */\n public static override get className(): string { return \"ModelSelectorRefersToModels\"; }\n /** @internal */\n protected override collectReferenceConcreteIds(referenceIds: EntityReferenceSet): void {\n super.collectReferenceConcreteIds(referenceIds);\n referenceIds.addElement(this.sourceId);\n referenceIds.addModel(this.targetId);\n }\n}\n\n/** Manages [[Relationship]]s.\n * @public\n */\nexport class Relationships {\n private _iModel: IModelDb;\n\n /** @internal */\n constructor(iModel: IModelDb) { this._iModel = iModel; }\n\n /** Create a new instance of a Relationship.\n * @param props The properties of the new Relationship.\n * @throws [[IModelError]] if there is a problem creating the Relationship.\n */\n public createInstance(props: RelationshipProps): Relationship { return this._iModel.constructEntity<Relationship>(props); }\n\n /** Check classFullName to ensure it is a link table relationship class. */\n private checkRelationshipClass(classFullName: string) {\n if (!this._iModel.nativeDb.isLinkTableRelationship(classFullName.replace(\".\", \":\"))) {\n throw new IModelError(DbResult.BE_SQLITE_ERROR, `Class '${classFullName}' must be a relationship class and it should be subclass of BisCore:ElementRefersToElements or BisCore:ElementDrivesElement.`);\n }\n }\n\n /** Insert a new relationship instance into the iModel. The relationship provided must be subclass of BisCore:ElementRefersToElements or BisCore:ElementDrivesElement.\n * @param props The properties of the new relationship.\n * @returns The Id of the newly inserted relationship.\n * @note The id property of the props object is set as a side effect of this function.\n */\n public insertInstance(props: RelationshipProps): Id64String {\n this.checkRelationshipClass(props.classFullName);\n return props.id = this._iModel.nativeDb.insertLinkTableRelationship(props);\n }\n\n /** Update the properties of an existing relationship instance in the iModel.\n * @param props the properties of the relationship instance to update. Any properties that are not present will be left unchanged.\n */\n public updateInstance(props: RelationshipProps): void {\n this._iModel.nativeDb.updateLinkTableRelationship(props);\n }\n\n /** Delete an Relationship instance from this iModel. */\n public deleteInstance(props: RelationshipProps): void {\n this._iModel.nativeDb.deleteLinkTableRelationship(props);\n }\n\n /** Get the props of a Relationship instance\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\n * @param criteria Either the relationship instanceId or the source and target Ids\n * @throws [IModelError]($common) if the relationship is not found or cannot be loaded.\n * @see tryGetInstanceProps\n */\n public getInstanceProps<T extends RelationshipProps>(relClassFullName: string, criteria: Id64String | SourceAndTarget): T {\n const relationshipProps = this.tryGetInstanceProps<T>(relClassFullName, criteria);\n if (undefined === relationshipProps) {\n throw new IModelError(IModelStatus.NotFound, \"Relationship not found\");\n }\n return relationshipProps;\n }\n\n /** Get the props of a Relationship instance\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\n * @param criteria Either the relationship instanceId or the source and target Ids\n * @returns The RelationshipProps or `undefined` if the relationship is not found.\n * @note Useful for cases when a relationship may or may not exist and throwing an `Error` would be overkill.\n * @see getInstanceProps\n */\n public tryGetInstanceProps<T extends RelationshipProps>(relClassFullName: string, criteria: Id64String | SourceAndTarget): T | undefined {\n let props: T | undefined;\n if (typeof criteria === \"string\") {\n props = this._iModel.withPreparedStatement(`SELECT * FROM ${relClassFullName} WHERE ecinstanceid=?`, (stmt: ECSqlStatement) => {\n stmt.bindId(1, criteria);\n return DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getRow() as T : undefined;\n });\n } else {\n props = this._iModel.withPreparedStatement(`SELECT * FROM ${relClassFullName} WHERE SourceECInstanceId=? AND TargetECInstanceId=?`, (stmt: ECSqlStatement) => {\n stmt.bindId(1, criteria.sourceId);\n stmt.bindId(2, criteria.targetId);\n return DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getRow() as T : undefined;\n });\n }\n if (undefined !== props) {\n props.classFullName = (props as any).className.replace(\".\", \":\");\n }\n return props;\n }\n\n /** Get a Relationship instance\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\n * @param criteria Either the relationship instanceId or the source and target Ids\n * @throws [IModelError]($common) if the relationship is not found or cannot be loaded.\n * @see tryGetInstance\n */\n public getInstance<T extends Relationship>(relClassSqlName: string, criteria: Id64String | SourceAndTarget): T {\n return this._iModel.constructEntity<T>(this.getInstanceProps(relClassSqlName, criteria));\n }\n\n /** Get a Relationship instance\n * @param relClassFullName The full class name of the relationship in the form of \"schema:class\"\n * @param criteria Either the relationship instanceId or the source and target Ids\n * @returns The relationship or `undefined` if the relationship is not found.\n * @note Useful for cases when a relationship may or may not exist and throwing an `Error` would be overkill.\n * @see getInstance\n */\n public tryGetInstance<T extends Relationship>(relClassFullName: string, criteria: Id64String | SourceAndTarget): T | undefined {\n const relationshipProps = this.tryGetInstanceProps<RelationshipProps>(relClassFullName, criteria);\n return undefined !== relationshipProps ? this._iModel.constructEntity<T>(relationshipProps) : undefined;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"RpcBackend.js","sourceRoot":"","sources":["../../src/RpcBackend.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,oDAAsF;AACtF,+CAAsG;AACtG,2CAAkD;AAClD,+CAA4D;AAC5D,+CAAiD;AACjD,iDAAkD;AAElD,4CAA4C;AAE5C,IAAI,WAAW,GAAG,KAAK,CAAC;AACxB,gBAAgB;AAChB,SAAgB,oBAAoB,CAAC,sBAA+B,KAAK;IACvE,IAAI,WAAW;QACb,OAAO;IAET,IAAA,2BAAiB,EAAC,mBAAmB,CAAC,CAAC;IAEvC,0BAAY,CAAC,QAAQ,CAAC,YAAY,GAAG,iCAAqB,CAAC;IAC3D,0BAAY,CAAC,QAAQ,CAAC,YAAY,GAAG,iCAAqB,CAAC;IAC3D,0BAAY,CAAC,QAAQ,CAAC,YAAY,GAAG,iCAAqB,CAAC;IAE3D,8BAAgB,CAAC,OAAO,CAAC,YAAY,GAAG,uBAAY,CAAC;IACrD,8BAAgB,CAAC,OAAO,CAAC,YAAY,GAAG,sBAAY,CAAC;IAErD,8BAAgB,CAAC,iBAAiB,CAAC,IAAI,iCAAuB,EAAE,CAAC,CAAC;IAElE,WAAW,GAAG,IAAI,CAAC;AACrB,CAAC;AAhBD,oDAgBC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module RpcInterface\r\n */\r\n\r\nimport { RpcMultipart, WebAppRpcLogging, WebAppRpcRequest } from \"@itwin/core-common\";\r\nimport { appendToMultipartForm, createMultipartStream, parseMultipartRequest } from \"./rpc/multipart\";\r\nimport { initializeTracing } from \"./rpc/tracing\";\r\nimport { WebAppRpcLoggingBackend } from \"./rpc/web/logging\";\r\nimport { parseRequest } from \"./rpc/web/request\";\r\nimport { sendResponse } from \"./rpc/web/response\";\r\n\r\n/* eslint-disable deprecation/deprecation */\r\n\r\nlet initialized = false;\r\n/** @internal */\r\nexport function initializeRpcBackend(enableOpenTelemetry: boolean = false) {\r\n if (initialized)\r\n return;\r\n\r\n initializeTracing(enableOpenTelemetry);\r\n\r\n RpcMultipart.platform.createStream = createMultipartStream;\r\n RpcMultipart.platform.parseRequest = parseMultipartRequest;\r\n RpcMultipart.platform.appendToForm = appendToMultipartForm;\r\n\r\n WebAppRpcRequest.backend.sendResponse = sendResponse;\r\n WebAppRpcRequest.backend.parseRequest = parseRequest;\r\n\r\n WebAppRpcLogging.initializeBackend(new WebAppRpcLoggingBackend());\r\n\r\n initialized = true;\r\n}\r\n"]}
1
+ {"version":3,"file":"RpcBackend.js","sourceRoot":"","sources":["../../src/RpcBackend.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,oDAAsF;AACtF,+CAAsG;AACtG,2CAAkD;AAClD,+CAA4D;AAC5D,+CAAiD;AACjD,iDAAkD;AAElD,4CAA4C;AAE5C,IAAI,WAAW,GAAG,KAAK,CAAC;AACxB,gBAAgB;AAChB,SAAgB,oBAAoB,CAAC,sBAA+B,KAAK;IACvE,IAAI,WAAW;QACb,OAAO;IAET,IAAA,2BAAiB,EAAC,mBAAmB,CAAC,CAAC;IAEvC,0BAAY,CAAC,QAAQ,CAAC,YAAY,GAAG,iCAAqB,CAAC;IAC3D,0BAAY,CAAC,QAAQ,CAAC,YAAY,GAAG,iCAAqB,CAAC;IAC3D,0BAAY,CAAC,QAAQ,CAAC,YAAY,GAAG,iCAAqB,CAAC;IAE3D,8BAAgB,CAAC,OAAO,CAAC,YAAY,GAAG,uBAAY,CAAC;IACrD,8BAAgB,CAAC,OAAO,CAAC,YAAY,GAAG,sBAAY,CAAC;IAErD,8BAAgB,CAAC,iBAAiB,CAAC,IAAI,iCAAuB,EAAE,CAAC,CAAC;IAElE,WAAW,GAAG,IAAI,CAAC;AACrB,CAAC;AAhBD,oDAgBC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module RpcInterface\n */\n\nimport { RpcMultipart, WebAppRpcLogging, WebAppRpcRequest } from \"@itwin/core-common\";\nimport { appendToMultipartForm, createMultipartStream, parseMultipartRequest } from \"./rpc/multipart\";\nimport { initializeTracing } from \"./rpc/tracing\";\nimport { WebAppRpcLoggingBackend } from \"./rpc/web/logging\";\nimport { parseRequest } from \"./rpc/web/request\";\nimport { sendResponse } from \"./rpc/web/response\";\n\n/* eslint-disable deprecation/deprecation */\n\nlet initialized = false;\n/** @internal */\nexport function initializeRpcBackend(enableOpenTelemetry: boolean = false) {\n if (initialized)\n return;\n\n initializeTracing(enableOpenTelemetry);\n\n RpcMultipart.platform.createStream = createMultipartStream;\n RpcMultipart.platform.parseRequest = parseMultipartRequest;\n RpcMultipart.platform.appendToForm = appendToMultipartForm;\n\n WebAppRpcRequest.backend.sendResponse = sendResponse;\n WebAppRpcRequest.backend.parseRequest = parseRequest;\n\n WebAppRpcLogging.initializeBackend(new WebAppRpcLoggingBackend());\n\n initialized = true;\n}\n"]}
@@ -1 +1 @@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d,uBAAc,KAAd,uBAAc,QASzB;AAgDH,CAAC,EAjHgB,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAiHxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module SQLiteDb\r\n */\r\n\r\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { DbResult, IDisposable, OpenMode } from \"@itwin/core-bentley\";\r\nimport { LocalFileName } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { IModelHost } from \"./IModelHost\";\r\nimport { SqliteStatement, StatementCache } from \"./SqliteStatement\";\r\n\r\n// cspell:ignore savepoint\r\n/* eslint-disable @typescript-eslint/unified-signatures */\r\n\r\n/** A SQLiteDb file\r\n * @public\r\n */\r\nexport class SQLiteDb implements IDisposable {\r\n /** @internal */\r\n public readonly nativeDb = new IModelHost.platform.SQLiteDb();\r\n private _sqliteStatementCache = new StatementCache<SqliteStatement>();\r\n\r\n /** @internal */\r\n public static createBlobIO(): SQLiteDb.BlobIO {\r\n return new IModelHost.platform.BlobIO();\r\n }\r\n\r\n /** alias for closeDb. */\r\n public dispose(): void {\r\n this.closeDb();\r\n }\r\n\r\n /** Create a SQLiteDb\r\n * @param dbName The path to the SQLiteDb file to create.\r\n */\r\n public createDb(dbName: string): void;\r\n /** @beta */\r\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void;\r\n /** @internal */\r\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void {\r\n this.nativeDb.createDb(dbName, container, params);\r\n }\r\n\r\n /** Open a SQLiteDb.\r\n * @param dbName The path to the SQLiteDb file to open\r\n */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams): void;\r\n /**\r\n * @param container optional CloudContainer holding database\r\n * @beta\r\n */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void;\r\n\r\n /** @internal */\r\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void {\r\n this.nativeDb.openDb(dbName, openMode, container);\r\n }\r\n\r\n /** Close SQLiteDb.\r\n * @param saveChanges if true, call `saveChanges` before closing db. Otherwise unsaved changes are abandoned.\r\n */\r\n public closeDb(saveChanges?: boolean): void {\r\n if (saveChanges && this.isOpen)\r\n this.saveChanges();\r\n this._sqliteStatementCache.clear();\r\n this.nativeDb.closeDb();\r\n }\r\n\r\n /** Returns true if this SQLiteDb is open */\r\n public get isOpen(): boolean { return this.nativeDb.isOpen(); }\r\n\r\n /** Returns true if this SQLiteDb is open readonly */\r\n public get isReadonly(): boolean { return this.nativeDb.isReadonly(); }\r\n\r\n /**\r\n * Open a database, perform an operation, then close the database.\r\n *\r\n * Details:\r\n * - if database is open, throw an error\r\n * - open a database\r\n * - call a function with the database opened. If it is async, await its return.\r\n * - if function throws, abandon all changes, close database, and rethrow\r\n * - save all changes\r\n * - close the database\r\n * @return value from operation\r\n */\r\n public withOpenDb<T>(args: SQLiteDb.WithOpenDbArgs, operation: () => T): T {\r\n if (this.isOpen)\r\n throw new Error(\"database is already open\");\r\n\r\n const save = () => this.closeDb(true), abandon = () => this.closeDb(false);\r\n this.openDb(args.dbName, args.openMode ?? OpenMode.Readonly, args.container);\r\n try {\r\n const result = operation();\r\n result instanceof Promise ? result.then(save, abandon) : save();\r\n return result;\r\n } catch (e) {\r\n abandon();\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * Perform an operation on a database in a CloudContainer with the write lock held.\r\n *\r\n * Details:\r\n * - acquire the write lock on a CloudContainer\r\n * - call `withOpenDb` with openMode `ReadWrite`\r\n * - upload changes\r\n * - release the write lock\r\n * @param args arguments to lock the container and open the database\r\n * @param operation an operation performed on the database with the write lock held.\r\n * @return value from operation\r\n * @internal\r\n */\r\n public async withLockedContainer<T>(args: CloudSqlite.LockAndOpenArgs, operation: () => T) {\r\n return CloudSqlite.withWriteLock(args.user, args.container, () => this.withOpenDb({ ...args, openMode: OpenMode.ReadWrite }, operation), args.busyHandler);\r\n }\r\n\r\n /** vacuum this database\r\n * @see https://www.sqlite.org/lang_vacuum.html\r\n */\r\n public vacuum(args?: SQLiteDb.VacuumDbArgs) {\r\n this.nativeDb.vacuum(args);\r\n }\r\n\r\n /** Commit the outermost transaction, writing changes to the file. Then, restart the transaction. */\r\n public saveChanges(): void {\r\n this.nativeDb.saveChanges();\r\n }\r\n\r\n /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the transaction. */\r\n public abandonChanges(): void {\r\n this.nativeDb.abandonChanges();\r\n }\r\n\r\n /**\r\n * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist\r\n * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved\r\n * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be\r\n * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding\r\n * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].\r\n * @param sql The SQLite SQL statement to execute\r\n * @param callback the callback to invoke on the prepared statement\r\n * @returns the value returned by `callback`.\r\n */\r\n public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\r\n const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql);\r\n const release = () => this._sqliteStatementCache.addOrDispose(stmt);\r\n try {\r\n const val = callback(stmt);\r\n val instanceof Promise ? val.then(release, release) : release();\r\n return val;\r\n } catch (err) {\r\n release();\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Prepared and execute a callback on a SQL statement. After the callback completes the statement is disposed.\r\n * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.\r\n * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].\r\n * @param sql The SQLite SQL statement to execute\r\n * @param callback the callback to invoke on the prepared statement\r\n * @returns the value returned by `callback`.\r\n */\r\n public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\r\n const stmt = this.prepareSqliteStatement(sql);\r\n const release = () => stmt.dispose();\r\n try {\r\n const val = callback(stmt);\r\n val instanceof Promise ? val.then(release, release) : release();\r\n return val;\r\n } catch (err) {\r\n release();\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Perform an operation on this database within a [savepoint](https://www.sqlite.org/lang_savepoint.html). If the operation completes successfully, the\r\n * changes remain in the current transaction. If the operation throws an exception, the savepoint is rolled back\r\n * and all changes to the database from this method are reversed, leaving the transaction exactly as it was before this method.\r\n */\r\n public withSavePoint(savePointName: string, operation: () => void) {\r\n if (this.isReadonly)\r\n throw new Error(\"database is readonly\");\r\n\r\n this.executeSQL(`SAVEPOINT ${savePointName}`);\r\n try {\r\n operation();\r\n this.executeSQL(`RELEASE ${savePointName}`);\r\n } catch (e) {\r\n this.executeSQL(`ROLLBACK TO ${savePointName}`);\r\n throw e;\r\n }\r\n }\r\n\r\n /** Prepare an SQL statement.\r\n * @param sql The SQLite SQL statement to prepare\r\n * @param logErrors Determine if errors are logged or not\r\n * @internal\r\n */\r\n public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {\r\n const stmt = new SqliteStatement(sql);\r\n stmt.prepare(this.nativeDb, logErrors);\r\n return stmt;\r\n }\r\n\r\n /** execute an SQL statement */\r\n public executeSQL(sql: string): DbResult {\r\n const stmt = this.prepareSqliteStatement(sql);\r\n try {\r\n return stmt.step();\r\n } finally {\r\n stmt.dispose();\r\n }\r\n }\r\n}\r\n\r\n/** @public */\r\nexport namespace SQLiteDb {\r\n /** interface for reading and writing to a blob in a SQLiteDb\r\n * @internal\r\n */\r\n export interface BlobIO {\r\n /** Close this BlobIO if it is opened.\r\n * @note this BlobIO *may* be reused after this call by calling `open` again.\r\n */\r\n close(): void;\r\n /** get the total number of bytes in the blob */\r\n getNumBytes(): number;\r\n /** @return true if this BlobIO was successfully opened and may be use to read or write the blob */\r\n isValid(): boolean;\r\n /** Open this BlobIO against a table/row/column in a Db */\r\n open(\r\n /** The database for the blob */\r\n db: IModelJsNative.AnyDb,\r\n args: {\r\n /** the name of the table for the blob*/\r\n tableName: string;\r\n /** the name of the column for the blob */\r\n columnName: string;\r\n /** The rowId of the blob */\r\n row: number;\r\n /** If true, open this BlobIO for write access */\r\n writeable?: boolean;\r\n }): void;\r\n /** Read from a blob\r\n * @returns the contents of the requested byte range\r\n */\r\n read(args: {\r\n /** The number of bytes to read */\r\n numBytes: number;\r\n /** starting offset within the blob to read */\r\n offset: number;\r\n /** If present and of sufficient size, use this ArrayBuffer for the value. */\r\n blob?: ArrayBuffer;\r\n }): Uint8Array;\r\n /** Reposition this BlobIO to a new rowId\r\n * @note this BlobIO must be valid when this methods is called.\r\n */\r\n changeRow(row: number): void;\r\n /** Write to a blob */\r\n write(args: {\r\n /** The number of bytes to write */\r\n numBytes: number;\r\n /** starting offset within the blob to write */\r\n offset: number;\r\n /** the value to write */\r\n blob: ArrayBuffer;\r\n }): void;\r\n }\r\n\r\n /** Default transaction mode for SQLiteDbs.\r\n * @see https://www.sqlite.org/lang_transaction.html\r\n */\r\n export enum DefaultTxnMode {\r\n /** no default transaction is started. You must use BEGIN/COMMIT or SQLite will use implicit transactions */\r\n None = 0,\r\n /** A deferred transaction is started when the file is first opened. This is the default. */\r\n Deferred = 1,\r\n /** An immediate transaction is started when the file is first opened. */\r\n Immediate = 2,\r\n /** An exclusive transaction is started when the file is first opened. */\r\n Exclusive = 3\r\n }\r\n\r\n /** parameters common to opening or creating a new SQLiteDb */\r\n export interface OpenOrCreateParams {\r\n /** If true, do not require that the `be_Prop` table exist */\r\n rawSQLite?: boolean;\r\n /** @see immutable option at https://www.sqlite.org/c3ref/open.html */\r\n immutable?: boolean;\r\n /** Do not attempt to verify that the file is a valid sQLite file before opening. */\r\n skipFileCheck?: boolean;\r\n /** the default transaction mode\r\n * @see [[SQLiteDb.DefaultTxnMode]]\r\n */\r\n defaultTxn?: 0 | 1 | 2 | 3;\r\n /** see query parameters from 'URI Filenames' in https://www.sqlite.org/c3ref/open.html */\r\n queryParam?: string;\r\n }\r\n\r\n /** Parameters for opening an existing SQLiteDb */\r\n export interface OpenParams extends OpenOrCreateParams {\r\n /** use OpenMode.ReadWrite to open the file with write access */\r\n openMode: OpenMode;\r\n }\r\n\r\n /** Size of a SQLiteDb page in bytes */\r\n export interface PageSize {\r\n /** see https://www.sqlite.org/pragma.html#pragma_page_size */\r\n pageSize?: number;\r\n }\r\n\r\n /** Parameters for creating a new SQLiteDb */\r\n export type CreateParams = OpenOrCreateParams & PageSize;\r\n\r\n /** Arguments for `SqliteDb.withOpenDb` */\r\n export interface WithOpenDbArgs {\r\n /** The name of the database to open */\r\n dbName: string;\r\n /** either an object with the open parameters or just OpenMode value. */\r\n openMode?: OpenMode | SQLiteDb.OpenParams;\r\n /** @internal */\r\n container?: CloudSqlite.CloudContainer;\r\n }\r\n\r\n /** Arguments for `SQLiteDb.vacuum` */\r\n export interface VacuumDbArgs extends PageSize {\r\n /** if present, name of new file to [vacuum into](https://www.sqlite.org/lang_vacuum.html) */\r\n into?: LocalFileName;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"SQLiteDb.js","sourceRoot":"","sources":["../../src/SQLiteDb.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAGH,sDAAsE;AAEtE,+CAA4C;AAC5C,6CAA0C;AAC1C,uDAAoE;AAEpE,0BAA0B;AAC1B,0DAA0D;AAE1D;;GAEG;AACH,MAAa,QAAQ;IAArB;QACE,gBAAgB;QACA,aAAQ,GAAG,IAAI,uBAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;QACtD,0BAAqB,GAAG,IAAI,gCAAc,EAAmB,CAAC;IAuMxE,CAAC;IArMC,gBAAgB;IACT,MAAM,CAAC,YAAY;QACx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AC,UAAU,CAAC,eAAe,aAAa,EAAE,CAAC,CAAC;YAChD,MAAM,CAAC,CAAC;SACT;IACH,CAAC;IAED;;;;SAIK;IACE,sBAAsB,CAAC,GAAW,EAAE,SAAS,GAAG,IAAI;QACzD,MAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,GAAG,CAAC,CAAC;QACtC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,+BAA+B;IACxB,UAAU,CAAC,GAAW;QAC3B,MAAM,IAAI,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC;QAC9C,IAAI;YACF,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC;SACpB;gBAAS;YACR,IAAI,CAAC,OAAO,EAAE,CAAC;SAChB;IACH,CAAC;CACF;AA1MD,4BA0MC;AAED,cAAc;AACd,WAAiB,QAAQ;IAqDvB;;OAEG;IACH,IAAY,cASX;IATD,WAAY,cAAc;QACxB,4GAA4G;QAC5G,mDAAQ,CAAA;QACR,4FAA4F;QAC5F,2DAAY,CAAA;QACZ,yEAAyE;QACzE,6DAAa,CAAA;QACb,yEAAyE;QACzE,6DAAa,CAAA;IACf,CAAC,EATW,cAAc,GAAd,uBAAc,KAAd,uBAAc,QASzB;AAgDH,CAAC,EAjHgB,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAiHxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module SQLiteDb\n */\n\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\nimport { DbResult, IDisposable, OpenMode } from \"@itwin/core-bentley\";\nimport { LocalFileName } from \"@itwin/core-common\";\nimport { CloudSqlite } from \"./CloudSqlite\";\nimport { IModelHost } from \"./IModelHost\";\nimport { SqliteStatement, StatementCache } from \"./SqliteStatement\";\n\n// cspell:ignore savepoint\n/* eslint-disable @typescript-eslint/unified-signatures */\n\n/** A SQLiteDb file\n * @public\n */\nexport class SQLiteDb implements IDisposable {\n /** @internal */\n public readonly nativeDb = new IModelHost.platform.SQLiteDb();\n private _sqliteStatementCache = new StatementCache<SqliteStatement>();\n\n /** @internal */\n public static createBlobIO(): SQLiteDb.BlobIO {\n return new IModelHost.platform.BlobIO();\n }\n\n /** alias for closeDb. */\n public dispose(): void {\n this.closeDb();\n }\n\n /** Create a SQLiteDb\n * @param dbName The path to the SQLiteDb file to create.\n */\n public createDb(dbName: string): void;\n /** @beta */\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void;\n /** @internal */\n public createDb(dbName: string, container?: CloudSqlite.CloudContainer, params?: SQLiteDb.CreateParams): void {\n this.nativeDb.createDb(dbName, container, params);\n }\n\n /** Open a SQLiteDb.\n * @param dbName The path to the SQLiteDb file to open\n */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams): void;\n /**\n * @param container optional CloudContainer holding database\n * @beta\n */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void;\n\n /** @internal */\n public openDb(dbName: string, openMode: OpenMode | SQLiteDb.OpenParams, container?: CloudSqlite.CloudContainer): void {\n this.nativeDb.openDb(dbName, openMode, container);\n }\n\n /** Close SQLiteDb.\n * @param saveChanges if true, call `saveChanges` before closing db. Otherwise unsaved changes are abandoned.\n */\n public closeDb(saveChanges?: boolean): void {\n if (saveChanges && this.isOpen)\n this.saveChanges();\n this._sqliteStatementCache.clear();\n this.nativeDb.closeDb();\n }\n\n /** Returns true if this SQLiteDb is open */\n public get isOpen(): boolean { return this.nativeDb.isOpen(); }\n\n /** Returns true if this SQLiteDb is open readonly */\n public get isReadonly(): boolean { return this.nativeDb.isReadonly(); }\n\n /**\n * Open a database, perform an operation, then close the database.\n *\n * Details:\n * - if database is open, throw an error\n * - open a database\n * - call a function with the database opened. If it is async, await its return.\n * - if function throws, abandon all changes, close database, and rethrow\n * - save all changes\n * - close the database\n * @return value from operation\n */\n public withOpenDb<T>(args: SQLiteDb.WithOpenDbArgs, operation: () => T): T {\n if (this.isOpen)\n throw new Error(\"database is already open\");\n\n const save = () => this.closeDb(true), abandon = () => this.closeDb(false);\n this.openDb(args.dbName, args.openMode ?? OpenMode.Readonly, args.container);\n try {\n const result = operation();\n result instanceof Promise ? result.then(save, abandon) : save();\n return result;\n } catch (e) {\n abandon();\n throw e;\n }\n }\n\n /**\n * Perform an operation on a database in a CloudContainer with the write lock held.\n *\n * Details:\n * - acquire the write lock on a CloudContainer\n * - call `withOpenDb` with openMode `ReadWrite`\n * - upload changes\n * - release the write lock\n * @param args arguments to lock the container and open the database\n * @param operation an operation performed on the database with the write lock held.\n * @return value from operation\n * @internal\n */\n public async withLockedContainer<T>(args: CloudSqlite.LockAndOpenArgs, operation: () => T) {\n return CloudSqlite.withWriteLock(args.user, args.container, () => this.withOpenDb({ ...args, openMode: OpenMode.ReadWrite }, operation), args.busyHandler);\n }\n\n /** vacuum this database\n * @see https://www.sqlite.org/lang_vacuum.html\n */\n public vacuum(args?: SQLiteDb.VacuumDbArgs) {\n this.nativeDb.vacuum(args);\n }\n\n /** Commit the outermost transaction, writing changes to the file. Then, restart the transaction. */\n public saveChanges(): void {\n this.nativeDb.saveChanges();\n }\n\n /** Abandon (cancel) the outermost transaction, discarding all changes since last save. Then, restart the transaction. */\n public abandonChanges(): void {\n this.nativeDb.abandonChanges();\n }\n\n /**\n * Use a prepared SQL statement, potentially from the statement cache. If the requested statement doesn't exist\n * in the statement cache, a new statement is prepared. After the callback completes, the statement is reset and saved\n * in the statement cache so it can be reused in the future. Use this method for SQL statements that will be\n * reused often and are expensive to prepare. The statement cache holds the most recently used statements, discarding\n * the oldest statements as it fills. For statements you don't intend to reuse, instead use [[withSqliteStatement]].\n * @param sql The SQLite SQL statement to execute\n * @param callback the callback to invoke on the prepared statement\n * @returns the value returned by `callback`.\n */\n public withPreparedSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\n const stmt = this._sqliteStatementCache.findAndRemove(sql) ?? this.prepareSqliteStatement(sql);\n const release = () => this._sqliteStatementCache.addOrDispose(stmt);\n try {\n const val = callback(stmt);\n val instanceof Promise ? val.then(release, release) : release();\n return val;\n } catch (err) {\n release();\n throw err;\n }\n }\n\n /**\n * Prepared and execute a callback on a SQL statement. After the callback completes the statement is disposed.\n * Use this method for SQL statements are either not expected to be reused, or are not expensive to prepare.\n * For statements that will be reused often, instead use [[withPreparedSqliteStatement]].\n * @param sql The SQLite SQL statement to execute\n * @param callback the callback to invoke on the prepared statement\n * @returns the value returned by `callback`.\n */\n public withSqliteStatement<T>(sql: string, callback: (stmt: SqliteStatement) => T): T {\n const stmt = this.prepareSqliteStatement(sql);\n const release = () => stmt.dispose();\n try {\n const val = callback(stmt);\n val instanceof Promise ? val.then(release, release) : release();\n return val;\n } catch (err) {\n release();\n throw err;\n }\n }\n\n /**\n * Perform an operation on this database within a [savepoint](https://www.sqlite.org/lang_savepoint.html). If the operation completes successfully, the\n * changes remain in the current transaction. If the operation throws an exception, the savepoint is rolled back\n * and all changes to the database from this method are reversed, leaving the transaction exactly as it was before this method.\n */\n public withSavePoint(savePointName: string, operation: () => void) {\n if (this.isReadonly)\n throw new Error(\"database is readonly\");\n\n this.executeSQL(`SAVEPOINT ${savePointName}`);\n try {\n operation();\n this.executeSQL(`RELEASE ${savePointName}`);\n } catch (e) {\n this.executeSQL(`ROLLBACK TO ${savePointName}`);\n throw e;\n }\n }\n\n /** Prepare an SQL statement.\n * @param sql The SQLite SQL statement to prepare\n * @param logErrors Determine if errors are logged or not\n * @internal\n */\n public prepareSqliteStatement(sql: string, logErrors = true): SqliteStatement {\n const stmt = new SqliteStatement(sql);\n stmt.prepare(this.nativeDb, logErrors);\n return stmt;\n }\n\n /** execute an SQL statement */\n public executeSQL(sql: string): DbResult {\n const stmt = this.prepareSqliteStatement(sql);\n try {\n return stmt.step();\n } finally {\n stmt.dispose();\n }\n }\n}\n\n/** @public */\nexport namespace SQLiteDb {\n /** interface for reading and writing to a blob in a SQLiteDb\n * @internal\n */\n export interface BlobIO {\n /** Close this BlobIO if it is opened.\n * @note this BlobIO *may* be reused after this call by calling `open` again.\n */\n close(): void;\n /** get the total number of bytes in the blob */\n getNumBytes(): number;\n /** @return true if this BlobIO was successfully opened and may be use to read or write the blob */\n isValid(): boolean;\n /** Open this BlobIO against a table/row/column in a Db */\n open(\n /** The database for the blob */\n db: IModelJsNative.AnyDb,\n args: {\n /** the name of the table for the blob*/\n tableName: string;\n /** the name of the column for the blob */\n columnName: string;\n /** The rowId of the blob */\n row: number;\n /** If true, open this BlobIO for write access */\n writeable?: boolean;\n }): void;\n /** Read from a blob\n * @returns the contents of the requested byte range\n */\n read(args: {\n /** The number of bytes to read */\n numBytes: number;\n /** starting offset within the blob to read */\n offset: number;\n /** If present and of sufficient size, use this ArrayBuffer for the value. */\n blob?: ArrayBuffer;\n }): Uint8Array;\n /** Reposition this BlobIO to a new rowId\n * @note this BlobIO must be valid when this methods is called.\n */\n changeRow(row: number): void;\n /** Write to a blob */\n write(args: {\n /** The number of bytes to write */\n numBytes: number;\n /** starting offset within the blob to write */\n offset: number;\n /** the value to write */\n blob: ArrayBuffer;\n }): void;\n }\n\n /** Default transaction mode for SQLiteDbs.\n * @see https://www.sqlite.org/lang_transaction.html\n */\n export enum DefaultTxnMode {\n /** no default transaction is started. You must use BEGIN/COMMIT or SQLite will use implicit transactions */\n None = 0,\n /** A deferred transaction is started when the file is first opened. This is the default. */\n Deferred = 1,\n /** An immediate transaction is started when the file is first opened. */\n Immediate = 2,\n /** An exclusive transaction is started when the file is first opened. */\n Exclusive = 3\n }\n\n /** parameters common to opening or creating a new SQLiteDb */\n export interface OpenOrCreateParams {\n /** If true, do not require that the `be_Prop` table exist */\n rawSQLite?: boolean;\n /** @see immutable option at https://www.sqlite.org/c3ref/open.html */\n immutable?: boolean;\n /** Do not attempt to verify that the file is a valid sQLite file before opening. */\n skipFileCheck?: boolean;\n /** the default transaction mode\n * @see [[SQLiteDb.DefaultTxnMode]]\n */\n defaultTxn?: 0 | 1 | 2 | 3;\n /** see query parameters from 'URI Filenames' in https://www.sqlite.org/c3ref/open.html */\n queryParam?: string;\n }\n\n /** Parameters for opening an existing SQLiteDb */\n export interface OpenParams extends OpenOrCreateParams {\n /** use OpenMode.ReadWrite to open the file with write access */\n openMode: OpenMode;\n }\n\n /** Size of a SQLiteDb page in bytes */\n export interface PageSize {\n /** see https://www.sqlite.org/pragma.html#pragma_page_size */\n pageSize?: number;\n }\n\n /** Parameters for creating a new SQLiteDb */\n export type CreateParams = OpenOrCreateParams & PageSize;\n\n /** Arguments for `SqliteDb.withOpenDb` */\n export interface WithOpenDbArgs {\n /** The name of the database to open */\n dbName: string;\n /** either an object with the open parameters or just OpenMode value. */\n openMode?: OpenMode | SQLiteDb.OpenParams;\n /** @internal */\n container?: CloudSqlite.CloudContainer;\n }\n\n /** Arguments for `SQLiteDb.vacuum` */\n export interface VacuumDbArgs extends PageSize {\n /** if present, name of new file to [vacuum into](https://www.sqlite.org/lang_vacuum.html) */\n into?: LocalFileName;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"Schema.js","sourceRoot":"","sources":["../../src/Schema.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAAmD;AACnD,oDAAiD;AACjD,mDAAgD;AAEhD;;GAEG;AACH,MAAa,MAAM;IACjB;;;;OAIG;IACI,MAAM,KAAK,UAAU,KAAa,MAAM,IAAI,KAAK,CAAC,0CAA0C,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IAElH;;;OAGG;IACI,MAAM,KAAK,uBAAuB,KAAc,OAAO,KAAK,CAAC,CAAC,CAAC;IAEtE;;;;;;OAMG;IACI,MAAM,CAAC,cAAc,CAAC,aA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AC,mBAAmB,CAAC,UAAkB,IAA+B,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC;;AA/B1H,0BAAkB,GAAG,IAAI,GAAG,EAAyB,CAAC;AADnE,0BAAO","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Schema\r\n */\r\n\r\nimport { IModelStatus } from \"@itwin/core-bentley\";\r\nimport { IModelError } from \"@itwin/core-common\";\r\nimport { ClassRegistry } from \"./ClassRegistry\";\r\n\r\n/** Base class for all schema classes - see [working with schemas and elements in TypeScript]($docs/learning/backend/SchemasAndElementsInTypeScript.md).\r\n * @public\r\n */\r\nexport class Schema {\r\n /** The name of the BIS schema handled by this Schema.\r\n * @note Every subclass of Schema ** MUST ** override this method to identify its BIS schema.\r\n * Failure to do so will ordinarily result in an error when the schema is registered, since there may only\r\n * be one JavaScript class for a given BIS schema (usually the errant schema will collide with its superclass.)\r\n */\r\n public static get schemaName(): string { throw new Error(`you must override static schemaName in ${this.name}`); }\r\n\r\n /** if true, this Schema is a proxy for a missing Domain marked with the `BisCore.SchemaHasBehavior` customAttribute.\r\n * Classes generated for this Schema will disallow protected operations.\r\n * @internal\r\n */\r\n public static get missingRequiredBehavior(): boolean { return false; }\r\n\r\n /** Get a semver-compatible string from a padded version string.\r\n * works on unpadded version strings as well\r\n * if there is no write version, it will be added\r\n * @example Schema.toSemverString(\"1.02.03\") === \"1.2.3\"\r\n * @example Schema.toSemverString(\"1.01\") === \"1.0.1\" // write version was added\r\n * @beta\r\n */\r\n public static toSemverString(paddedVersion: string): string {\r\n const tuple = paddedVersion.split(\".\").map(Number);\r\n const noWriteVersion = tuple.length === 2;\r\n if (noWriteVersion)\r\n tuple.splice(1, 0, 0); // insert 0 before the second element\r\n return tuple.join(\".\");\r\n }\r\n\r\n /** Schemas may not be instantiated. The method is not private only because that precludes subclassing. It throws an\r\n * error if it is ever called.\r\n * @internal\r\n */\r\n protected constructor() { throw new Error(`cannot create an instance of a Schema ${this.constructor.name}`); }\r\n}\r\n\r\n/** Manages registered schemas\r\n * @public\r\n */\r\nexport class Schemas {\r\n private static readonly _registeredSchemas = new Map<string, typeof Schema>();\r\n private constructor() { } // this is a singleton\r\n\r\n /** Register a schema prior to using it.\r\n * @throws [[IModelError]] if a schema of the same name is already registered.\r\n */\r\n public static registerSchema(schema: typeof Schema) {\r\n const key = schema.schemaName.toLowerCase();\r\n if (this.getRegisteredSchema(key))\r\n throw new IModelError(IModelStatus.DuplicateName, `Schema \"${schema.schemaName}\" is already registered`);\r\n this._registeredSchemas.set(key, schema);\r\n }\r\n\r\n /** Unregister a schema, by name, if one is already registered.\r\n * This function is not normally needed, but is useful for cases where a generated *proxy* schema needs to be replaced by the *real* schema.\r\n * @param schemaName Name of the schema to unregister\r\n * @return true if the schema was unregistered\r\n * @internal\r\n */\r\n public static unregisterSchema(schemaName: string): boolean {\r\n const schema = this.getRegisteredSchema(schemaName);\r\n if (undefined !== schema)\r\n ClassRegistry.unregisterClassesFrom(schema);\r\n\r\n return this._registeredSchemas.delete(schemaName.toLowerCase());\r\n }\r\n\r\n /** Look up a previously registered schema\r\n * @param schemaName The name of the schema\r\n * @returns the previously registered schema or undefined if not registered.\r\n */\r\n public static getRegisteredSchema(schemaName: string): typeof Schema | undefined { return this._registeredSchemas.get(schemaName.toLowerCase()); }\r\n}\r\n"]}
1
+ {"version":3,"file":"Schema.js","sourceRoot":"","sources":["../../src/Schema.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAAmD;AACnD,oDAAiD;AACjD,mDAAgD;AAEhD;;GAEG;AACH,MAAa,MAAM;IACjB;;;;OAIG;IACI,MAAM,KAAK,UAAU,KAAa,MAAM,IAAI,KAAK,CAAC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MAAM;YACtB,6BAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;QAE9C,OAAO,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;IAClE,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,mBAAmB,CAAC,UAAkB,IAA+B,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC;;AA/B1H,0BAAkB,GAAG,IAAI,GAAG,EAAyB,CAAC;AADnE,0BAAO","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Schema\n */\n\nimport { IModelStatus } from \"@itwin/core-bentley\";\nimport { IModelError } from \"@itwin/core-common\";\nimport { ClassRegistry } from \"./ClassRegistry\";\n\n/** Base class for all schema classes - see [working with schemas and elements in TypeScript]($docs/learning/backend/SchemasAndElementsInTypeScript.md).\n * @public\n */\nexport class Schema {\n /** The name of the BIS schema handled by this Schema.\n * @note Every subclass of Schema ** MUST ** override this method to identify its BIS schema.\n * Failure to do so will ordinarily result in an error when the schema is registered, since there may only\n * be one JavaScript class for a given BIS schema (usually the errant schema will collide with its superclass.)\n */\n public static get schemaName(): string { throw new Error(`you must override static schemaName in ${this.name}`); }\n\n /** if true, this Schema is a proxy for a missing Domain marked with the `BisCore.SchemaHasBehavior` customAttribute.\n * Classes generated for this Schema will disallow protected operations.\n * @internal\n */\n public static get missingRequiredBehavior(): boolean { return false; }\n\n /** Get a semver-compatible string from a padded version string.\n * works on unpadded version strings as well\n * if there is no write version, it will be added\n * @example Schema.toSemverString(\"1.02.03\") === \"1.2.3\"\n * @example Schema.toSemverString(\"1.01\") === \"1.0.1\" // write version was added\n * @beta\n */\n public static toSemverString(paddedVersion: string): string {\n const tuple = paddedVersion.split(\".\").map(Number);\n const noWriteVersion = tuple.length === 2;\n if (noWriteVersion)\n tuple.splice(1, 0, 0); // insert 0 before the second element\n return tuple.join(\".\");\n }\n\n /** Schemas may not be instantiated. The method is not private only because that precludes subclassing. It throws an\n * error if it is ever called.\n * @internal\n */\n protected constructor() { throw new Error(`cannot create an instance of a Schema ${this.constructor.name}`); }\n}\n\n/** Manages registered schemas\n * @public\n */\nexport class Schemas {\n private static readonly _registeredSchemas = new Map<string, typeof Schema>();\n private constructor() { } // this is a singleton\n\n /** Register a schema prior to using it.\n * @throws [[IModelError]] if a schema of the same name is already registered.\n */\n public static registerSchema(schema: typeof Schema) {\n const key = schema.schemaName.toLowerCase();\n if (this.getRegisteredSchema(key))\n throw new IModelError(IModelStatus.DuplicateName, `Schema \"${schema.schemaName}\" is already registered`);\n this._registeredSchemas.set(key, schema);\n }\n\n /** Unregister a schema, by name, if one is already registered.\n * This function is not normally needed, but is useful for cases where a generated *proxy* schema needs to be replaced by the *real* schema.\n * @param schemaName Name of the schema to unregister\n * @return true if the schema was unregistered\n * @internal\n */\n public static unregisterSchema(schemaName: string): boolean {\n const schema = this.getRegisteredSchema(schemaName);\n if (undefined !== schema)\n ClassRegistry.unregisterClassesFrom(schema);\n\n return this._registeredSchemas.delete(schemaName.toLowerCase());\n }\n\n /** Look up a previously registered schema\n * @param schemaName The name of the schema\n * @returns the previously registered schema or undefined if not registered.\n */\n public static getRegisteredSchema(schemaName: string): typeof Schema | undefined { return this._registeredSchemas.get(schemaName.toLowerCase()); }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ServerBasedLocks.js","sourceRoot":"","sources":["../../src/ServerBasedLocks.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F;;GAEG;AAEH,sDAAkG;AAClG,oDAAyD;AACzD,yDAAwD;AAExD,6CAA0C;AAC1C,yCAAsC;AAoBtC,gBAAgB;AAChB,MAAa,gBAAgB;IAC3B,IAAW,aAAa,KAAK,OAAO,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,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IACrC,CAAC;IAED,wGAAwG;IACjG,iBAAiB,CAAC,EAAc;QACrC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,4BAAS,CAAC,SAAS,gCAAwB,CAAC;QAChE,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;IAC5B,CAAC;IAED,yDAAyD;IACzD,IAAY,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAElF,uGAAuG;IAChG,kBAAkB,CAAC,EAAc,EAAE,IAAY,EAAE,SAAiB;QACvE,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC;YACxD,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,WAAW,EAAE,8BAA8B,IAAI,QAAQ,SAAS,QAAQ,EAAE,GAAG,CAAC,CAAC;IACtH,CAAC;IAED,kGAAkG;IAC3F,eAAe,CAAC,EAAc,EAAE,IAAY,EAAE,SAAiB;QACpE,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,WAAW,EAAE,2BAA2B,IAAI,QAAQ,SAAS,QAAQ,EAAE,GAAG,CAAC,CAAC;IACnH,CAAC;CAEF;AAlLD,4CAkLC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\n/** @packageDocumentation\r\n * @module iModels\r\n */\r\n\r\nimport { DbResult, Id64, Id64Arg, Id64String, IModelStatus, OpenMode } from \"@itwin/core-bentley\";\r\nimport { IModel, IModelError } from \"@itwin/core-common\";\r\nimport { LockMap, LockState } from \"./BackendHubAccess\";\r\nimport { BriefcaseDb, LockControl } from \"./IModelDb\";\r\nimport { IModelHost } from \"./IModelHost\";\r\nimport { SQLiteDb } from \"./SQLiteDb\";\r\n\r\n/**\r\n * Both the Model and Parent of an element are considered \"owners\" of their member elements. That means:\r\n * 1) they must hold at least a shared lock before an exclusive lock can be acquired for their members\r\n * 2) if they hold an exclusive lock, then all of their members are exclusively locked implicitly.\r\n * @internal\r\n */\r\nexport interface ElementOwners {\r\n readonly modelId: Id64String;\r\n readonly parentId: Id64String | undefined;\r\n}\r\n\r\n// eslint-disable-next-line no-restricted-syntax\r\nconst enum LockOrigin {\r\n Acquired = 0,\r\n NewElement = 1,\r\n Discovered = 2,\r\n}\r\n\r\n/** @internal */\r\nexport class ServerBasedLocks implements LockControl {\r\n public get isServerBased() { return true; }\r\n protected readonly lockDb = new SQLiteDb();\r\n protected readonly briefcase: BriefcaseDb;\r\n\r\n public constructor(iModel: BriefcaseDb) {\r\n this.briefcase = iModel;\r\n const dbName = `${iModel.nativeDb.getTempFileBaseName()}-locks`;\r\n try {\r\n this.lockDb.openDb(dbName, OpenMode.ReadWrite);\r\n } catch (_e) {\r\n this.lockDb.createDb(dbName);\r\n this.lockDb.executeSQL(\"CREATE TABLE locks(id INTEGER PRIMARY KEY NOT NULL,state INTEGER NOT NULL,origin INTEGER)\");\r\n this.lockDb.saveChanges();\r\n }\r\n }\r\n\r\n public close() {\r\n if (this.lockDb.isOpen)\r\n this.lockDb.closeDb();\r\n }\r\n\r\n private getOwners(id: Id64String): ElementOwners {\r\n return this.briefcase.withPreparedSqliteStatement(\"SELECT ModelId,ParentId FROM bis_Element WHERE id=?\", (stmt) => {\r\n stmt.bindId(1, id);\r\n const rc = stmt.step();\r\n if (DbResult.BE_SQLITE_ROW !== rc)\r\n throw new IModelError(rc, `element ${id} not found`);\r\n\r\n return { modelId: stmt.getValueId(0), parentId: stmt.getValueId(1) };\r\n });\r\n }\r\n\r\n private getLockState(id?: Id64String): LockState | undefined {\r\n return (id === undefined || !Id64.isValid(id)) ? undefined : this.lockDb.withPreparedSqliteStatement(\"SELECT state FROM locks WHERE id=?\", (stmt) => {\r\n stmt.bindId(1, id);\r\n return (DbResult.BE_SQLITE_ROW === stmt.step()) ? stmt.getValueInteger(0) : undefined;\r\n });\r\n }\r\n\r\n /** Clear the cache of locally held locks.\r\n * Note: does *not* release locks from server.\r\n */\r\n private clearAllLocks() {\r\n this.lockDb.executeSQL(\"DELETE FROM locks\");\r\n this.lockDb.saveChanges();\r\n }\r\n\r\n /** only for tests */\r\n public getLockCount(state: LockState): number {\r\n return this.lockDb.withSqliteStatement(\"SELECT count(*) FROM locks WHERE state=?\", (stmt) => {\r\n stmt.bindInteger(1, state);\r\n stmt.step();\r\n return stmt.getValueInteger(0);\r\n });\r\n }\r\n\r\n public async releaseAllLocks(): Promise<void> {\r\n await IModelHost.hubAccess.releaseAllLocks(this.briefcase); // throws if unsuccessful\r\n this.clearAllLocks();\r\n }\r\n\r\n private insertLock(id: Id64String, state: LockState, origin: LockOrigin): true {\r\n this.lockDb.withPreparedSqliteStatement(\"INSERT INTO locks(id,state,origin) VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,origin=excluded.origin\", (stmt) => {\r\n stmt.bindId(1, id);\r\n stmt.bindInteger(2, state);\r\n stmt.bindInteger(3, origin);\r\n const rc = stmt.step();\r\n if (DbResult.BE_SQLITE_DONE !== rc)\r\n throw new IModelError(rc, \"can't insert lock into database\");\r\n });\r\n return true;\r\n }\r\n\r\n private ownerHoldsExclusiveLock(id: Id64String | undefined): boolean {\r\n if (id === undefined || id === IModel.rootSubjectId)\r\n return false; // has no owners\r\n\r\n const { modelId, parentId } = this.getOwners(id);\r\n if (this.getLockState(modelId) === LockState.Exclusive || this.getLockState(parentId) === LockState.Exclusive)\r\n return true;\r\n\r\n // see if this model is exclusively locked by one of its owners. If so, save that fact on modelId so future tests won't have to descend.\r\n if (this.ownerHoldsExclusiveLock(modelId))\r\n return this.insertLock(modelId, LockState.Exclusive, LockOrigin.Discovered);\r\n\r\n // see if the parent is exclusively locked by one of its owners. If so, save that fact on parentId so future tests won't have to descend.\r\n return this.ownerHoldsExclusiveLock(parentId) ? this.insertLock(parentId!, LockState.Exclusive, LockOrigin.Discovered) : false; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n }\r\n\r\n /** Determine whether an the exclusive lock is already held by an element (or one of its owners) */\r\n public holdsExclusiveLock(id: Id64String): boolean {\r\n // see if we hold the exclusive lock. or if one of the element's owners is exclusively locked (recursively)\r\n return this.getLockState(id) === LockState.Exclusive || this.ownerHoldsExclusiveLock(id);\r\n }\r\n\r\n public holdsSharedLock(id: Id64String): boolean {\r\n const state = this.getLockState(id);\r\n // see if we hold shared or exclusive lock, or if an owner has exclusive lock. If so we implicitly have shared lock, but owner holding shared lock doesn't help.\r\n return (state === LockState.Shared || state === LockState.Exclusive) || this.ownerHoldsExclusiveLock(id);\r\n }\r\n\r\n /** if the shared lock on the element supplied is not already held, add it to the set of shared locks required. Then, check owners. */\r\n private addSharedLock(id: Id64String | undefined, locks: Set<Id64String>) {\r\n // if the id is not valid, or of the lock is already in the set, or if we already hold a shared lock, we're done\r\n // Note: if we hold a shared lock, it is guaranteed that we also hold all required shared locks on owners.\r\n if (id === undefined || !Id64.isValid(id) || locks.has(id) || this.holdsSharedLock(id))\r\n return;\r\n\r\n locks.add(id); // add to set of needed shared locks\r\n this.addOwnerSharedLocks(id, locks); // check parent models and groups\r\n }\r\n\r\n /** add owners (recursively) of an element to a list of required shared locks, if not already held. */\r\n private addOwnerSharedLocks(id: Id64String, locks: Set<Id64String>) {\r\n const el = this.getOwners(id);\r\n this.addSharedLock(el.parentId, locks); // if this element is in a group\r\n this.addSharedLock(el.modelId, locks); // check its model\r\n }\r\n\r\n /** attempt to acquire all necessary locks for a set of elements */\r\n private async acquireAllLocks(locks: LockMap) {\r\n if (locks.size === 0) // no locks are required.\r\n return;\r\n\r\n const sharedLocks = new Set<Id64String>();\r\n for (const lock of locks)\r\n this.addOwnerSharedLocks(lock[0], sharedLocks);\r\n\r\n for (const shared of sharedLocks) {\r\n if (!locks.has(shared)) // we may already be asking for exclusive lock\r\n locks.set(shared, LockState.Shared);\r\n }\r\n\r\n await IModelHost.hubAccess.acquireLocks(this.briefcase, locks); // throws if unsuccessful\r\n for (const lock of locks)\r\n this.insertLock(lock[0], lock[1], LockOrigin.Acquired);\r\n this.lockDb.saveChanges();\r\n }\r\n\r\n public async acquireLocks(arg: { shared?: Id64Arg, exclusive?: Id64Arg }): Promise<void> {\r\n const locks = new Map<Id64String, LockState>();\r\n if (arg.shared) {\r\n for (const id of Id64.iterable(arg.shared)) {\r\n if (!this.holdsSharedLock(id))\r\n locks.set(id, LockState.Shared);\r\n }\r\n }\r\n if (arg.exclusive) {\r\n for (const id of Id64.iterable(arg.exclusive)) {\r\n if (!this.holdsExclusiveLock(id))\r\n locks.set(id, LockState.Exclusive);\r\n }\r\n }\r\n return this.acquireAllLocks(locks);\r\n }\r\n\r\n /** When an element is newly created in a session, we hold the lock on it implicitly. Save that fact. */\r\n public elementWasCreated(id: Id64String) {\r\n this.insertLock(id, LockState.Exclusive, LockOrigin.NewElement);\r\n this.lockDb.saveChanges();\r\n }\r\n\r\n /** locks are not necessary during change propagation. */\r\n private get _locksAreRequired() { return !this.briefcase.txns.isIndirectChanges; }\r\n\r\n /** throw if locks are currently required and the exclusive lock is not held on the supplied element */\r\n public checkExclusiveLock(id: Id64String, type: string, operation: string) {\r\n if (this._locksAreRequired && !this.holdsExclusiveLock(id))\r\n throw new IModelError(IModelStatus.LockNotHeld, `exclusive lock not held on ${type} for ${operation} (id=${id})`);\r\n }\r\n\r\n /** throw if locks are currently required and a shared lock is not held on the supplied element */\r\n public checkSharedLock(id: Id64String, type: string, operation: string) {\r\n if (this._locksAreRequired && !this.holdsSharedLock(id))\r\n throw new IModelError(IModelStatus.LockNotHeld, `shared lock not held on ${type} for ${operation} (id=${id})`);\r\n }\r\n\r\n}\r\n\r\n"]}
1
+ {"version":3,"file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,KAAK,MAAM,EAAE,IAAI,mBAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;gBAC7C,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC;oBAC9B,KAAK,CAAC,GAAG,CAAC,EAAE,EAAE,4BAAS,CAAC,SAAS,CAAC,CAAC;aACtC;SACF;QACD,OAAO,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IACrC,CAAC;IAED,wGAAwG;IACjG,iBAAiB,CAAC,EAAc;QACrC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,4BAAS,CAAC,SAAS,gCAAwB,CAAC;QAChE,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;IAC5B,CAAC;IAED,yDAAyD;IACzD,IAAY,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAElF,uGAAuG;IAChG,kBAAkB,CAAC,EAAc,EAAE,IAAY,EAAE,SAAiB;QACvE,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC;YACxD,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,WAAW,EAAE,8BAA8B,IAAI,QAAQ,SAAS,QAAQ,EAAE,GAAG,CAAC,CAAC;IACtH,CAAC;IAED,kGAAkG;IAC3F,eAAe,CAAC,EAAc,EAAE,IAAY,EAAE,SAAiB;QACpE,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,WAAW,EAAE,2BAA2B,IAAI,QAAQ,SAAS,QAAQ,EAAE,GAAG,CAAC,CAAC;IACnH,CAAC;CAEF;AAlLD,4CAkLC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n\n/** @packageDocumentation\n * @module iModels\n */\n\nimport { DbResult, Id64, Id64Arg, Id64String, IModelStatus, OpenMode } from \"@itwin/core-bentley\";\nimport { IModel, IModelError } from \"@itwin/core-common\";\nimport { LockMap, LockState } from \"./BackendHubAccess\";\nimport { BriefcaseDb, LockControl } from \"./IModelDb\";\nimport { IModelHost } from \"./IModelHost\";\nimport { SQLiteDb } from \"./SQLiteDb\";\n\n/**\n * Both the Model and Parent of an element are considered \"owners\" of their member elements. That means:\n * 1) they must hold at least a shared lock before an exclusive lock can be acquired for their members\n * 2) if they hold an exclusive lock, then all of their members are exclusively locked implicitly.\n * @internal\n */\nexport interface ElementOwners {\n readonly modelId: Id64String;\n readonly parentId: Id64String | undefined;\n}\n\n// eslint-disable-next-line no-restricted-syntax\nconst enum LockOrigin {\n Acquired = 0,\n NewElement = 1,\n Discovered = 2,\n}\n\n/** @internal */\nexport class ServerBasedLocks implements LockControl {\n public get isServerBased() { return true; }\n protected readonly lockDb = new SQLiteDb();\n protected readonly briefcase: BriefcaseDb;\n\n public constructor(iModel: BriefcaseDb) {\n this.briefcase = iModel;\n const dbName = `${iModel.nativeDb.getTempFileBaseName()}-locks`;\n try {\n this.lockDb.openDb(dbName, OpenMode.ReadWrite);\n } catch (_e) {\n this.lockDb.createDb(dbName);\n this.lockDb.executeSQL(\"CREATE TABLE locks(id INTEGER PRIMARY KEY NOT NULL,state INTEGER NOT NULL,origin INTEGER)\");\n this.lockDb.saveChanges();\n }\n }\n\n public close() {\n if (this.lockDb.isOpen)\n this.lockDb.closeDb();\n }\n\n private getOwners(id: Id64String): ElementOwners {\n return this.briefcase.withPreparedSqliteStatement(\"SELECT ModelId,ParentId FROM bis_Element WHERE id=?\", (stmt) => {\n stmt.bindId(1, id);\n const rc = stmt.step();\n if (DbResult.BE_SQLITE_ROW !== rc)\n throw new IModelError(rc, `element ${id} not found`);\n\n return { modelId: stmt.getValueId(0), parentId: stmt.getValueId(1) };\n });\n }\n\n private getLockState(id?: Id64String): LockState | undefined {\n return (id === undefined || !Id64.isValid(id)) ? undefined : this.lockDb.withPreparedSqliteStatement(\"SELECT state FROM locks WHERE id=?\", (stmt) => {\n stmt.bindId(1, id);\n return (DbResult.BE_SQLITE_ROW === stmt.step()) ? stmt.getValueInteger(0) : undefined;\n });\n }\n\n /** Clear the cache of locally held locks.\n * Note: does *not* release locks from server.\n */\n private clearAllLocks() {\n this.lockDb.executeSQL(\"DELETE FROM locks\");\n this.lockDb.saveChanges();\n }\n\n /** only for tests */\n public getLockCount(state: LockState): number {\n return this.lockDb.withSqliteStatement(\"SELECT count(*) FROM locks WHERE state=?\", (stmt) => {\n stmt.bindInteger(1, state);\n stmt.step();\n return stmt.getValueInteger(0);\n });\n }\n\n public async releaseAllLocks(): Promise<void> {\n await IModelHost.hubAccess.releaseAllLocks(this.briefcase); // throws if unsuccessful\n this.clearAllLocks();\n }\n\n private insertLock(id: Id64String, state: LockState, origin: LockOrigin): true {\n this.lockDb.withPreparedSqliteStatement(\"INSERT INTO locks(id,state,origin) VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,origin=excluded.origin\", (stmt) => {\n stmt.bindId(1, id);\n stmt.bindInteger(2, state);\n stmt.bindInteger(3, origin);\n const rc = stmt.step();\n if (DbResult.BE_SQLITE_DONE !== rc)\n throw new IModelError(rc, \"can't insert lock into database\");\n });\n return true;\n }\n\n private ownerHoldsExclusiveLock(id: Id64String | undefined): boolean {\n if (id === undefined || id === IModel.rootSubjectId)\n return false; // has no owners\n\n const { modelId, parentId } = this.getOwners(id);\n if (this.getLockState(modelId) === LockState.Exclusive || this.getLockState(parentId) === LockState.Exclusive)\n return true;\n\n // see if this model is exclusively locked by one of its owners. If so, save that fact on modelId so future tests won't have to descend.\n if (this.ownerHoldsExclusiveLock(modelId))\n return this.insertLock(modelId, LockState.Exclusive, LockOrigin.Discovered);\n\n // see if the parent is exclusively locked by one of its owners. If so, save that fact on parentId so future tests won't have to descend.\n return this.ownerHoldsExclusiveLock(parentId) ? this.insertLock(parentId!, LockState.Exclusive, LockOrigin.Discovered) : false; // eslint-disable-line @typescript-eslint/no-non-null-assertion\n }\n\n /** Determine whether an the exclusive lock is already held by an element (or one of its owners) */\n public holdsExclusiveLock(id: Id64String): boolean {\n // see if we hold the exclusive lock. or if one of the element's owners is exclusively locked (recursively)\n return this.getLockState(id) === LockState.Exclusive || this.ownerHoldsExclusiveLock(id);\n }\n\n public holdsSharedLock(id: Id64String): boolean {\n const state = this.getLockState(id);\n // see if we hold shared or exclusive lock, or if an owner has exclusive lock. If so we implicitly have shared lock, but owner holding shared lock doesn't help.\n return (state === LockState.Shared || state === LockState.Exclusive) || this.ownerHoldsExclusiveLock(id);\n }\n\n /** if the shared lock on the element supplied is not already held, add it to the set of shared locks required. Then, check owners. */\n private addSharedLock(id: Id64String | undefined, locks: Set<Id64String>) {\n // if the id is not valid, or of the lock is already in the set, or if we already hold a shared lock, we're done\n // Note: if we hold a shared lock, it is guaranteed that we also hold all required shared locks on owners.\n if (id === undefined || !Id64.isValid(id) || locks.has(id) || this.holdsSharedLock(id))\n return;\n\n locks.add(id); // add to set of needed shared locks\n this.addOwnerSharedLocks(id, locks); // check parent models and groups\n }\n\n /** add owners (recursively) of an element to a list of required shared locks, if not already held. */\n private addOwnerSharedLocks(id: Id64String, locks: Set<Id64String>) {\n const el = this.getOwners(id);\n this.addSharedLock(el.parentId, locks); // if this element is in a group\n this.addSharedLock(el.modelId, locks); // check its model\n }\n\n /** attempt to acquire all necessary locks for a set of elements */\n private async acquireAllLocks(locks: LockMap) {\n if (locks.size === 0) // no locks are required.\n return;\n\n const sharedLocks = new Set<Id64String>();\n for (const lock of locks)\n this.addOwnerSharedLocks(lock[0], sharedLocks);\n\n for (const shared of sharedLocks) {\n if (!locks.has(shared)) // we may already be asking for exclusive lock\n locks.set(shared, LockState.Shared);\n }\n\n await IModelHost.hubAccess.acquireLocks(this.briefcase, locks); // throws if unsuccessful\n for (const lock of locks)\n this.insertLock(lock[0], lock[1], LockOrigin.Acquired);\n this.lockDb.saveChanges();\n }\n\n public async acquireLocks(arg: { shared?: Id64Arg, exclusive?: Id64Arg }): Promise<void> {\n const locks = new Map<Id64String, LockState>();\n if (arg.shared) {\n for (const id of Id64.iterable(arg.shared)) {\n if (!this.holdsSharedLock(id))\n locks.set(id, LockState.Shared);\n }\n }\n if (arg.exclusive) {\n for (const id of Id64.iterable(arg.exclusive)) {\n if (!this.holdsExclusiveLock(id))\n locks.set(id, LockState.Exclusive);\n }\n }\n return this.acquireAllLocks(locks);\n }\n\n /** When an element is newly created in a session, we hold the lock on it implicitly. Save that fact. */\n public elementWasCreated(id: Id64String) {\n this.insertLock(id, LockState.Exclusive, LockOrigin.NewElement);\n this.lockDb.saveChanges();\n }\n\n /** locks are not necessary during change propagation. */\n private get _locksAreRequired() { return !this.briefcase.txns.isIndirectChanges; }\n\n /** throw if locks are currently required and the exclusive lock is not held on the supplied element */\n public checkExclusiveLock(id: Id64String, type: string, operation: string) {\n if (this._locksAreRequired && !this.holdsExclusiveLock(id))\n throw new IModelError(IModelStatus.LockNotHeld, `exclusive lock not held on ${type} for ${operation} (id=${id})`);\n }\n\n /** throw if locks are currently required and a shared lock is not held on the supplied element */\n public checkSharedLock(id: Id64String, type: string, operation: string) {\n if (this._locksAreRequired && !this.holdsSharedLock(id))\n throw new IModelError(IModelStatus.LockNotHeld, `shared lock not held on ${type} for ${operation} (id=${id})`);\n }\n\n}\n\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"SqliteStatement.js","sourceRoot":"","sources":["../../src/SqliteStatement.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAAkH;AAClH,oDAA4D;AAE5D,6CAA0C;AAqB1C,SAAS,SAAS,CAAC,IAAc;IAC/B,IAAI,IAAI,KAAK,uBAAQ,CAAC,YAAY;QAChC,MAAM,IAAI,yBAAW,CAAC,IAAI,EAAE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I,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE;YACzC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAG,CAAC;YACpC,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;SACrB;QACD,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;IAEM,aAAa,CAAC,GAAW;QAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF;AAjCD,wCAiCC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module SQLite\r\n */\r\n\r\nimport { assert, BentleyError, DbResult, GuidString, Id64String, IDisposable, LRUMap } from \"@itwin/core-bentley\";\r\nimport { ECJsNames, IModelError } from \"@itwin/core-common\";\r\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { IModelHost } from \"./IModelHost\";\r\n\r\n// spell:ignore julianday\r\n\r\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\r\n\r\n/** Marks a string as either an [Id64String]($core-bentley) or [GuidString]($core-bentley), so\r\n * that it can be passed to the [bindValue]($backend.SqliteStatement) or [bindValues]($backend.SqliteStatement)\r\n * methods of [SqliteStatement]($backend).\r\n * @internal\r\n */\r\nexport interface StringParam {\r\n id?: Id64String;\r\n guid?: GuidString;\r\n}\r\n\r\n/** parameter Index (1-based), or name of the parameter (including the initial ':', '@' or '$')\r\n * @public\r\n */\r\nexport type BindParameter = number | string;\r\n\r\nfunction checkBind(stat: DbResult) {\r\n if (stat !== DbResult.BE_SQLITE_OK)\r\n throw new IModelError(stat, \"SQLite Bind error\");\r\n}\r\n\r\n/** Executes SQLite SQL statements.\r\n *\r\n * A statement must be prepared before it can be executed, and it must be released when no longer needed.\r\n * See [IModelDb.withPreparedSqliteStatement]($backend) or\r\n * [ECDb.withPreparedSqliteStatement]($backend) for a convenient and\r\n * reliable way to prepare, execute, and then release a statement.\r\n *\r\n * A statement may contain parameters that must be filled in before use by calling [SqliteStatement.bindValue]($backend)\r\n * or [SqliteStatement.bindValues]($backend).\r\n *\r\n * Once prepared (and parameters are bound, if any), the statement is executed by calling [SqliteStatement.step]($backend).\r\n * In case of an **SQL SELECT** statement, the current row can be retrieved with [SqliteStatement.getRow]($backend) as\r\n * a whole, or with [SqliteStatement.getValue]($backend) when individual values are needed.\r\n * Alternatively, query results of an **SQL SELECT** statement can be stepped through by using\r\n * standard iteration syntax, such as `for of`.\r\n *\r\n * > Preparing a statement can be time-consuming. The best way to reduce the effect of this overhead is to cache and reuse prepared\r\n * > statements. A cached prepared statement may be used in different places in an app, as long as the statement is general enough.\r\n * > The key to making this strategy work is to phrase a statement in a general way and use placeholders to represent parameters that will vary on each use.\r\n * @public\r\n */\r\nexport class SqliteStatement implements IterableIterator<any>, IDisposable {\r\n private _stmt: IModelJsNative.SqliteStatement | undefined;\r\n private _db: IModelJsNative.AnyDb | undefined;\r\n\r\n public constructor(private _sql: string) { }\r\n public get stmt(): IModelJsNative.SqliteStatement { return this._stmt!; }\r\n public get sql() { return this._sql; }\r\n\r\n /** Check if this statement has been prepared successfully or not */\r\n public get isPrepared(): boolean { return undefined !== this._stmt; }\r\n\r\n /** Prepare this statement prior to first use.\r\n * @param db The DgnDb or ECDb to prepare the statement against\r\n * @param sql The SQL statement string to prepare\r\n * @param logErrors Determine if errors are logged or not\r\n * @throws if the SQL statement cannot be prepared. Normally, prepare fails due to SQL syntax errors or references to tables or properties that do not exist.\r\n * The error.message property will provide details.\r\n */\r\n public prepare(db: IModelJsNative.AnyDb, logErrors = true): void {\r\n if (this.isPrepared)\r\n throw new Error(\"SqliteStatement is already prepared\");\r\n this._db = db;\r\n this._stmt = new IModelHost.platform.SqliteStatement();\r\n this._stmt.prepare(db, this._sql, logErrors);\r\n }\r\n\r\n /** Indicates whether the prepared statement makes no **direct* changes to the content of the file\r\n * or not. See [SQLite docs](https://www.sqlite.org/c3ref/stmt_readonly.html) for details.\r\n */\r\n public get isReadonly(): boolean {\r\n return this.stmt.isReadonly();\r\n }\r\n\r\n /** Reset this statement so that the next call to step will return the first row, if any.\r\n */\r\n public reset(): void {\r\n this.stmt.reset();\r\n }\r\n\r\n /** Call this function when finished with this statement. This releases the native resources held by the statement. */\r\n public dispose(): void {\r\n if (this._stmt) {\r\n this._stmt.dispose(); // free native statement\r\n this._stmt = undefined;\r\n this._db = undefined;\r\n }\r\n }\r\n\r\n /**\r\n * Call `step` on this statement and determine whether a new row is available.\r\n * Use this method only when this statement has been prepared with a SELECT statement.\r\n * @return true if a new row is available, false otherwise.\r\n * @throws if `step` returns anything other than BE_SQLITE_ROW or BE_SQLITE_DONE.\r\n */\r\n public nextRow(): boolean {\r\n const rc = this.step();\r\n switch (rc) {\r\n case DbResult.BE_SQLITE_ROW:\r\n return true;\r\n case DbResult.BE_SQLITE_DONE:\r\n return false;\r\n }\r\n\r\n throw new BentleyError(rc, this._db!.getLastError());\r\n }\r\n\r\n /** Binds a value to the specified SQL parameter.\r\n * The value must be of one of these types:\r\n * JavaScript Type | SQLite Type\r\n * --- | ---\r\n * undefined | NULL\r\n * boolean | INTEGER with true being bound as 1 and false as 0\r\n * number | INTEGER if number is integral or REAL if number is not integral\r\n * string | TEXT\r\n * Uint8Array or ArrayBuffer | BLOB\r\n * [StringParam]($backend) where member **id** is set | INTEGER\r\n * [StringParam]($backend) where member **guid** is set | BLOB\r\n *\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param value Value to bind.\r\n * @throws [IModelError]($common) if the value is of an unsupported type or in\r\n * case of other binding errors.\r\n */\r\n public bindValue(parameter: BindParameter, value: any): void {\r\n let stat: DbResult;\r\n if (value === undefined || value === null) {\r\n stat = this.stmt.bindNull(parameter);\r\n } else if (typeof (value) === \"number\") {\r\n if (Number.isInteger(value))\r\n stat = this.stmt.bindInteger(parameter, value);\r\n else\r\n stat = this.stmt.bindDouble(parameter, value);\r\n } else if (typeof (value) === \"boolean\") {\r\n stat = this.stmt.bindInteger(parameter, value ? 1 : 0);\r\n } else if (typeof (value) === \"string\") {\r\n stat = this.stmt.bindString(parameter, value);\r\n } else if (!!value.id) {\r\n stat = this.stmt.bindId(parameter, value.id);\r\n } else if (!!value.guid) {\r\n stat = this.stmt.bindGuid(parameter, value.guid);\r\n } else if (value instanceof Uint8Array) {\r\n stat = this.stmt.bindBlob(parameter, value);\r\n } else\r\n throw new IModelError(DbResult.BE_SQLITE_ERROR, `Parameter value ${value} is of an unsupported data type.`);\r\n\r\n if (stat !== DbResult.BE_SQLITE_OK)\r\n throw new IModelError(stat, \"Error in bindValue\");\r\n }\r\n\r\n /** Bind an integer parameter\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val integer to bind.\r\n */\r\n public bindInteger(parameter: BindParameter, val: number) {\r\n checkBind(this.stmt.bindInteger(parameter, val));\r\n }\r\n /** Bind an integer parameter if it is defined. Otherwise do nothing.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val integer to bind.\r\n */\r\n public maybeBindInteger(parameter: BindParameter, val?: number) {\r\n if (val !== undefined)\r\n this.bindInteger(parameter, val);\r\n }\r\n /** Bind a boolean parameter.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val boolean to bind.\r\n */\r\n public bindBoolean(parameter: BindParameter, val: boolean) {\r\n this.bindInteger(parameter, val ? 1 : 0);\r\n }\r\n /** Bind a boolean parameter if it is defined. Otherwise do nothing.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val boolean to bind.\r\n */\r\n public maybeBindBoolean(parameter: BindParameter, val?: boolean) {\r\n if (val !== undefined)\r\n this.bindBoolean(parameter, val);\r\n }\r\n /** JSON.stringify a property value and bind the JSON string.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val object to bind.\r\n * @internal\r\n */\r\n public bindProps<T>(colIndex: number, val: T) {\r\n this.bindString(colIndex, JSON.stringify(val));\r\n }\r\n /** JSON.stringify a property value if it is defined, and bind the JSON string. Otherwise do nothing.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val object to bind.\r\n * @internal\r\n */\r\n public maybeBindProps<T>(colIndex: number, val?: T) {\r\n if (val !== undefined)\r\n this.bindProps(colIndex, val);\r\n }\r\n /** Bind a double parameter\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val double to bind.\r\n */\r\n public bindDouble(parameter: BindParameter, val: number) {\r\n checkBind(this.stmt.bindDouble(parameter, val));\r\n }\r\n /** Bind a double parameter if it is defined. Otherwise do nothing.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val double to bind.\r\n */\r\n public maybeBindDouble(parameter: BindParameter, val?: number) {\r\n if (val !== undefined)\r\n this.bindDouble(parameter, val);\r\n }\r\n /** Bind a string parameter\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val string to bind.\r\n */\r\n public bindString(parameter: BindParameter, val: string) {\r\n checkBind(this.stmt.bindString(parameter, val));\r\n }\r\n /** Bind a string parameter if it is defined. Otherwise do nothing.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val string to bind.\r\n */\r\n public maybeBindString(parameter: BindParameter, val?: string) {\r\n if (val !== undefined)\r\n this.bindString(parameter, val);\r\n }\r\n /** Bind an Id64String parameter as a 64-bit integer\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val Id to bind.\r\n */\r\n public bindId(parameter: BindParameter, id: Id64String) {\r\n checkBind(this.stmt.bindId(parameter, id));\r\n }\r\n /** Bind a Guid parameter\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val Guid to bind.\r\n */\r\n public bindGuid(parameter: BindParameter, guid: GuidString) {\r\n checkBind(this.stmt.bindGuid(parameter, guid));\r\n }\r\n /** Bind a blob parameter\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val blob to bind.\r\n */\r\n public bindBlob(parameter: BindParameter, blob: Uint8Array) {\r\n checkBind(this.stmt.bindBlob(parameter, blob));\r\n }\r\n /** Bind a blob parameter if it is defined. Otherwise do nothing.\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n * @param val blob to bind.\r\n */\r\n public maybeBindBlob(parameter: BindParameter, val?: Uint8Array) {\r\n if (val !== undefined)\r\n this.bindBlob(parameter, val);\r\n }\r\n /** Bind null to a parameter\r\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\r\n */\r\n public bindNull(parameter: BindParameter) {\r\n checkBind(this.stmt.bindNull(parameter));\r\n }\r\n\r\n /** Bind values to all parameters in the statement.\r\n * @param values The values to bind to the parameters.\r\n * Pass an *array* of values if the parameters are *positional*.\r\n * Pass an *object of the values keyed on the parameter name* for *named parameters*.\r\n * The values in either the array or object must match the respective types of the parameter.\r\n * See [[SqliteStatement.bindValue]] for details on the supported types.\r\n */\r\n public bindValues(values: any[] | object): void {\r\n if (Array.isArray(values)) {\r\n for (let i = 0; i < values.length; i++) {\r\n const paramIndex: number = i + 1;\r\n const paramValue: any = values[i];\r\n if (paramValue === undefined || paramValue === null)\r\n continue;\r\n\r\n this.bindValue(paramIndex, paramValue);\r\n }\r\n return;\r\n }\r\n\r\n for (const entry of Object.entries(values)) {\r\n const paramName: string = entry[0];\r\n const paramValue: any = entry[1];\r\n if (paramValue === undefined || paramValue === null)\r\n continue;\r\n\r\n this.bindValue(paramName, paramValue);\r\n }\r\n }\r\n\r\n /** Clear any bindings that were previously set on this statement.\r\n * @throws [IModelError]($common) in case of errors\r\n */\r\n public clearBindings(): void {\r\n const stat = this.stmt.clearBindings();\r\n if (stat !== DbResult.BE_SQLITE_OK)\r\n throw new IModelError(stat, \"Error in clearBindings\");\r\n }\r\n\r\n /** Step this statement to the next row.\r\n *\r\n * For **SQL SELECT** statements the method returns\r\n * - [DbResult.BE_SQLITE_ROW]($core-bentley) if the statement now points successfully to the next row.\r\n * - [DbResult.BE_SQLITE_DONE]($core-bentley) if the statement has no more rows.\r\n * - Error status in case of errors.\r\n *\r\n * For **SQL INSERT, UPDATE, DELETE** statements the method returns\r\n * - [DbResult.BE_SQLITE_DONE]($core-bentley) if the statement has been executed successfully.\r\n * - Error status in case of errors.\r\n */\r\n public step(): DbResult {\r\n return this.stmt.step();\r\n }\r\n /** Get the query result's column count (only for SQL SELECT statements). */\r\n public getColumnCount(): number {\r\n return this.stmt.getColumnCount();\r\n }\r\n /** Get the value for the column at the given index in the query result.\r\n * @param columnIx Index of SQL column in query result (0-based)\r\n */\r\n public getValue(columnIx: number): SqliteValue {\r\n return new SqliteValue(this.stmt, columnIx);\r\n }\r\n /** Determine whether the value of the specified column is null\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public isValueNull(colIndex: number): boolean {\r\n return this.stmt.isValueNull(colIndex);\r\n }\r\n /** Get a size in bytes of a blob or text column\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getColumnBytes(colIndex: number): number {\r\n return this.stmt.getColumnBytes(colIndex);\r\n }\r\n /** Get a value as a blob\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueBlob(colIndex: number): Uint8Array {\r\n return this.stmt.getValueBlob(colIndex);\r\n }\r\n /** Get the value as a blob, or undefined if it is null.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueBlobMaybe(colIndex: number): Uint8Array | undefined {\r\n return this.isValueNull(colIndex) ? undefined : this.getValueBlob(colIndex);\r\n }\r\n /** Get a value as a double\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueDouble(colIndex: number): number {\r\n return this.stmt.getValueDouble(colIndex);\r\n }\r\n /** Get the value as an double, or undefined if it is null.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueDoubleMaybe(colIndex: number): number | undefined {\r\n return this.isValueNull(colIndex) ? undefined : this.getValueDouble(colIndex);\r\n }\r\n /** Get a value as a integer\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueInteger(colIndex: number): number {\r\n return this.stmt.getValueInteger(colIndex);\r\n }\r\n /** Get the value as an integer, or undefined if it is null.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueIntegerMaybe(colIndex: number): number | undefined {\r\n return this.isValueNull(colIndex) ? undefined : this.getValueInteger(colIndex);\r\n }\r\n /** Get a value as a string\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueString(colIndex: number): string {\r\n return this.stmt.getValueString(colIndex);\r\n }\r\n /** Get the value as a string, or undefined if it is null.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueStringMaybe(colIndex: number): string | undefined {\r\n return this.isValueNull(colIndex) ? undefined : this.getValueString(colIndex);\r\n }\r\n /** Get a value as an Id\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueId(colIndex: number): Id64String {\r\n return this.stmt.getValueId(colIndex);\r\n }\r\n /** Get a value as a Guid\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueGuid(colIndex: number): GuidString {\r\n return this.stmt.getValueGuid(colIndex);\r\n }\r\n /** Get the value as a boolean. Returns `false` if the column is null.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n */\r\n public getValueBoolean(colIndex: number) {\r\n return this.isValueNull(colIndex) ? false : 0 !== this.getValueInteger(colIndex);\r\n }\r\n /** Get the value of a [julianday](https://www.sqlite.org/lang_datefunc.html) column as a JavaScript `Date`.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n * @beta\r\n */\r\n public getValueDate(colIndex: number) {\r\n return new Date((this.stmt.getValueDouble(colIndex) - 2440587.5) * 86400000); // conversion from julian day ms to unix epoch ms\r\n }\r\n /** Get the value as a \"props\" JSON string, then parse it and return the object\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n * @internal\r\n */\r\n public getProps<T>(colIndex: number): T {\r\n return JSON.parse(this.getValueString(colIndex));\r\n }\r\n /** Get the value as a \"props\" JSON string, then parse it and return the object.\r\n * If the column is null, return undefined.\r\n * @param colIndex Index of SQL column in query result (0-based)\r\n * @internal\r\n */\r\n public getPropsMaybe<T>(colIndex: number): T | undefined {\r\n return this.isValueNull(colIndex) ? undefined : this.getProps(colIndex);\r\n }\r\n\r\n /** Get the current row.\r\n * The returned row is formatted as JavaScript object where every SELECT clause item becomes a property in the JavaScript object.\r\n *\r\n * The SQL select clause item's name becomes the member name of the JavaScript object, **with the first character lowered**.\r\n *\r\n * SQLite Type | JavaScript Type\r\n * --- | ---\r\n * [SqliteValueType.Null]($backend) | undefined\r\n * [SqliteValueType.Integer]($backend) | number\r\n * [SqliteValueType.Double]($backend) | number\r\n * [SqliteValueType.String]($backend) | string\r\n * [SqliteValueType.Blob]($backend) | Uint8Array\r\n */\r\n public getRow(): any {\r\n const colCount = this.getColumnCount();\r\n const row: object = {};\r\n const duplicatePropNames = new Map<string, number>();\r\n for (let i = 0; i < colCount; i++) {\r\n const sqliteValue = this.getValue(i);\r\n if (!sqliteValue.isNull) {\r\n const propName: string = SqliteStatement.determineResultRowPropertyName(duplicatePropNames, sqliteValue);\r\n let val: any;\r\n switch (sqliteValue.type) {\r\n case SqliteValueType.Blob:\r\n val = sqliteValue.getBlob();\r\n break;\r\n case SqliteValueType.Double:\r\n val = sqliteValue.getDouble();\r\n break;\r\n case SqliteValueType.Integer:\r\n val = sqliteValue.getInteger();\r\n break;\r\n case SqliteValueType.String:\r\n val = sqliteValue.getString();\r\n break;\r\n\r\n default:\r\n throw new Error(\"Unsupported SqliteValueType\");\r\n }\r\n\r\n Object.defineProperty(row, propName, { enumerable: true, configurable: true, writable: true, value: val });\r\n }\r\n }\r\n return row;\r\n }\r\n\r\n private static determineResultRowPropertyName(duplicatePropNames: Map<string, number>, sqliteValue: SqliteValue): string {\r\n let jsName = ECJsNames.toJsName(sqliteValue.columnName);\r\n\r\n // now check duplicates. If there are, append a numeric suffix to the duplicates\r\n let suffix = duplicatePropNames.get(jsName);\r\n if (suffix === undefined)\r\n duplicatePropNames.set(jsName, 0);\r\n else {\r\n suffix++;\r\n duplicatePropNames.set(jsName, suffix);\r\n jsName += `_${suffix}`;\r\n }\r\n\r\n return jsName;\r\n }\r\n\r\n /** Calls step when called as an iterator.\r\n */\r\n public next(): IteratorResult<any> {\r\n return DbResult.BE_SQLITE_ROW === this.step() ? { done: false, value: this.getRow() } : { done: true, value: undefined };\r\n }\r\n\r\n /** The iterator that will step through the results of this statement. */\r\n public [Symbol.iterator](): IterableIterator<any> { return this; }\r\n}\r\n\r\n/** Data type of a value in in an SQLite SQL query result.\r\n * See also:\r\n * - [SqliteValue]($backend)\r\n * - [SqliteStatement]($backend)\r\n * - [SqliteStatement.getValue]($backend)\r\n * @public\r\n */\r\nexport enum SqliteValueType {\r\n // do not change the values of that enum. It must correspond to the respective\r\n // enum DbValueType in the native BeSQLite API.\r\n Integer = 1,\r\n Double = 2,\r\n String = 3,\r\n Blob = 4,\r\n Null = 5,\r\n}\r\n\r\n/** Value of a column in a row of an SQLite SQL query result.\r\n * See also:\r\n * - [SqliteStatement]($backend)\r\n * - [SqliteStatement.getValue]($backend)\r\n * @public\r\n */\r\nexport class SqliteValue {\r\n private readonly _stmt: IModelJsNative.SqliteStatement;\r\n private readonly _colIndex: number;\r\n\r\n public constructor(stmt: IModelJsNative.SqliteStatement, colIndex: number) {\r\n this._stmt = stmt;\r\n this._colIndex = colIndex;\r\n }\r\n\r\n /** Indicates whether the value is NULL or not. */\r\n public get isNull(): boolean { return this._stmt.isValueNull(this._colIndex); }\r\n\r\n /** Gets the data type of the value. */\r\n public get type(): SqliteValueType { return this._stmt.getColumnType(this._colIndex); }\r\n\r\n /** Gets the name of the column of the value. */\r\n public get columnName(): string { return this._stmt.getColumnName(this._colIndex); }\r\n\r\n /** Gets the SqlValue as JavaScript value.\r\n *\r\n * SQLite Type | JavaScript Type\r\n * --- | ---\r\n * [SqliteValueType.Null]($backend) | undefined\r\n * [SqliteValueType.Integer]($backend) | number\r\n * [SqliteValueType.Double]($backend) | number\r\n * [SqliteValueType.String]($backend) | string\r\n * [SqliteValueType.Blob]($backend) | Uint8Array\r\n */\r\n public get value(): any {\r\n switch (this.type) {\r\n case SqliteValueType.Null:\r\n return undefined;\r\n case SqliteValueType.Blob:\r\n return this.getBlob();\r\n case SqliteValueType.Double:\r\n return this.getDouble();\r\n case SqliteValueType.Integer:\r\n return this.getInteger();\r\n case SqliteValueType.String:\r\n return this.getString();\r\n default:\r\n throw new Error(\"Unhandled SqliteValueType\");\r\n }\r\n }\r\n\r\n /** Get the value as Blob */\r\n public getBlob(): Uint8Array { return this._stmt.getValueBlob(this._colIndex); }\r\n /** Get the value as a double value */\r\n public getDouble(): number { return this._stmt.getValueDouble(this._colIndex); }\r\n /** Get the value as a integer value */\r\n public getInteger(): number { return this._stmt.getValueInteger(this._colIndex); }\r\n /** Get the value as a string value */\r\n public getString(): string { return this._stmt.getValueString(this._colIndex); }\r\n /** Get the value as an Id value */\r\n public getId(): Id64String { return this._stmt.getValueId(this._colIndex); }\r\n /** Get the value as a Guid value */\r\n public getGuid(): GuidString { return this._stmt.getValueGuid(this._colIndex); }\r\n}\r\n\r\ninterface Statement {\r\n isPrepared: boolean;\r\n sql: string;\r\n dispose(): void;\r\n reset(): void;\r\n clearBindings(): void;\r\n}\r\n\r\n/** A cache for previously prepared SqliteStatements.\r\n * It only holds Statements after they are no longer in use, resetting and clearing their bindings before saving them.\r\n * When a request to use a statement from the cache is made, it is first removed from the cache.\r\n * @internal\r\n */\r\nexport class StatementCache<Stmt extends Statement> {\r\n private _cache: LRUMap<string, Stmt>;\r\n\r\n public constructor(maxCount = 40) {\r\n this._cache = new LRUMap<string, Stmt>(maxCount);\r\n }\r\n\r\n public get size() { return this._cache.size; }\r\n public addOrDispose(stmt: Stmt): void {\r\n assert(stmt.isPrepared);\r\n\r\n const existing = this._cache.get(stmt.sql);\r\n if (existing !== undefined) {\r\n stmt.dispose(); // we already have a statement with this sql cached, we can't save another one so just dispose it\r\n return;\r\n }\r\n if (this._cache.size >= this._cache.limit) {\r\n const oldest = this._cache.shift()!;\r\n oldest[1].dispose();\r\n }\r\n stmt.reset();\r\n stmt.clearBindings();\r\n this._cache.set(stmt.sql, stmt);\r\n }\r\n\r\n public findAndRemove(sql: string): Stmt | undefined {\r\n return this._cache.delete(sql);\r\n }\r\n\r\n public clear() {\r\n this._cache.forEach((stmt) => stmt.dispose());\r\n this._cache.clear();\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"SqliteStatement.js","sourceRoot":"","sources":["../../src/SqliteStatement.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAAkH;AAClH,oDAA4D;AAE5D,6CAA0C;AAqB1C,SAAS,SAAS,CAAC,IAAc;IAC/B,IAAI,IAAI,KAAK,uBAAQ,CAAC,YAAY;QAChC,MAAM,IAAI,yBAAW,CAAC,IAAI,EAAE,mBAAmB,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,eAAe;IAI1B,YAA2B,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;I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CAAC,OAAO,EAAE,CAAC;SACrB;QACD,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;IAEM,aAAa,CAAC,GAAW;QAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF;AAjCD,wCAiCC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module SQLite\n */\n\nimport { assert, BentleyError, DbResult, GuidString, Id64String, IDisposable, LRUMap } from \"@itwin/core-bentley\";\nimport { ECJsNames, IModelError } from \"@itwin/core-common\";\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\nimport { IModelHost } from \"./IModelHost\";\n\n// spell:ignore julianday\n\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\n/** Marks a string as either an [Id64String]($core-bentley) or [GuidString]($core-bentley), so\n * that it can be passed to the [bindValue]($backend.SqliteStatement) or [bindValues]($backend.SqliteStatement)\n * methods of [SqliteStatement]($backend).\n * @internal\n */\nexport interface StringParam {\n id?: Id64String;\n guid?: GuidString;\n}\n\n/** parameter Index (1-based), or name of the parameter (including the initial ':', '@' or '$')\n * @public\n */\nexport type BindParameter = number | string;\n\nfunction checkBind(stat: DbResult) {\n if (stat !== DbResult.BE_SQLITE_OK)\n throw new IModelError(stat, \"SQLite Bind error\");\n}\n\n/** Executes SQLite SQL statements.\n *\n * A statement must be prepared before it can be executed, and it must be released when no longer needed.\n * See [IModelDb.withPreparedSqliteStatement]($backend) or\n * [ECDb.withPreparedSqliteStatement]($backend) for a convenient and\n * reliable way to prepare, execute, and then release a statement.\n *\n * A statement may contain parameters that must be filled in before use by calling [SqliteStatement.bindValue]($backend)\n * or [SqliteStatement.bindValues]($backend).\n *\n * Once prepared (and parameters are bound, if any), the statement is executed by calling [SqliteStatement.step]($backend).\n * In case of an **SQL SELECT** statement, the current row can be retrieved with [SqliteStatement.getRow]($backend) as\n * a whole, or with [SqliteStatement.getValue]($backend) when individual values are needed.\n * Alternatively, query results of an **SQL SELECT** statement can be stepped through by using\n * standard iteration syntax, such as `for of`.\n *\n * > Preparing a statement can be time-consuming. The best way to reduce the effect of this overhead is to cache and reuse prepared\n * > statements. A cached prepared statement may be used in different places in an app, as long as the statement is general enough.\n * > The key to making this strategy work is to phrase a statement in a general way and use placeholders to represent parameters that will vary on each use.\n * @public\n */\nexport class SqliteStatement implements IterableIterator<any>, IDisposable {\n private _stmt: IModelJsNative.SqliteStatement | undefined;\n private _db: IModelJsNative.AnyDb | undefined;\n\n public constructor(private _sql: string) { }\n public get stmt(): IModelJsNative.SqliteStatement { return this._stmt!; }\n public get sql() { return this._sql; }\n\n /** Check if this statement has been prepared successfully or not */\n public get isPrepared(): boolean { return undefined !== this._stmt; }\n\n /** Prepare this statement prior to first use.\n * @param db The DgnDb or ECDb to prepare the statement against\n * @param sql The SQL statement string to prepare\n * @param logErrors Determine if errors are logged or not\n * @throws if the SQL statement cannot be prepared. Normally, prepare fails due to SQL syntax errors or references to tables or properties that do not exist.\n * The error.message property will provide details.\n */\n public prepare(db: IModelJsNative.AnyDb, logErrors = true): void {\n if (this.isPrepared)\n throw new Error(\"SqliteStatement is already prepared\");\n this._db = db;\n this._stmt = new IModelHost.platform.SqliteStatement();\n this._stmt.prepare(db, this._sql, logErrors);\n }\n\n /** Indicates whether the prepared statement makes no **direct* changes to the content of the file\n * or not. See [SQLite docs](https://www.sqlite.org/c3ref/stmt_readonly.html) for details.\n */\n public get isReadonly(): boolean {\n return this.stmt.isReadonly();\n }\n\n /** Reset this statement so that the next call to step will return the first row, if any.\n */\n public reset(): void {\n this.stmt.reset();\n }\n\n /** Call this function when finished with this statement. This releases the native resources held by the statement. */\n public dispose(): void {\n if (this._stmt) {\n this._stmt.dispose(); // free native statement\n this._stmt = undefined;\n this._db = undefined;\n }\n }\n\n /**\n * Call `step` on this statement and determine whether a new row is available.\n * Use this method only when this statement has been prepared with a SELECT statement.\n * @return true if a new row is available, false otherwise.\n * @throws if `step` returns anything other than BE_SQLITE_ROW or BE_SQLITE_DONE.\n */\n public nextRow(): boolean {\n const rc = this.step();\n switch (rc) {\n case DbResult.BE_SQLITE_ROW:\n return true;\n case DbResult.BE_SQLITE_DONE:\n return false;\n }\n\n throw new BentleyError(rc, this._db!.getLastError());\n }\n\n /** Binds a value to the specified SQL parameter.\n * The value must be of one of these types:\n * JavaScript Type | SQLite Type\n * --- | ---\n * undefined | NULL\n * boolean | INTEGER with true being bound as 1 and false as 0\n * number | INTEGER if number is integral or REAL if number is not integral\n * string | TEXT\n * Uint8Array or ArrayBuffer | BLOB\n * [StringParam]($backend) where member **id** is set | INTEGER\n * [StringParam]($backend) where member **guid** is set | BLOB\n *\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param value Value to bind.\n * @throws [IModelError]($common) if the value is of an unsupported type or in\n * case of other binding errors.\n */\n public bindValue(parameter: BindParameter, value: any): void {\n let stat: DbResult;\n if (value === undefined || value === null) {\n stat = this.stmt.bindNull(parameter);\n } else if (typeof (value) === \"number\") {\n if (Number.isInteger(value))\n stat = this.stmt.bindInteger(parameter, value);\n else\n stat = this.stmt.bindDouble(parameter, value);\n } else if (typeof (value) === \"boolean\") {\n stat = this.stmt.bindInteger(parameter, value ? 1 : 0);\n } else if (typeof (value) === \"string\") {\n stat = this.stmt.bindString(parameter, value);\n } else if (!!value.id) {\n stat = this.stmt.bindId(parameter, value.id);\n } else if (!!value.guid) {\n stat = this.stmt.bindGuid(parameter, value.guid);\n } else if (value instanceof Uint8Array) {\n stat = this.stmt.bindBlob(parameter, value);\n } else\n throw new IModelError(DbResult.BE_SQLITE_ERROR, `Parameter value ${value} is of an unsupported data type.`);\n\n if (stat !== DbResult.BE_SQLITE_OK)\n throw new IModelError(stat, \"Error in bindValue\");\n }\n\n /** Bind an integer parameter\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val integer to bind.\n */\n public bindInteger(parameter: BindParameter, val: number) {\n checkBind(this.stmt.bindInteger(parameter, val));\n }\n /** Bind an integer parameter if it is defined. Otherwise do nothing.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val integer to bind.\n */\n public maybeBindInteger(parameter: BindParameter, val?: number) {\n if (val !== undefined)\n this.bindInteger(parameter, val);\n }\n /** Bind a boolean parameter.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val boolean to bind.\n */\n public bindBoolean(parameter: BindParameter, val: boolean) {\n this.bindInteger(parameter, val ? 1 : 0);\n }\n /** Bind a boolean parameter if it is defined. Otherwise do nothing.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val boolean to bind.\n */\n public maybeBindBoolean(parameter: BindParameter, val?: boolean) {\n if (val !== undefined)\n this.bindBoolean(parameter, val);\n }\n /** JSON.stringify a property value and bind the JSON string.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val object to bind.\n * @internal\n */\n public bindProps<T>(colIndex: number, val: T) {\n this.bindString(colIndex, JSON.stringify(val));\n }\n /** JSON.stringify a property value if it is defined, and bind the JSON string. Otherwise do nothing.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val object to bind.\n * @internal\n */\n public maybeBindProps<T>(colIndex: number, val?: T) {\n if (val !== undefined)\n this.bindProps(colIndex, val);\n }\n /** Bind a double parameter\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val double to bind.\n */\n public bindDouble(parameter: BindParameter, val: number) {\n checkBind(this.stmt.bindDouble(parameter, val));\n }\n /** Bind a double parameter if it is defined. Otherwise do nothing.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val double to bind.\n */\n public maybeBindDouble(parameter: BindParameter, val?: number) {\n if (val !== undefined)\n this.bindDouble(parameter, val);\n }\n /** Bind a string parameter\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val string to bind.\n */\n public bindString(parameter: BindParameter, val: string) {\n checkBind(this.stmt.bindString(parameter, val));\n }\n /** Bind a string parameter if it is defined. Otherwise do nothing.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val string to bind.\n */\n public maybeBindString(parameter: BindParameter, val?: string) {\n if (val !== undefined)\n this.bindString(parameter, val);\n }\n /** Bind an Id64String parameter as a 64-bit integer\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val Id to bind.\n */\n public bindId(parameter: BindParameter, id: Id64String) {\n checkBind(this.stmt.bindId(parameter, id));\n }\n /** Bind a Guid parameter\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val Guid to bind.\n */\n public bindGuid(parameter: BindParameter, guid: GuidString) {\n checkBind(this.stmt.bindGuid(parameter, guid));\n }\n /** Bind a blob parameter\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val blob to bind.\n */\n public bindBlob(parameter: BindParameter, blob: Uint8Array) {\n checkBind(this.stmt.bindBlob(parameter, blob));\n }\n /** Bind a blob parameter if it is defined. Otherwise do nothing.\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n * @param val blob to bind.\n */\n public maybeBindBlob(parameter: BindParameter, val?: Uint8Array) {\n if (val !== undefined)\n this.bindBlob(parameter, val);\n }\n /** Bind null to a parameter\n * @param parameter Index (1-based) or name of the parameter (including the initial ':', '@' or '$')\n */\n public bindNull(parameter: BindParameter) {\n checkBind(this.stmt.bindNull(parameter));\n }\n\n /** Bind values to all parameters in the statement.\n * @param values The values to bind to the parameters.\n * Pass an *array* of values if the parameters are *positional*.\n * Pass an *object of the values keyed on the parameter name* for *named parameters*.\n * The values in either the array or object must match the respective types of the parameter.\n * See [[SqliteStatement.bindValue]] for details on the supported types.\n */\n public bindValues(values: any[] | object): void {\n if (Array.isArray(values)) {\n for (let i = 0; i < values.length; i++) {\n const paramIndex: number = i + 1;\n const paramValue: any = values[i];\n if (paramValue === undefined || paramValue === null)\n continue;\n\n this.bindValue(paramIndex, paramValue);\n }\n return;\n }\n\n for (const entry of Object.entries(values)) {\n const paramName: string = entry[0];\n const paramValue: any = entry[1];\n if (paramValue === undefined || paramValue === null)\n continue;\n\n this.bindValue(paramName, paramValue);\n }\n }\n\n /** Clear any bindings that were previously set on this statement.\n * @throws [IModelError]($common) in case of errors\n */\n public clearBindings(): void {\n const stat = this.stmt.clearBindings();\n if (stat !== DbResult.BE_SQLITE_OK)\n throw new IModelError(stat, \"Error in clearBindings\");\n }\n\n /** Step this statement to the next row.\n *\n * For **SQL SELECT** statements the method returns\n * - [DbResult.BE_SQLITE_ROW]($core-bentley) if the statement now points successfully to the next row.\n * - [DbResult.BE_SQLITE_DONE]($core-bentley) if the statement has no more rows.\n * - Error status in case of errors.\n *\n * For **SQL INSERT, UPDATE, DELETE** statements the method returns\n * - [DbResult.BE_SQLITE_DONE]($core-bentley) if the statement has been executed successfully.\n * - Error status in case of errors.\n */\n public step(): DbResult {\n return this.stmt.step();\n }\n /** Get the query result's column count (only for SQL SELECT statements). */\n public getColumnCount(): number {\n return this.stmt.getColumnCount();\n }\n /** Get the value for the column at the given index in the query result.\n * @param columnIx Index of SQL column in query result (0-based)\n */\n public getValue(columnIx: number): SqliteValue {\n return new SqliteValue(this.stmt, columnIx);\n }\n /** Determine whether the value of the specified column is null\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public isValueNull(colIndex: number): boolean {\n return this.stmt.isValueNull(colIndex);\n }\n /** Get a size in bytes of a blob or text column\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getColumnBytes(colIndex: number): number {\n return this.stmt.getColumnBytes(colIndex);\n }\n /** Get a value as a blob\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueBlob(colIndex: number): Uint8Array {\n return this.stmt.getValueBlob(colIndex);\n }\n /** Get the value as a blob, or undefined if it is null.\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueBlobMaybe(colIndex: number): Uint8Array | undefined {\n return this.isValueNull(colIndex) ? undefined : this.getValueBlob(colIndex);\n }\n /** Get a value as a double\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueDouble(colIndex: number): number {\n return this.stmt.getValueDouble(colIndex);\n }\n /** Get the value as an double, or undefined if it is null.\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueDoubleMaybe(colIndex: number): number | undefined {\n return this.isValueNull(colIndex) ? undefined : this.getValueDouble(colIndex);\n }\n /** Get a value as a integer\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueInteger(colIndex: number): number {\n return this.stmt.getValueInteger(colIndex);\n }\n /** Get the value as an integer, or undefined if it is null.\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueIntegerMaybe(colIndex: number): number | undefined {\n return this.isValueNull(colIndex) ? undefined : this.getValueInteger(colIndex);\n }\n /** Get a value as a string\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueString(colIndex: number): string {\n return this.stmt.getValueString(colIndex);\n }\n /** Get the value as a string, or undefined if it is null.\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueStringMaybe(colIndex: number): string | undefined {\n return this.isValueNull(colIndex) ? undefined : this.getValueString(colIndex);\n }\n /** Get a value as an Id\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueId(colIndex: number): Id64String {\n return this.stmt.getValueId(colIndex);\n }\n /** Get a value as a Guid\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueGuid(colIndex: number): GuidString {\n return this.stmt.getValueGuid(colIndex);\n }\n /** Get the value as a boolean. Returns `false` if the column is null.\n * @param colIndex Index of SQL column in query result (0-based)\n */\n public getValueBoolean(colIndex: number) {\n return this.isValueNull(colIndex) ? false : 0 !== this.getValueInteger(colIndex);\n }\n /** Get the value of a [julianday](https://www.sqlite.org/lang_datefunc.html) column as a JavaScript `Date`.\n * @param colIndex Index of SQL column in query result (0-based)\n * @beta\n */\n public getValueDate(colIndex: number) {\n return new Date((this.stmt.getValueDouble(colIndex) - 2440587.5) * 86400000); // conversion from julian day ms to unix epoch ms\n }\n /** Get the value as a \"props\" JSON string, then parse it and return the object\n * @param colIndex Index of SQL column in query result (0-based)\n * @internal\n */\n public getProps<T>(colIndex: number): T {\n return JSON.parse(this.getValueString(colIndex));\n }\n /** Get the value as a \"props\" JSON string, then parse it and return the object.\n * If the column is null, return undefined.\n * @param colIndex Index of SQL column in query result (0-based)\n * @internal\n */\n public getPropsMaybe<T>(colIndex: number): T | undefined {\n return this.isValueNull(colIndex) ? undefined : this.getProps(colIndex);\n }\n\n /** Get the current row.\n * The returned row is formatted as JavaScript object where every SELECT clause item becomes a property in the JavaScript object.\n *\n * The SQL select clause item's name becomes the member name of the JavaScript object, **with the first character lowered**.\n *\n * SQLite Type | JavaScript Type\n * --- | ---\n * [SqliteValueType.Null]($backend) | undefined\n * [SqliteValueType.Integer]($backend) | number\n * [SqliteValueType.Double]($backend) | number\n * [SqliteValueType.String]($backend) | string\n * [SqliteValueType.Blob]($backend) | Uint8Array\n */\n public getRow(): any {\n const colCount = this.getColumnCount();\n const row: object = {};\n const duplicatePropNames = new Map<string, number>();\n for (let i = 0; i < colCount; i++) {\n const sqliteValue = this.getValue(i);\n if (!sqliteValue.isNull) {\n const propName: string = SqliteStatement.determineResultRowPropertyName(duplicatePropNames, sqliteValue);\n let val: any;\n switch (sqliteValue.type) {\n case SqliteValueType.Blob:\n val = sqliteValue.getBlob();\n break;\n case SqliteValueType.Double:\n val = sqliteValue.getDouble();\n break;\n case SqliteValueType.Integer:\n val = sqliteValue.getInteger();\n break;\n case SqliteValueType.String:\n val = sqliteValue.getString();\n break;\n\n default:\n throw new Error(\"Unsupported SqliteValueType\");\n }\n\n Object.defineProperty(row, propName, { enumerable: true, configurable: true, writable: true, value: val });\n }\n }\n return row;\n }\n\n private static determineResultRowPropertyName(duplicatePropNames: Map<string, number>, sqliteValue: SqliteValue): string {\n let jsName = ECJsNames.toJsName(sqliteValue.columnName);\n\n // now check duplicates. If there are, append a numeric suffix to the duplicates\n let suffix = duplicatePropNames.get(jsName);\n if (suffix === undefined)\n duplicatePropNames.set(jsName, 0);\n else {\n suffix++;\n duplicatePropNames.set(jsName, suffix);\n jsName += `_${suffix}`;\n }\n\n return jsName;\n }\n\n /** Calls step when called as an iterator.\n */\n public next(): IteratorResult<any> {\n return DbResult.BE_SQLITE_ROW === this.step() ? { done: false, value: this.getRow() } : { done: true, value: undefined };\n }\n\n /** The iterator that will step through the results of this statement. */\n public [Symbol.iterator](): IterableIterator<any> { return this; }\n}\n\n/** Data type of a value in in an SQLite SQL query result.\n * See also:\n * - [SqliteValue]($backend)\n * - [SqliteStatement]($backend)\n * - [SqliteStatement.getValue]($backend)\n * @public\n */\nexport enum SqliteValueType {\n // do not change the values of that enum. It must correspond to the respective\n // enum DbValueType in the native BeSQLite API.\n Integer = 1,\n Double = 2,\n String = 3,\n Blob = 4,\n Null = 5,\n}\n\n/** Value of a column in a row of an SQLite SQL query result.\n * See also:\n * - [SqliteStatement]($backend)\n * - [SqliteStatement.getValue]($backend)\n * @public\n */\nexport class SqliteValue {\n private readonly _stmt: IModelJsNative.SqliteStatement;\n private readonly _colIndex: number;\n\n public constructor(stmt: IModelJsNative.SqliteStatement, colIndex: number) {\n this._stmt = stmt;\n this._colIndex = colIndex;\n }\n\n /** Indicates whether the value is NULL or not. */\n public get isNull(): boolean { return this._stmt.isValueNull(this._colIndex); }\n\n /** Gets the data type of the value. */\n public get type(): SqliteValueType { return this._stmt.getColumnType(this._colIndex); }\n\n /** Gets the name of the column of the value. */\n public get columnName(): string { return this._stmt.getColumnName(this._colIndex); }\n\n /** Gets the SqlValue as JavaScript value.\n *\n * SQLite Type | JavaScript Type\n * --- | ---\n * [SqliteValueType.Null]($backend) | undefined\n * [SqliteValueType.Integer]($backend) | number\n * [SqliteValueType.Double]($backend) | number\n * [SqliteValueType.String]($backend) | string\n * [SqliteValueType.Blob]($backend) | Uint8Array\n */\n public get value(): any {\n switch (this.type) {\n case SqliteValueType.Null:\n return undefined;\n case SqliteValueType.Blob:\n return this.getBlob();\n case SqliteValueType.Double:\n return this.getDouble();\n case SqliteValueType.Integer:\n return this.getInteger();\n case SqliteValueType.String:\n return this.getString();\n default:\n throw new Error(\"Unhandled SqliteValueType\");\n }\n }\n\n /** Get the value as Blob */\n public getBlob(): Uint8Array { return this._stmt.getValueBlob(this._colIndex); }\n /** Get the value as a double value */\n public getDouble(): number { return this._stmt.getValueDouble(this._colIndex); }\n /** Get the value as a integer value */\n public getInteger(): number { return this._stmt.getValueInteger(this._colIndex); }\n /** Get the value as a string value */\n public getString(): string { return this._stmt.getValueString(this._colIndex); }\n /** Get the value as an Id value */\n public getId(): Id64String { return this._stmt.getValueId(this._colIndex); }\n /** Get the value as a Guid value */\n public getGuid(): GuidString { return this._stmt.getValueGuid(this._colIndex); }\n}\n\ninterface Statement {\n isPrepared: boolean;\n sql: string;\n dispose(): void;\n reset(): void;\n clearBindings(): void;\n}\n\n/** A cache for previously prepared SqliteStatements.\n * It only holds Statements after they are no longer in use, resetting and clearing their bindings before saving them.\n * When a request to use a statement from the cache is made, it is first removed from the cache.\n * @internal\n */\nexport class StatementCache<Stmt extends Statement> {\n private _cache: LRUMap<string, Stmt>;\n\n public constructor(maxCount = 40) {\n this._cache = new LRUMap<string, Stmt>(maxCount);\n }\n\n public get size() { return this._cache.size; }\n public addOrDispose(stmt: Stmt): void {\n assert(stmt.isPrepared);\n\n const existing = this._cache.get(stmt.sql);\n if (existing !== undefined) {\n stmt.dispose(); // we already have a statement with this sql cached, we can't save another one so just dispose it\n return;\n }\n if (this._cache.size >= this._cache.limit) {\n const oldest = this._cache.shift()!;\n oldest[1].dispose();\n }\n stmt.reset();\n stmt.clearBindings();\n this._cache.set(stmt.sql, stmt);\n }\n\n public findAndRemove(sql: string): Stmt | undefined {\n return this._cache.delete(sql);\n }\n\n public clear() {\n this._cache.forEach((stmt) => stmt.dispose());\n this._cache.clear();\n }\n}\n"]}