Listener on Schema

This page explains listeners: expressions that λORM runs before or after a query, or when it fails. They are defined in application.listeners (see Listener).

  • on: the categories of query that trigger the listener: select, insert, upsert, update and delete. A bulk insert belongs to the insert category, and a merge to the upsert category.
  • condition: an expression that decides whether the listener runs.
  • before, after and error: the expressions to run before the query, after it, or when it fails.
  • transactional: whether the listener runs inside the query's transaction (default true).

How listeners run

  • before, after and error run one after the other and are awaited: orm.execute returns when they have finished. An error in before prevents the sentence; an error in after fails it (the error listeners run first).
  • They run in the sentence's transaction: the orm.execute calls of a listener use the same connections, and a rollback undoes what they wrote. A sentence with listeners that runs on its own opens a transaction for the sentence and its listeners, so both are all or nothing.
  • A listener's orm.execute can name another stage ({ stage: "insights" }): it joins the same transaction (since @lambdaorm/lib 3.3.0).
  • transactional: false runs a listener outside the transaction: what it writes is kept even if the transaction rolls back (for example, an audit log).

In this example, touchInstallation updates the installation of each inserted file in the same transaction, and audit writes an audit log that is kept even if the transaction rolls back:

application:
  listeners:
    - name: touchInstallation
      on: [insert]
      condition: entity == "InstallationFiles"
      after: >-
        orm.execute("Installations.update(p => ({ lastEventAt: at })).filter(p => p.id == id)",
          { id: data.installationId, at: data.uploadedAt })
    - name: audit
      on: [insert, update, delete]
      transactional: false
      after: orm.execute("AuditLogs.insert()", { entity: entity, action: action })

Arguments

The arguments available in condition, before, after and error:

Parameter Description
query The query expression that was executed
data The data that was sent when the expression was executed
options The options that were sent when the expression was executed
result It is only available in the after event and contains the result of the expression execution
action The action that was executed (select, insert, bulkInsert, update, upsert, merge, bulkMerge, delete, bulkDelete)
type The type of sentence that was executed (dql, dml)
category The category of the sentence that was executed (select, insert, update, delete, upsert)
sentence The sentence that was executed
dialect The dialect of the source where the sentence was executed
source The source where the sentence was executed
entity The entity that was affected by the sentence
error It is only available in the error event and contains the error that occurred

Listener Example

This example declares a listener that copies the data to the insights stage (CQRS pattern). When records are inserted, updated or deleted on the default or cqrs stage, the listener runs. Its after expression executes the same query, with the same data, on the insights stage, in the same transaction as the original query: if the write in insights fails, the original one is rolled back too.

Part of the schema where the listener is defined:

...
application:
  listeners:
    - name: syncInsights
      on: [insert, update, delete]
      condition: options.stage.in("default","cqrs")
      after: orm.execute(query,data,{stage:"insights"}) 

Complete schema:

The default stage spreads the entities over MySQL, PostgreSQL and MongoDB, the insights stage stores everything in another PostgreSQL database, and the cqrs stage reads from insights and writes to the sources of default.

