SELECT
  "c"."relname" AS "table",
  "a"."attname" AS "field",
  COALESCE("a"."attnum" = ANY("i"."indkey"), FALSE) AS "main",
  "t"."typname" AS "type",
  "a"."attndims" AS "dims",
  NOT "a"."attnotnull" AS "null",
  col_description("c"."oid", "a"."attnum") AS "info",
  ARRAY["r"."relname", "r"."attname"] as "refs"
FROM
  "pg_namespace" "n"
JOIN
  "pg_class" "c"
ON
  "c"."relnamespace" = "n"."oid"
LEFT JOIN
  "pg_index" "i"
ON
  "c"."oid" = "i"."indrelid"
  AND
  "i"."indisprimary"
JOIN
  "pg_attribute" "a"
ON
  "c"."oid" = "a"."attrelid"
JOIN
  "pg_type" "t"
ON
  "a"."atttypid" = "t"."oid"
LEFT OUTER JOIN
  (
    SELECT
      "s"."connamespace",
      "s"."conrelid",
      "s"."conkey",
      "c"."relname",
      "a"."attname",
      "s"."confkey",
      array_position("s"."confkey", "a"."attnum") AS "confpos"
    FROM
      "pg_constraint" "s"
    JOIN
      "pg_class" "c"
    ON
      "s"."confrelid" = "c"."oid"
    JOIN
      "pg_attribute" "a"
    ON
      "c"."oid" = "a"."attrelid"
      AND
      "a"."attnum" = ANY("s"."confkey")
    WHERE
      "s"."contype" = 'f'
  ) "r"
ON
  "r"."connamespace" = "n"."oid"
  AND
  "r"."conrelid" = "c"."oid"
  AND
  "a"."attnum" = ANY("r"."conkey")
  AND
  array_position("r"."conkey", "a"."attnum") = "r"."confpos"
WHERE
  "c"."relkind" = 'r'
  AND
  "c"."relpersistence" = 'p'
  AND
  "a"."attnum" > 0
  AND
  "n"."nspname" = 'api'
  AND
  NOT "a"."attisdropped";
