Private _bPrivate _datetimePrivate _deferredPrivate _localPrivate _needsPrivate _poolProtected _preResult from PreRunQueries hook containing cache status for batch operations
Optional cacheOptional cachedOptional telemetryOptional uncachedProtected _preResult from PreRunQuery hook containing cache status and optional cached result
Optional cachedOptional fingerprint?: stringOptional telemetryProtected _preResult from PreRunView hook containing cache status and optional cached result
Optional cachedOptional fingerprint?: stringOptional telemetryProtected _preResult from PreRunViews hook containing cache status for batch operations
Optional cacheOptional cachedOptional smartWhen CacheLocal is enabled, contains the cache check params to send to server
Optional telemetryOptional uncachedOptional useWhen CacheLocal is enabled, indicates we should use smart cache check
Private _queuePrivate _recordPrivate _savepointPrivate _savepointPrivate _sqlPrivate _sqlOptional options?: InternalSQLOptionsPrivate _transactionPrivate _transactionPrivate _transactionPrivate queryProtected Static _mjGets all explorer navigation items including inactive ones.
Array of all ExplorerNavigationItem objects
Returns the currently loaded local metadata from within the instance
Protected AllowInternal Gets whether metadata refresh is currently allowed
Gets all application metadata in the system.
Array of ApplicationInfo objects representing all applications
Gets all audit log types defined for tracking system activities.
Array of AuditLogTypeInfo objects
Gets all authorization definitions in the system.
Array of AuthorizationInfo objects defining permissions
Gets the current configuration data for this provider instance
Gets the underlying SQL Server connection pool
The mssql ConnectionPool object
Gets all entity metadata in the system.
Array of EntityInfo objects representing all entities
For the SQLServerDataProvider the unique instance connection string which is used to identify, uniquely, a given connection is the following format: mssql://host:port/instanceName?/database instanceName is only inserted if it is provided in the options
Gets the latest metadata timestamps from local cache. Used for comparison with remote timestamps.
Array of locally cached metadata timestamps
Gets the latest metadata timestamps from the remote server. Used to determine if local cache is out of date.
Array of metadata timestamp information
Gets all library definitions in the system.
Array of LibraryInfo objects representing code libraries
Protected LocalThis property will return the prefix to use for local storage keys. This is useful if you have multiple instances of a provider running in the same environment and you want to keep their local storage keys separate. The default implementation returns an empty string, but subclasses can override this to return a unique string based on the connection or other distinct identifier.
Gets the local storage provider implementation. Must be implemented by subclasses to provide environment-specific storage.
Local storage provider instance
Gets the MemberJunction core schema name (defaults to __mj if not configured)
Protected MetadataProtected PreOptional cacheOptional cachedOptional telemetryOptional uncachedProtected PreOptional cachedOptional fingerprint?: stringOptional telemetryProtected PreOptional cachedOptional fingerprint?: stringOptional telemetryProtected PreOptional cacheOptional cachedOptional smartWhen CacheLocal is enabled, contains the cache check params to send to server
Optional telemetryOptional uncachedOptional useWhen CacheLocal is enabled, indicates we should use smart cache check
Gets all query category definitions.
Array of QueryCategoryInfo objects for query organization
Gets all query entity associations.
Array of QueryEntityInfo objects linking queries to entities
Gets all query field definitions.
Array of QueryFieldInfo objects defining query result columns
Gets all query parameter definitions.
Array of QueryParameterInfo objects for parameterized queries
Gets all query permission assignments.
Array of QueryPermissionInfo objects defining query access
Gets all row-level security filters defined in the system.
Array of RowLevelSecurityFilterInfo objects for data access control
Gets only active explorer navigation items sorted by sequence. Results are cached for performance.
Array of active ExplorerNavigationItem objects
Checks if we're currently in a nested transaction (depth > 1)
Checks if we're currently in a transaction (at any depth)
Gets whether a transaction is currently active
Gets the current savepoint names in the stack (for debugging) Returns a copy to prevent external modification
Gets the current transaction nesting depth 0 = no transaction, 1 = first level, 2+ = nested transactions
Observable that emits the current transaction state (true when active, false when not) External code can subscribe to this to know when transactions start and end
provider.transactionState$.subscribe(isActive => {
console.log('Transaction active:', isActive);
});
Protected BuildBuilds dataset filters based on the provider configuration. Ensures MJ Core schema is always included and never excluded.
Array of filters to apply when loading metadata
Stores a dataset in the local cache. If itemFilters are provided, the combination of datasetName and the filters are used to build a key and determine a match in the cache
Checks if local metadata is out of date and needs refreshing. Compares local timestamps with server timestamps.
Optional providerToUse: IMetadataProviderTrue if refresh is needed, false otherwise
Protected CheckIf the specified datasetName is cached, this method will clear the cache. If itemFilters are provided, the combination of datasetName and the filters are used to determine a match in the cache
Optional itemFilters: DatasetItemFilterType[]Protected CloneProtected CompleteOptional contextUser: UserInfoConfigures the SQL Server data provider with connection settings and initializes the connection pool
Configuration data including connection string and options
Optional providerToUse: IMetadataProviderPromise
Protected ConvertConverts dataset item filters into a unique string key for caching.
Array of filters to convert
JSON-formatted string representing the filters
Protected CopyCreates a new SQL logging session that will capture all SQL operations to a file. Returns a disposable session object that must be disposed to stop logging.
Full path to the file where SQL statements will be logged
Optional options: SqlLoggingOptionsOptional configuration for the logging session
Promise
// Basic usage
const session = await provider.CreateSqlLogger('./logs/metadata-sync.sql');
try {
// Perform operations that will be logged
await provider.ExecuteSQL('INSERT INTO ...');
} finally {
await session.dispose(); // Stop logging
}
// With migration formatting
const session = await provider.CreateSqlLogger('./migrations/changes.sql', {
formatAsMigration: true,
description: 'MetadataSync push operation'
});
Creates a new transaction group for managing database transactions. Must be implemented by subclasses to provide transaction support.
A new transaction group instance
This method will create a human-readable string that describes the changes object that was created using the DiffObjects() method
JavaScript object that has properties for each changed field that in turn have field, oldValue and newValue as sub-properties
If not specified, default value of 200 characters applies where any values after the maxValueLength is cut off. The actual values are stored in the ChangesJSON and FullRecordJSON in the RecordChange table, this is only for the human-display
If specified, and if maxValueLength applies to any of the values being included in the description, this cutOffText param will be appended to the end of the cut off string to indicate to the human reader that the value is partial.
Creates a changes object by comparing two javascript objects, identifying fields that have different values. Each property in the returned object represents a changed field, with the field name as the key.
The original data object to compare from
The new data object to compare to
Entity metadata used to validate fields and determine comparison logic
The quote character to escape in string values (typically "'")
A Record mapping field names to FieldChange objects containing the field name, old value, and new value. Returns null if either oldData or newData is null/undefined. Only includes fields that have actually changed and are not read-only.
const changes = provider.DiffObjects(
{ name: "John's Co", revenue: 1000 },
{ name: "John's Co", revenue: 2000 },
entityInfo,
"'"
);
// Returns: { revenue: { field: "revenue", oldValue: 1000, newValue: 2000 } }
Protected EntityUsed to check to see if the entity in question is active or not If it is not active, it will throw an exception or log a warning depending on the status of the entity being either Deprecated or Disabled.
This method can be used to execute raw SQL statements outside of the MJ infrastructure. CAUTION - use this method with great care.
Optional options: ExecuteSQLOptionsOptional contextUser: UserInfoExecutes multiple SQL queries in a single batch for optimal performance. All queries are combined into a single SQL statement and executed together. This is particularly useful for bulk operations where you need to execute many similar queries and want to minimize round trips to the database.
Array of SQL queries to execute
Optional parameters: any[][]Optional array of parameter arrays, one for each query
Optional options: ExecuteSQLBatchOptionsOptional execution options for logging and description
Optional contextUser: UserInfoPromise<any[][]> - Array of result arrays, one for each query
Gets information about all active SQL logging sessions. Useful for monitoring and debugging.
Array of session information objects
Protected GetRetrieves all metadata from the server and constructs typed instances. Uses the MJ_Metadata dataset for efficient bulk loading.
Optional providerToUse: IMetadataProviderComplete metadata collection with all relationships
Gets a database by name, if required, and caches it in a format available to the client (e.g. IndexedDB, LocalStorage, File, etc). The cache method is Provider specific If itemFilters are provided, the combination of datasetName and the filters are used to determine a match in the cache
Optional itemFilters: DatasetItemFilterType[]Optional contextUser: UserInfoOptional providerToUse: IMetadataProviderProtected GetProtected GetProtected GetThis routine gets the local cached version of a given datasetName/itemFilters combination, it does NOT check the server status first and does not fall back on the server if there isn't a local cache version of this dataset/itemFilters combination
Optional itemFilters: DatasetItemFilterType[]Protected GetReturns the stored procedure name to use for the given entity based on if it is a new record or an existing record.
Optional itemFilters: DatasetItemFilterType[]Optional contextUser: UserInfoOptional providerToUse: IMetadataProviderCreates a unique key for the given datasetName and itemFilters combination coupled with the instance connection string to ensure uniqueness when 2+ connections exist
Optional itemFilters: DatasetItemFilterType[]Protected GetProtected GetConstructs the SQL query for a dataset item.
The dataset item metadata
Optional filters to apply
Name of the dataset (for error logging)
The SQL query string, or null if columns are invalid
Retrieves the date status information for a dataset and all its items from the server. This method will match the datasetName and itemFilters to the server's dataset and item filters to determine a match
Optional itemFilters: DatasetItemFilterType[]Optional contextUser: UserInfoOptional providerToUse: IMetadataProviderProtected GetInternal Generates the SQL statement for deleting an entity record
The entity to delete
The user performing the delete
The full SQL statement for deletion
Private GetThis function generates both the full SQL (with record change metadata) and the simple stored procedure call for delete
Object with fullSQL and simpleSQL properties
Protected GetInternal Gets AI actions configured for an entity based on trigger timing
The entity to get AI actions for
True to get before-save actions, false for after-save
Array of AI action entities
Returns a list of entity dependencies, basically metadata that tells you the links to this entity from all other entities.
Creates a new instance of a BaseEntity subclass for the specified entity and automatically calls NewRecord() to initialize it. This method serves as the core implementation for entity instantiation in the MemberJunction framework.
The name of the entity to create (must exist in metadata)
Optional contextUser: UserInfoOptional user context for permissions and audit tracking
Promise resolving to the newly created entity instance with NewRecord() called
Error if entity name is not found in metadata or if instantiation fails
Creates a new instance of a BaseEntity subclass and loads an existing record using the provided key. This overload provides a convenient way to instantiate and load in a single operation.
The name of the entity to create (must exist in metadata)
CompositeKey containing the primary key value(s) for the record to load
Optional contextUser: UserInfoOptional user context for permissions and audit tracking
Promise resolving to the entity instance with the specified record loaded
Error if entity name is not found, instantiation fails, or record cannot be loaded
Returns the Name of the specific recordId for a given entityName. This is done by looking for the IsNameField within the EntityFields collection for a given entity. If no IsNameField is found, but a field called "Name" exists, that value is returned. Otherwise null returned
Optional contextUser: UserInfothe name of the record
Protected GetReturns one or more record names using the same logic as GetEntityRecordName, but for multiple records at once - more efficient to use this method if you need to get multiple record names at once
Optional contextUser: UserInfoan array of EntityRecordNameResult objects
Protected GetProtected GetRetrieves the latest metadata update timestamps from the server.
Optional providerToUse: IMetadataProviderArray of metadata update information
Returns the timestamp of the local cached version of a given datasetName or null if there is no local cache for the specified dataset
the name of the dataset to check
Optional itemFilters: DatasetItemFilterType[]optional filters to apply to the dataset
Protected GetOptional contextUser: UserInfoReturns a list of dependencies - records that are linked to the specified Entity/RecordID combination. A dependency is as defined by the relationships in the database. The MemberJunction metadata that is used for this simply reflects the foreign key relationships that exist in the database. The CodeGen tool is what detects all of the relationships and generates the metadata that is used by MemberJunction. The metadata in question is within the EntityField table and specifically the RelatedEntity and RelatedEntityField columns. In turn, this method uses that metadata and queries the database to determine the dependencies. To get the list of entity dependencies you can use the utility method GetEntityDependencies(), which doesn't check for dependencies on a specific record, but rather gets the metadata in one shot that can be used for dependency checking.
the name of the entity to check
Optional contextUser: UserInfoProtected GetReturns a list of record IDs that are possible duplicates of the specified record.
Object containing many properties used in fetching records and determining which ones to return
Optional contextUser: UserInfoOptional contextUser: UserInfoChecks if a specific record is marked as a favorite by the user.
The ID of the user to check
The name of the entity
The primary key value(s) for the record
Optional contextUser: UserInfoOptional user context for permissions
True if the record is a favorite, false otherwise
Generates the SQL Statement that will Save a record to the database.
This method is used by the Save() method of this class, but it is marked as public because it is also used by the SQLServerTransactionGroup to regenerate Save SQL if any values were changed by the transaction group due to transaction variables being set into the object.
The entity to generate save SQL for
Whether this is a new record (create) or existing record (update)
The stored procedure name to call
The user context for the operation
The full SQL statement for the save operation
This method handles field-level encryption transparently. Fields marked with Encrypt=true will have their values encrypted before being included in the SQL statement.
Private GetThis function generates both the full SQL (with record change metadata) and the simple stored procedure call
Object with fullSQL and simpleSQL properties
This method handles field-level encryption transparently. Fields marked with Encrypt=true will have their values encrypted before being included in the SQL statement.
Protected GetThis function will generate SQL statements for all of the possible soft links that are not traditional foreign keys but exist in entities where there is a column that has the EntityIDFieldName set to a column name (not null). We need to get a list of all such soft link fields across ALL entities and then generate queries for each possible soft link in the same format as the hard links
Protected GetProtected HandleHandles Entity AI Actions. Parameters are setup for a future support of delete actions, but currently that isn't supported so the baseType parameter isn't fully functional. If you pass in delete, the function will just exit for now, and in the future calling code will start working when we support Delete as a trigger event for Entity AI Actions...
Protected HandleInternal Handles entity actions (non-AI) for save, delete, or validate operations
The entity being operated on
The type of operation
Whether this is before or after the operation
The user performing the operation
Array of action results
Protected InternalInternal implementation of batch query execution. Runs multiple queries in parallel for efficiency.
Array of query parameters
Optional contextUser: UserInfoOptional user context for permissions
Array of query results
Protected InternalOptional contextUser: UserInfoProtected InternalOptional contextUser: UserInfoProtected InternalInternal implementation of RunViews that subclasses must provide. This method should ONLY contain the batch data fetching logic - no pre/post processing. The base class handles all orchestration (telemetry, caching, transformation).
Array of view parameters
Optional contextUser: UserInfoOptional user context for permissions
This routine checks to see if the local cache version of a given datasetName/itemFilters combination is up to date with the server or not
Optional itemFilters: DatasetItemFilterType[]Determines if a given datasetName/itemFilters combination is cached locally or not
Optional itemFilters: DatasetItemFilterType[]Protected LoadProtected LogProtected MapThis method will merge two or more records based on the request provided. The RecordMergeRequest type you pass in specifies the record that will survive the merge, the records to merge into the surviving record, and an optional field map that can update values in the surviving record, if desired. The process followed is:
The return value from this method contains detailed information about the execution of the process. In addition, all attempted merges are logged in the RecordMergeLog and RecordMergeDeletionLog tables.
Optional contextUser: UserInfoOptional options: EntityMergeOptionsDetermines whether the database driver requires adjustment for datetimeoffset fields. This method performs an empirical test on first use to detect if the driver (e.g., mssql) incorrectly handles timezone information in datetimeoffset columns.
True if datetimeoffset values need timezone adjustment, false otherwise
const provider = new SQLServerDataProvider();
if (await provider.NeedsDatetimeOffsetAdjustment()) {
console.log('Driver requires datetimeoffset adjustment');
}
Some database drivers (notably TypeORM) incorrectly interpret SQL Server's datetimeoffset values as local time instead of respecting the timezone offset. This method detects this behavior by inserting a known UTC time and checking if it's retrieved correctly. The test is performed only once and the result is cached for performance.
Protected PostPost-processes entity metadata to establish relationships between entities and their child objects. Links fields, permissions, relationships, and settings to their parent entities.
Array of entity metadata
Array of entity field metadata
Array of entity field value metadata
Array of entity permission metadata
Array of entity relationship metadata
Array of entity settings metadata
Processed array of EntityInfo instances with all relationships established
Protected PostBase class post-processor that all sub-classes should call after they finish their RunView process
Optional contextUser: UserInfoProtected PostBase class utilty method that should be called after each sub-class handles its internal RunViews() process before returning results This handles the optional conversion of simple objects to entity objects for each requested view depending on if the params requests a result_type === 'entity_object'
Optional contextUser: UserInfoProtected PostPost-processing hook for RunQueries (batch). Handles telemetry end.
Array of query results
Array of query parameters
The pre-processing result
Optional cacheOptional cachedOptional telemetryOptional uncachedOptional contextUser: UserInfoOptional user context
Protected PostPost-processing hook for RunQuery. Handles cache storage and telemetry end.
The query result
The query parameters
The pre-processing result
Optional cachedOptional fingerprint?: stringOptional telemetryOptional contextUser: UserInfoOptional user context
Protected PostPost-processing hook for RunView. Handles result transformation, cache storage, and telemetry end.
The view result
The view parameters
The pre-processing result
Optional cachedOptional fingerprint?: stringOptional telemetryOptional contextUser: UserInfoOptional user context
Protected PostPost-processing hook for RunViews (batch). Handles result transformation, cache storage, and telemetry end.
Array of view results
Array of view parameters
The pre-processing result
Optional cacheOptional cachedOptional smartWhen CacheLocal is enabled, contains the cache check params to send to server
Optional telemetryOptional uncachedOptional useWhen CacheLocal is enabled, indicates we should use smart cache check
Optional contextUser: UserInfoOptional user context
Protected PreOptional contextUser: UserInfoUse PreRunView instead. This method is kept for backward compatibility.
Protected PreBase class implementation for handling pre-processing of RunViews() each sub-class should call this within their RunViews() method implementation
Optional contextUser: UserInfoProtected PrePre-processing hook for RunQueries (batch). Handles telemetry for batch query operations.
Array of query parameters
Optional contextUser: UserInfoOptional user context
Pre-processing result
Protected PrePre-processing hook for RunQuery. Handles telemetry and cache lookup.
The query parameters
Optional contextUser: UserInfoOptional user context
Pre-processing result with cache status and optional cached result
Protected PrePre-processing hook for RunView. Handles telemetry, validation, entity status check, and cache lookup.
The view parameters
Optional contextUser: UserInfoOptional user context
Pre-processing result with cache status and optional cached result
Protected PrePre-processing hook for RunViews (batch). Handles telemetry, validation, and cache lookup for multiple views.
Array of view parameters
Optional contextUser: UserInfoOptional user context
Pre-processing result with cache status for each view
Processes entity rows returned from SQL Server to handle:
This method specifically handles the conversion of datetime2 fields (which SQL Server returns without timezone info) to proper UTC dates, preventing JavaScript from incorrectly interpreting them as local time.
For encrypted fields, this method decrypts values at the data provider level. API-level filtering (AllowDecryptInAPI/SendEncryptedValue) is handled by the GraphQL layer.
The raw result rows from SQL Server
The entity metadata to determine field types
Optional contextUser: UserInfoOptional user context for decryption operations
The processed rows with corrected datetime values and decrypted fields
Encrypted fields are decrypted here for internal use. The API layer handles response filtering based on AllowDecryptInAPI settings.
Refreshes all metadata from the server. Respects the AllowRefresh flag from subclasses.
Optional providerToUse: IMetadataProviderTrue if refresh was initiated or allowed
Refreshes the remote metadata timestamps from the server. Updates the internal cache of remote timestamps.
Optional providerToUse: IMetadataProviderTrue if timestamps were successfully refreshed
Protected RenderThis method will check to see if the where clause for the view provided has any templating within it, and if it does will replace the templating with the appropriate run-time values. This is done recursively with depth-first traversal so that if there are nested templates, they will be replaced as well. We also maintain a stack to ensure that any possible circular references are caught and an error is thrown if that is the case.
Runs multiple queries based on the provided parameters. This method orchestrates the full execution flow for batch query operations.
Array of query parameters
Optional contextUser: UserInfoOptional user context for permissions (required server-side)
Array of query results
RunQueriesWithCacheCheck - Smart cache validation for batch RunQueries. For each query request, if cacheStatus is provided, uses the Query's CacheValidationSQL to check if the cached data is still current by comparing MAX(__mj_UpdatedAt) and COUNT(*) with client's values. Returns 'current' if cache is valid (no data), or 'stale' with fresh data.
Queries without CacheValidationSQL configured will return 'no_validation' status with full data.
Optional contextUser: UserInfoRuns a query based on the provided parameters. This method orchestrates the full execution flow: pre-processing, cache check, internal execution, post-processing, and cache storage.
The query parameters
Optional contextUser: UserInfoOptional user context for permissions (required server-side)
The query results
Optional contextUser: UserInfoRuns a view based on the provided parameters. This method orchestrates the full execution flow: pre-processing, cache check, internal execution, post-processing, and cache storage.
The view parameters
Optional contextUser: UserInfoOptional user context for permissions (required server-side)
The view results
Runs multiple views based on the provided parameters. This method orchestrates the full execution flow for batch operations.
Array of view parameters
Optional contextUser: UserInfoOptional user context for permissions (required server-side)
Array of view results
RunViewsWithCacheCheck - Smart cache validation for batch RunViews. For each view request, if cacheStatus is provided, first checks if the cache is current by comparing MAX(__mj_UpdatedAt) and COUNT(*) with client's values. Returns 'current' if cache is valid (no data), or 'stale' with fresh data if cache is outdated.
Optimized to batch all cache status checks into a single SQL call with multiple result sets.
Optional contextUser: UserInfoSets or removes a record's favorite status for a user.
The ID of the user
The name of the entity
The primary key value(s) for the record
True to mark as favorite, false to remove
User context for permissions (required)
Protected StartProtected TransformTransforms the result set from simple objects to entity objects if needed.
The RunViewParams used for the request
The RunViewResult returned from the request
Optional contextUser: UserInfoThe user context for permissions
Protected UpdateUpdates the local metadata cache with new data.
The new metadata to store locally
Private _internalPrivate Internal centralized method for executing SQL queries with consistent transaction and connection handling. This method ensures proper request object creation and management to avoid concurrency issues, particularly when using transactions where multiple operations may execute in parallel.
The SQL query to execute
Optional parameters: anyOptional parameters for the query (array for positional, object for named)
Optional connectionSource: ConnectionPool | Transaction | RequestOptional specific connection source (pool, transaction, or request)
Optional loggingOptions: { Optional logging configuration
Optional contextOptional description?: stringOptional ignoreOptional isOptional simpleSQLFallback?: stringPromise<sql.IResult
Rethrows any SQL execution errors after logging
Private _internalInternal SQL execution method for instance calls - routes queries based on transaction state
Optional options: InternalSQLOptionsPrivate _logInternal method to log SQL statement to all active logging sessions. This is called automatically by ExecuteSQL methods.
The SQL query being executed
Optional parameters: anyParameters for the query
Optional description: stringOptional description for this operation
If true, this statement will not be logged
Whether this is a data mutation operation
Optional simpleSQLFallback: stringOptional simple SQL to use for loggers with logRecordChangeMetadata=false
Optional contextUser: UserInfoProtected applyApplies pagination to query results based on StartRow and MaxRows parameters
Protected auditCreates an audit log record for query execution (fire-and-forget)
Optional contextUser: UserInfoProtected buildBuilds the WHERE clause for cache status check, using same logic as InternalRunView.
Protected cacheCaches query results if caching is enabled for the query
Protected checkChecks the cache for existing results and returns them if valid
Protected createProtected escapeRecursively escapes quotes in all string properties of an object or array. This method traverses through nested objects and arrays, escaping the specified quote character in all string values to prevent SQL injection and syntax errors.
The object, array, or primitive value to process
The quote character to escape (typically single quote "'")
A new object/array with all string values having quotes properly escaped. Non-string values are preserved as-is.
// Escaping single quotes in a nested object
const input = {
name: "John's Company",
details: {
description: "It's the best",
tags: ["Won't fail", "Can't stop"]
}
};
const escaped = this.escapeQuotesInProperties(input, "'");
// Result: {
// name: "John''s Company",
// details: {
// description: "It''s the best",
// tags: ["Won''t fail", "Can''t stop"]
// }
// }
This method is essential for preparing data to be embedded in SQL strings. It handles:
Protected executeExecutes the query and tracks execution time
Optional contextUser: UserInfoProtected executeSQLForProtected extractProtected findFinds a query based on provided parameters and validates user permissions
Optional contextUser: UserInfoProtected findFinds a query by ID or by Name+Category combination. Supports both direct CategoryID lookup and hierarchical CategoryPath path resolution.
Unique identifier for the query
Name of the query to find
Direct category ID for the query
Hierarchical category path (e.g., "/MJ/AI/Agents/") or simple category name
Whether to refresh metadata if query is not found
The found QueryInfo or null if not found
Private generateSPParamsGenerates the stored procedure parameters for a save operation.
This method handles:
The entity being saved
Whether this is an update (true) or create (false) operation
Optional contextUser: UserInfoThe user context for encryption operations
An object containing the SQL components for the stored procedure call
Fields with Encrypt=true are encrypted before being sent to the database. Encryption uses the key specified in EncryptionKeyID.
Private generateGenerates the value portion of a SET statement for a field
The field info
The value to set
SQL value string
Private generatePrivate getProtected getExecutes a batched cache status check for multiple queries using their CacheValidationSQL.
Optional contextUser: UserInfoProtected getExecutes a batched cache status check for multiple views in a single SQL call. Uses multiple result sets to return status for each view efficiently.
Optional contextUser: UserInfoProtected getProtected getPrivate initializeProtected isCompares client cache status with server status to determine if cache is current.
Optional maxOptional rowProtected mergeMerges cached and fresh results for RunViews, maintaining original order.
The pre-processing result with cache info
Optional cacheOptional cachedOptional smartWhen CacheLocal is enabled, contains the cache check params to send to server
Optional telemetryOptional uncachedOptional useWhen CacheLocal is enabled, indicates we should use smart cache check
The fresh results from InternalRunViews
Combined results in original order
Protected mergeMerges cached and fresh results for RunQueries, maintaining original order.
The pre-processing result with cache info
Optional cacheOptional cachedOptional telemetryOptional uncachedThe fresh results from InternalRunQueries
Combined results in original order
Protected packageSPParamReturns a string that packages the parameter value for the stored procedure call. It will handle quoting the value based on the quoteString provided and will also handle null values by returning 'NULL' as a string. Finally, the prefix is used for unicode fields to add the 'N' prefix if needed.
Private processProtected processProcesses query parameters and applies template substitution if needed
Optional parameters: Record<string, any>Private resolveResolves a hierarchical category path (e.g., "/MJ/AI/Agents/") to a CategoryID. The path is split by "/" and each segment is matched case-insensitively against category names, walking down the hierarchy from root to leaf.
The hierarchical category path (e.g., "/MJ/AI/Agents/")
The CategoryID if the path exists, null otherwise
Protected resolveResolves QueryInfo from RunQueryParams (by ID or Name+CategoryPath).
Protected runRuns the full query and returns results with cache metadata.
Optional contextUser: UserInfoProtected runRuns the full query and returns results with cache metadata.
Optional contextUser: UserInfoOptional queryId: stringPrivate testProtected trimProtected validateStatic ExecuteSQLBatchStatic method to execute a batch of SQL queries using a provided connection source. This allows the batch logic to be reused from external contexts like TransactionGroup. All queries are combined into a single SQL statement and executed together within the same connection/transaction context for optimal performance.
Either a sql.ConnectionPool, sql.Transaction, or sql.Request to use for execution
Array of SQL queries to execute
Optional parameters: any[][]Optional array of parameter arrays, one for each query
Optional contextUser: UserInfoPromise<any[][]> - Array of result arrays, one for each query
Static ExecuteSQLWithStatic helper method for executing SQL queries on an external connection pool. This method is designed to be used by generated code where a connection pool is passed in from the context. It returns results as arrays for consistency with the expected behavior in generated resolvers.
The mssql ConnectionPool to execute the query on
The SQL query to execute
Optional parameters: anyOptional parameters for the query
Optional contextUser: UserInfoPromise<any[]> - Array of results (empty array if no results)
Static LogSQLStatementStatic method to log SQL statements from external sources like transaction groups
The SQL query being executed
Optional parameters: anyParameters for the query
Optional description: stringOptional description for this operation
Whether this is a data mutation operation
Optional simpleSQLFallback: stringOptional simple SQL to use for loggers with logRecordChangeMetadata=false
Optional contextUser: UserInfoPrivate Static _internalStatic SQL execution method - for static methods like ExecuteSQLWithPool Static methods don't have access to instance queues, so they execute directly Transactions are not supported in static context
Optional options: InternalSQLOptions
SQL Server implementation of the MemberJunction data provider interfaces.
This class provides comprehensive database functionality including:
Example