apiVersion: v1
kind: ConfigMap
metadata:
  name: benthos-max-to-table
data:
  benthos.yaml: |-
    input:
      generate:
        interval: '@every 5s'
        mapping: 'root = {}'
      processors:
        - sql:
            driver: postgres
            data_source_name: ${BENTHOS_TENANT_DB}
            query: |
              SELECT time_bucket('5 seconds', time) AS time, app, module, max((payload->>'x')::numeric) as x, max((payload->>'y')::numeric) as y, max((payload->>'z')::numeric) as z
              FROM demo
              WHERE time > now() - interval '10 seconds'
              GROUP BY 1, 2, 3;
            result_codec: json_array
    pipeline:
      processors:
        - unarchive:
            format: json_array

    output:
      processors:
        - bloblang: |
            root = this
            meta time = this.time
            root.time = deleted()
            meta originApp = this.app
            root.app = deleted()
            meta originModule = this.module
            root.module = deleted()

      sql:
        driver: postgres
        data_source_name: ${BENTHOS_TENANT_DB}
        query: |
          INSERT INTO "accmaximumvalues" (time, app, module, payload)
          VALUES ($1, $2, $3, $4);
        args:
          - ${! meta("time") }
          - ${! meta("originApp") }
          - ${! meta("originModule") }
          - ${! json() }