domain:  
  enums:
  entities:
  - name: Address
    abstract: true
    indexes:
    - name: postalCode
      fields: ["postalCode"]
    - name: region
      fields: ["region", "country"]
    - name: city
      fields: ["city"]
    properties:
    - name: address
    - name: city
    - name: region
    - name: postalCode
      length: 20
    - name: country
  - name: Categories
    primaryKey: ["id"]
    uniqueKey: ["name"]
    properties:
    - name: id
      type: integer
      required: true
      autoIncrement: true
    - name: name
      required: true
  - name: Customers
    extends: Address
    primaryKey: ["id"]
    indexes:
    - name: name
      fields: ["name"]
    properties:
    - name: id
      length: 5
      required: true
    - name: name
      required: true
  - name: Products
    primaryKey: ["id"]
    uniqueKey: ["name", "supplierId"]
    properties:
    - name: id
      type: integer
      required: true
      autoIncrement: true
    - name: name
      required: true
    - name: categoryId
      type: integer
    - name: quantity
    - name: price
      type: decimal
      default: 0
    relations:
    - name: category
      from: categoryId
      entity: Categories
      to: id
      target: products
  - name: Orders
    primaryKey: ["id"]
    indexes:
    - name: orderDate
      fields: ["orderDate"]
    properties:
    - name: id
      type: integer
      required: true
      autoIncrement: true
    - name: customerId
      required: true
      length: 5
    - name: orderDate
      type: dateTime 
    relations:
    - name: customer
      from: customerId
      entity: Customers
      to: id
      target: orders
  - name: Orders.details
    primaryKey: ["orderId", "productId"]
    properties:
    - name: orderId
      required: true
      type: integer
    - name: productId
      required: true
      type: integer
    - name: unitPrice
      type: decimal
    - name: quantity
      type: decimal
    relations:
    - name: order
      from: orderId
      entity: Orders
      to: id
      target: details
    - name: product
      from: productId
      entity: Products
      to: id
      target: orderDetails
infrastructure:
  views:
  - name: default  
  mappings:
  - name: default
    entities:
    - name: Address
      abstract: true
      properties:
      - name: address
        mapping: Address
      - name: city
        mapping: City
      - name: region
        mapping: Region
      - name: postalCode
        mapping: PostalCode
      - name: country
        mapping: Country
    - name: Categories
      mapping: Categories
      properties:
      - name: id
        mapping: CategoryID
      - name: name
        mapping: CategoryName
    - name: Customers
      extends: Address
      mapping: Customers
      properties:
      - name: id
        mapping: CustomerID
      - name: name
        mapping: CompanyName
    - name: Products
      mapping: Products
      properties:
      - name: id
        mapping: ProductID
      - name: name
        mapping: ProductName
      - name: categoryId
        mapping: CategoryID
      - name: quantity
        mapping: QuantityPerUnit
      - name: price
        mapping: UnitPrice
    - name: Orders
      mapping: Orders
      properties:
      - name: id
        mapping: OrderID
      - name: customerId
        mapping: CustomerID
      - name: orderDate
        mapping: OrderDate
    - name: Orders.details
      mapping: Order Details
      properties:
      - name: orderId
        mapping: OrderID
      - name: productId
        mapping: ProductID
      - name: unitPrice
        mapping: UnitPrice
      - name: quantity
        mapping: Quantity
  - name: mongoDb
    extends: default
    entities:
      - name: Orders
        sequence: SQ_ORDERS
        properties:
          - name: id
            mapping: _id
  sources:
  - name: Catalog      
    dialect: MySQL
    mapping: default
    connection: ${CNN_MYSQL}      
  - name: Crm    
    dialect: PostgreSQL
    mapping: default
    connection: ${CNN_POSTGRES}
  - name: Ordering
    dialect: MongoDB
    mapping: mongoDb      
    connection: ${CNN_MONGODB}
  - name: Insights    
    dialect: PostgreSQL
    mapping: default
    connection: ${CNN_INSIGHTS}      
  stages:
  - name: default
    sources:
    - name: Catalog
      condition: entity.in(["Categories","Products"])
    - name: Crm
      condition: entity.in(["Address","Customers"])
    - name: Ordering
      condition: entity.in(["Orders","Orders.details"])
  - name: insights
    sources:
    - name: Insights
  - name: cqrs
    sources:
    - name: Insights
      condition: action == "select"
    - name: Catalog
      condition: entity.in(["Categories","Products"])
    - name: Crm
      condition: entity.in(["Address","Customers"])
    - name: Ordering
      condition: entity.in(["Orders","Orders.details"])    
application:
  listeners:
    - name: syncInsights
      on: [insert, update, delete]
      condition: options.stage.in("default","cqrs")
      after: orm.execute(query,data,{stage:"insights"}) 

Labs