{
  "name": "ezGPT - PostgreSQL versioned UPSERT",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgupsert-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Product",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{\"sku\":\"SKU-001\",\"product_name\":\"Демо товар\",\"price_kopecks\":149900,\"source_version\":1}}];"
      },
      "id": "pgupsert-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check Product",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one product');\nconst p = items[0].json;\nconst keys = ['sku','product_name','price_kopecks','source_version'];\nif (Object.keys(p).length !== 4 || !keys.every(k => Object.hasOwn(p,k)) ||\n    typeof p.sku !== 'string' || !/^SKU-\\d{3}$/.test(p.sku) ||\n    typeof p.product_name !== 'string' || !p.product_name.trim() || p.product_name.length > 80 ||\n    /[\\u0000-\\u001f\\u007f]/.test(p.product_name) ||\n    Buffer.from(p.product_name,'utf8').toString('utf8') !== p.product_name ||\n    !Number.isSafeInteger(p.price_kopecks) || p.price_kopecks < 0 || p.price_kopecks > 100000000 ||\n    !Number.isSafeInteger(p.source_version) || p.source_version < 1 || p.source_version > 1000) {\n  throw new Error('Invalid product');\n}\nreturn [{json:p}];"
      },
      "id": "pgupsert-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Upsert Product",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH changed AS (\n  INSERT INTO app.products AS stored (sku, product_name, price_kopecks, source_version)\n  VALUES ($1, $2, $3, $4)\n  ON CONFLICT (sku) DO UPDATE\n  SET product_name = EXCLUDED.product_name,\n      price_kopecks = EXCLUDED.price_kopecks,\n      source_version = EXCLUDED.source_version\n  WHERE stored.source_version < EXCLUDED.source_version\n  RETURNING sku, product_name, price_kopecks, source_version\n)\nSELECT count(*)::integer AS applied_count,\n       COALESCE(jsonb_agg(to_jsonb(c)), '[]'::jsonb) AS rows\nFROM changed c;",
        "options": {
          "queryReplacement": "={{ [$json.sku, $json.product_name, $json.price_kopecks, $json.source_version] }}"
        }
      },
      "id": "pgupsert-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Write",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one write envelope');\nconst d = items[0].json;\nconst sent = $('Check Product').first().json;\nif (Object.keys(d).length !== 2 || ![0,1].includes(d.applied_count) ||\n    !Array.isArray(d.rows) || d.rows.length !== d.applied_count) {\n  throw new Error('Invalid write result');\n}\nif (d.applied_count === 1) {\n  const r = d.rows[0];\n  const keys = ['sku','product_name','price_kopecks','source_version'];\n  if (!r || Object.keys(r).length !== 4 || !keys.every(k => Object.hasOwn(r,k) && r[k] === sent[k])) {\n    throw new Error('Returned product differs from input');\n  }\n}\nreturn [{json:{sku:sent.sku, submitted_version:sent.source_version,\n  applied:d.applied_count === 1, record:d.rows[0] ?? null,\n  result:d.applied_count === 1 ? 'written' : 'not_applied',\n  verified:true, external_send:false}}];"
      },
      "id": "pgupsert-4",
      "position": [
        960,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Sample Product",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample Product": {
      "main": [
        [
          {
            "node": "Check Product",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Product": {
      "main": [
        [
          {
            "node": "Upsert Product",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Product": {
      "main": [
        [
          {
            "node": "Check Write",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
