Member Junction
    Preparing search index...

    Catalog of stored queries. This is useful for any arbitrary query that is known to be performant and correct and can be reused. Queries can be viewed/run by a user, used programatically via RunQuery, and also used by AI systems for improved reliability instead of dynamically generated SQL. Queries can also improve security since they store the SQL instead of using dynamic SQL.

    Use MJQueryEntityExtended from @memberjunction/core-entities instead. MJQueryEntityExtended provides the same child-relationship getters and business logic with event-driven cache invalidation via QueryEngine.

    Hierarchy (View Summary)

    Implements

    Index

    Constructors

    Properties

    __mj_CreatedAt: Date = null

    Date and time when this query record was created

    __mj_UpdatedAt: Date = null

    Date and time when this query record was last updated

    AuditQueryRuns: boolean = false

    When true, all executions of this query will be logged to the Audit Log system for tracking and compliance

    CacheEnabled: boolean = false

    When true, query results will be cached in memory with TTL expiration

    CacheMaxSize: number = null

    Maximum number of cached result sets for this query. NULL uses default size limit.

    CacheTTLMinutes: number = null

    Time-to-live in minutes for cached query results. NULL uses default TTL.

    CacheValidationSQL: string = null

    SQL query that returns cache validation fingerprint data (MaxUpdatedAt, RowCount). Used for smart cache refresh to determine if cached data is stale without fetching full results. When provided, enables efficient server-side cache validation before sending full query results.

    The SQL should return exactly one row with two columns:

    • MaxUpdatedAt: DATETIME - The maximum __mj_UpdatedAt timestamp from the underlying data
    • RowCount: INT - The total number of rows that would be returned

    Example for a simple entity query:

    SELECT MAX(__mj_UpdatedAt) AS MaxUpdatedAt, COUNT(*) AS RowCount FROM [schema].[EntityView]
    

    For complex queries with filters/joins, the validation SQL should mirror the main query's data scope but only return the fingerprint metrics.

    Category: string = null

    Category name from the related Query Categories entity

    CategoryID: string = null

    Foreign key reference to the Query Categories entity

    Description: string = null

    Detailed description of what the query does and what data it returns

    EmbeddingModel: string = null

    The AI Model name used to generate the embedding vector

    EmbeddingModelID: string = null

    The AI Model ID used to generate the embedding vector for this query. Required for vector similarity comparisons.

    EmbeddingVector: string = null

    Optional JSON-serialized embedding vector for the query, used for similarity search and query analysis

    Feedback: string = null

    User feedback on query accuracy, performance, or suggested improvements

    ID: string = null

    Unique identifier for the query record

    Name: string = null

    Name of the query for display and reference

    OriginalSQL: string = null

    The original SQL before any optimization or modification, kept for reference and comparison

    PlatformVariants: string = null

    JSON column containing platform-specific SQL variants for multi-database support. Stores alternative SQL for platforms other than the default (typically SQL Server). Parsed at runtime via GetPlatformSQL() and GetPlatformCacheValidationSQL().

    Use the QuerySQL child table via GetPlatformSQL() instead.

    QualityRank: number = null

    Value indicating the quality of the query, higher values mean better quality

    Reusable: boolean = false

    When true, this query can be referenced by other queries using {{query:"..."}} composition syntax. Only queries with Reusable=true AND Status='Approved' can be composed into other queries.

    SQL: string = null

    The actual SQL query text to execute, may include Nunjucks template parameters

    SQLDialectID: string = null

    Foreign key to the SQL dialect this query's SQL column is written in. Defaults to T-SQL for backward compatibility.

    Status: "Pending" | "Approved" | "Rejected" | "Expired" = null

    Current status of the query in the approval workflow

    TechnicalDescription: string = null

    Technical documentation of the query logic, performance considerations, and parameter usage. Supports markdown content including mermaid diagrams.

    UsesTemplate: boolean = false

    Automatically set to true when the SQL column contains Nunjucks template markers like {{paramName}}

    Accessors

    • get CategoryPath(): string

      Gets the full hierarchical path of this query's category (e.g., "/MJ/AI/Agents/"). This provides a unique filepath-like identifier for the category hierarchy. Returns empty string if the query is not categorized.

      Returns string

      The category path with leading and trailing slashes

    • get IsComposable(): boolean

      Whether this query can be referenced by other queries via composition syntax. A query is composable only when both Reusable=true and Status='Approved'.

      Returns boolean

    Methods

    • Copies initialization data from a plain object to the class instance. Only copies properties that already exist on the class to prevent creating new fields. Special handling for DefaultValue fields to extract actual values from SQL Server syntax.

      Parameters

      • initData: any

        The initialization data object

      Returns void

    • Resolves CacheValidationSQL for a given database platform. Checks PlatformVariants first; falls back to the base CacheValidationSQL property.

      Parameters

      Returns string

      The appropriate CacheValidationSQL string, or null if none configured

    • Resolves the SQL for a given database platform. Resolution order:

      1. QuerySQL child table entry matching this query + platform's dialect
      2. PlatformVariants JSON (legacy approach)
      3. Base SQL property (the query's primary SQL)

      Parameters

      Returns string

      The appropriate SQL string for the platform

    • Default JSON serialization for BaseInfo subclasses.

      Emits all non-underscored direct field declarations. For _-prefixed private backing fields (the MJ pattern for collection storage — e.g. _Fields, _RelatedEntities, _OrganicKeys), emits the value of the corresponding same-named public getter instead. Purely computed getters without a backing field (display-name formatters, derived flags) are intentionally skipped — they can throw when source fields are null and don't belong on the wire anyway.

      Nested BaseInfo instances and arrays of them unwrap automatically via JSON.stringify's native toJSON() protocol.

      Subclasses may override to emit a filtered subset or custom shape (see EntityFieldValueInfo).

      Returns Record<string, unknown>

    • Checks if a user can run this query based on permissions. Non-approved queries are allowed to execute (with a server-side warning) to enable testing before formal approval.

      Parameters

      Returns boolean

      true if the user has permission to run the query

    • Checks if a user has permission to run this query based on their roles. A user can run a query if:

      1. The query has no permissions defined (open to all)
      2. The user has at least one role that is granted permission

      Parameters

      • user: UserInfo

        The user to check permissions for

      Returns boolean

      true if the user has permission to run the query