graphile-build-pg 4.12.0 → 4.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +10 -3
  2. package/node8plus/GraphQLJSON.js.map +1 -1
  3. package/node8plus/QueryBuilder.js +3 -4
  4. package/node8plus/QueryBuilder.js.map +1 -1
  5. package/node8plus/index.d.ts +2 -6
  6. package/node8plus/index.js +84 -83
  7. package/node8plus/index.js.map +1 -1
  8. package/node8plus/inflections.js +1 -1
  9. package/node8plus/inflections.js.flow +1 -3
  10. package/node8plus/inflections.js.map +1 -1
  11. package/node8plus/omit.js +2 -2
  12. package/node8plus/omit.js.flow +1 -1
  13. package/node8plus/omit.js.map +1 -1
  14. package/node8plus/plugins/PgAllRows.js.flow +2 -3
  15. package/node8plus/plugins/PgAllRows.js.map +1 -1
  16. package/node8plus/plugins/PgBackwardRelationPlugin.js +2 -2
  17. package/node8plus/plugins/PgBackwardRelationPlugin.js.flow +22 -18
  18. package/node8plus/plugins/PgBackwardRelationPlugin.js.map +1 -1
  19. package/node8plus/plugins/PgBasicsPlugin.js +3 -3
  20. package/node8plus/plugins/PgBasicsPlugin.js.flow +120 -120
  21. package/node8plus/plugins/PgBasicsPlugin.js.map +1 -1
  22. package/node8plus/plugins/PgColumnsPlugin.js +1 -1
  23. package/node8plus/plugins/PgColumnsPlugin.js.flow +5 -2
  24. package/node8plus/plugins/PgColumnsPlugin.js.map +1 -1
  25. package/node8plus/plugins/PgComputedColumnsPlugin.js +4 -4
  26. package/node8plus/plugins/PgComputedColumnsPlugin.js.flow +1 -1
  27. package/node8plus/plugins/PgComputedColumnsPlugin.js.map +1 -1
  28. package/node8plus/plugins/PgConnectionArgCondition.js.flow +4 -4
  29. package/node8plus/plugins/PgConnectionArgCondition.js.map +1 -1
  30. package/node8plus/plugins/PgConnectionArgOrderBy.js +1 -1
  31. package/node8plus/plugins/PgConnectionArgOrderBy.js.flow +1 -1
  32. package/node8plus/plugins/PgConnectionArgOrderBy.js.map +1 -1
  33. package/node8plus/plugins/PgConnectionArgOrderByDefaultValue.js +2 -1
  34. package/node8plus/plugins/PgConnectionArgOrderByDefaultValue.js.flow +2 -1
  35. package/node8plus/plugins/PgConnectionArgOrderByDefaultValue.js.map +1 -1
  36. package/node8plus/plugins/PgForwardRelationPlugin.js.flow +9 -8
  37. package/node8plus/plugins/PgForwardRelationPlugin.js.map +1 -1
  38. package/node8plus/plugins/PgIntrospectionPlugin.js +5 -5
  39. package/node8plus/plugins/PgIntrospectionPlugin.js.flow +13 -12
  40. package/node8plus/plugins/PgIntrospectionPlugin.js.map +1 -1
  41. package/node8plus/plugins/PgJWTPlugin.js.flow +2 -3
  42. package/node8plus/plugins/PgJWTPlugin.js.map +1 -1
  43. package/node8plus/plugins/PgMutationCreatePlugin.js.flow +2 -3
  44. package/node8plus/plugins/PgMutationCreatePlugin.js.map +1 -1
  45. package/node8plus/plugins/PgMutationPayloadEdgePlugin.js +2 -1
  46. package/node8plus/plugins/PgMutationPayloadEdgePlugin.js.flow +2 -1
  47. package/node8plus/plugins/PgMutationPayloadEdgePlugin.js.map +1 -1
  48. package/node8plus/plugins/PgMutationUpdateDeletePlugin.js +4 -4
  49. package/node8plus/plugins/PgMutationUpdateDeletePlugin.js.flow +14 -19
  50. package/node8plus/plugins/PgMutationUpdateDeletePlugin.js.map +1 -1
  51. package/node8plus/plugins/PgOrderByPrimaryKeyPlugin.js +4 -3
  52. package/node8plus/plugins/PgOrderByPrimaryKeyPlugin.js.flow +3 -3
  53. package/node8plus/plugins/PgOrderByPrimaryKeyPlugin.js.map +1 -1
  54. package/node8plus/plugins/PgOrderComputedColumnsPlugin.js.flow +3 -5
  55. package/node8plus/plugins/PgOrderComputedColumnsPlugin.js.map +1 -1
  56. package/node8plus/plugins/PgQueryProceduresPlugin.js +2 -2
  57. package/node8plus/plugins/PgQueryProceduresPlugin.js.map +1 -1
  58. package/node8plus/plugins/PgRecordFunctionConnectionPlugin.js.flow +4 -6
  59. package/node8plus/plugins/PgRecordFunctionConnectionPlugin.js.map +1 -1
  60. package/node8plus/plugins/PgRecordReturnTypesPlugin.js +3 -3
  61. package/node8plus/plugins/PgRecordReturnTypesPlugin.js.flow +5 -5
  62. package/node8plus/plugins/PgRecordReturnTypesPlugin.js.map +1 -1
  63. package/node8plus/plugins/PgRowByUniqueConstraint.js.flow +2 -3
  64. package/node8plus/plugins/PgRowByUniqueConstraint.js.map +1 -1
  65. package/node8plus/plugins/PgRowNode.js.flow +9 -11
  66. package/node8plus/plugins/PgRowNode.js.map +1 -1
  67. package/node8plus/plugins/PgTablesPlugin.js +13 -13
  68. package/node8plus/plugins/PgTablesPlugin.js.flow +8 -13
  69. package/node8plus/plugins/PgTablesPlugin.js.map +1 -1
  70. package/node8plus/plugins/PgTypesPlugin.js +7 -7
  71. package/node8plus/plugins/PgTypesPlugin.js.flow +28 -34
  72. package/node8plus/plugins/PgTypesPlugin.js.map +1 -1
  73. package/node8plus/plugins/debugSql.js +1 -1
  74. package/node8plus/plugins/introspectionQuery.js.map +1 -1
  75. package/node8plus/plugins/makeProcField.js +5 -5
  76. package/node8plus/plugins/makeProcField.js.flow +2 -6
  77. package/node8plus/plugins/makeProcField.js.map +1 -1
  78. package/node8plus/plugins/pgField.js.flow +2 -4
  79. package/node8plus/plugins/pgField.js.map +1 -1
  80. package/node8plus/plugins/viaTemporaryTable.js +2 -2
  81. package/node8plus/plugins/viaTemporaryTable.js.map +1 -1
  82. package/node8plus/queryFromResolveDataFactory.js +3 -4
  83. package/node8plus/queryFromResolveDataFactory.js.flow +474 -464
  84. package/node8plus/queryFromResolveDataFactory.js.map +1 -1
  85. package/node8plus/utils.js +1 -1
  86. package/node8plus/utils.js.flow +1 -1
  87. package/node8plus/utils.js.map +1 -1
  88. package/node8plus/withPgClient.js +1 -1
  89. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/introspectionQuery.js"],"names":["makeIntrospectionQuery","serverVersionNum","options","pgLegacyFunctionsOnly","pgIgnoreRBAC","unionRBAC","module","exports"],"mappings":";;AACA;;;;;;;;AAQA,SAASA,sBAAT,CACEC,gBADF,EAEEC,OAGC,GAAG,EALN,EAMU;AACR,QAAM;AAAEC,IAAAA,qBAAqB,GAAG,KAA1B;AAAiCC,IAAAA,YAAY,GAAG;AAAhD,MAAyDF,OAA/D;AACA,QAAMG,SAAS,GAAI;;;;;;GAAnB;AAOA,SAAQ;;;;;;;;IAQN,CAACD,YAAD,GAAgB,WAAhB,GAA8B,EAAG;;;;MAI/B,CAACA,YAAD,GAAgBC,SAAhB,GAA4B,EAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QA2D7BJ,gBAAgB,IAAI,MAApB,GACI,mBADJ,GAEI,kDACL;QAECE,qBAAqB,GAChB;;;;;sDADgB,GAOhB;;;;;;;;4GASN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAiGCF,gBAAgB,IAAI,MAApB,GAA6B,iBAA7B,GAAiD,IAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QA8KtDA,gBAAgB,IAAI,KAApB,GACK;;;;;;;;4CADL,GAUI,EACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAtXL;AAwZD;;AAEDK,MAAM,CAACC,OAAP,GAAiB;AACfP,EAAAA;AADe,CAAjB","sourcesContent":["// @flow\n/*\n * IMPORTANT: when editing this file, ensure all operators (e.g. `@>`) are\n * specified in the correct namespace (e.g. `operator(pg_catalog.@>)`). It looks\n * weird, but it prevents clashes with extensions or user code that may\n * overload operators, e.g. extension `intarray` overloads `@>`.\n *\n * NOTE: I'm not doing this with `=` because that way lies madness.\n */\nfunction makeIntrospectionQuery(\n serverVersionNum: number,\n options: {\n pgLegacyFunctionsOnly?: boolean,\n pgIgnoreRBAC?: boolean,\n } = {}\n): string {\n const { pgLegacyFunctionsOnly = false, pgIgnoreRBAC = true } = options;\n const unionRBAC = `\n union all\n select pg_roles.oid _oid, pg_roles.*\n from pg_roles, accessible_roles, pg_auth_members\n where pg_auth_members.roleid = pg_roles.oid\n and pg_auth_members.member = accessible_roles._oid \n `;\n return `\\\n-- @see https://www.postgresql.org/docs/9.5/static/catalogs.html\n-- @see https://github.com/graphile/graphile-engine/blob/master/packages/graphile-build-pg/src/plugins/introspectionQuery.js\n--\n-- ## Parameters\n-- - \\`$1\\`: An array of strings that represent the namespaces we are introspecting.\n-- - \\`$2\\`: set true to include functions/tables/etc that come from extensions\nwith\n ${!pgIgnoreRBAC ? \"recursive\" : \"\"} accessible_roles as (\n select oid _oid, pg_roles.*\n from pg_roles\n where rolname = current_user\n ${!pgIgnoreRBAC ? unionRBAC : \"\"}\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-namespace.html\n namespace as (\n select\n 'namespace' as \"kind\",\n nsp.oid as \"id\",\n nsp.nspname as \"name\",\n dsc.description as \"description\"\n from\n pg_catalog.pg_namespace as nsp\n left join pg_catalog.pg_description as dsc on dsc.objoid = nsp.oid and dsc.classoid = 'pg_catalog.pg_namespace'::regclass\n where\n nsp.nspname = any ($1)\n order by\n nsp.nspname\n ),\n -- Select all of the remote procedures we can use in this schema. This comes\n -- first so that we can select types and classes using the information we get\n -- from it.\n --\n -- @see https://www.postgresql.org/docs/9.6/static/catalog-pg-proc.html\n procedure as (\n select\n 'procedure' as \"kind\",\n pro.oid as \"id\",\n pro.proname as \"name\",\n dsc.description as \"description\",\n pro.pronamespace as \"namespaceId\",\n nsp.nspname as \"namespaceName\",\n pro.proisstrict as \"isStrict\",\n pro.proretset as \"returnsSet\",\n case\n when pro.provolatile = 'i' then true\n when pro.provolatile = 's' then true\n else false\n end as \"isStable\",\n pro.prorettype as \"returnTypeId\",\n coalesce(pro.proallargtypes, pro.proargtypes) as \"argTypeIds\",\n coalesce(pro.proargmodes, array[]::text[]) as \"argModes\",\n coalesce(pro.proargnames, array[]::text[]) as \"argNames\",\n pro.pronargs as \"inputArgsCount\",\n pro.pronargdefaults as \"argDefaultsNum\",\n pro.procost as \"cost\",\n exists(select 1 from accessible_roles where has_function_privilege(accessible_roles.oid, pro.oid, 'EXECUTE')) as \"aclExecutable\",\n (select lanname from pg_catalog.pg_language where pg_language.oid = pro.prolang) as \"language\"\n from\n pg_catalog.pg_proc as pro\n left join pg_catalog.pg_description as dsc on dsc.objoid = pro.oid and dsc.classoid = 'pg_catalog.pg_proc'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = pro.pronamespace\n where\n pro.pronamespace in (select \"id\" from namespace) and\n -- Currently we don’t support functions with variadic arguments. In the\n -- future we may, but for now let’s just ignore functions with variadic\n -- arguments.\n -- TODO: Variadic arguments.\n pro.provariadic = 0 and\n -- Filter our aggregate functions and window functions.\n ${\n serverVersionNum >= 110000\n ? \"pro.prokind = 'f'\"\n : \"pro.proisagg = false and pro.proiswindow = false\"\n } and\n ${\n pgLegacyFunctionsOnly\n ? `\\\n -- We want to make sure the argument mode for all of our arguments is\n -- \\`IN\\` which means \\`proargmodes\\` will be null.\n pro.proargmodes is null and\n -- Do not select procedures that return \\`RECORD\\` (oid 2249).\n pro.prorettype operator(pg_catalog.<>) 2249 and`\n : `\\\n -- We want to make sure the argument modes for all of our arguments are\n -- \\`IN\\`, \\`OUT\\`, \\`INOUT\\`, or \\`TABLE\\` (not \\`VARIADIC\\`).\n (pro.proargmodes is null or pro.proargmodes operator(pg_catalog.<@) array['i','o','b','t']::\"char\"[]) and\n -- Do not select procedures that return \\`RECORD\\` (oid 2249) unless they\n -- have \\`OUT\\`, \\`INOUT\\`, or \\`TABLE\\` arguments to define the return type.\n (pro.prorettype operator(pg_catalog.<>) 2249 or pro.proargmodes && array['o','b','t']::\"char\"[]) and\n -- Do not select procedures that have \\`RECORD\\` arguments.\n (pro.proallargtypes is null or not (pro.proallargtypes operator(pg_catalog.@>) array[2249::oid])) and`\n }\n -- Do not select procedures that create range types. These are utility\n -- functions that really don’t need to be exposed in an API.\n pro.proname not in (\n select typ.typname\n from pg_catalog.pg_type as typ\n where typ.typtype = 'r'\n and typ.typnamespace = pro.pronamespace\n ) and\n -- Do not expose trigger functions (type trigger has oid 2279)\n pro.prorettype operator(pg_catalog.<>) 2279 and\n -- We don't want functions that will clash with GraphQL (treat them as private)\n pro.proname not like E'\\\\\\\\_\\\\\\\\_%' and\n -- We also don’t want procedures that have been defined in our namespace\n -- twice. This leads to duplicate fields in the API which throws an\n -- error. In the future we may support this case. For now though, it is\n -- too complex.\n (\n select count(pro2.*)\n from pg_catalog.pg_proc as pro2\n where pro2.pronamespace = pro.pronamespace\n and pro2.proname = pro.proname\n ) = 1 and\n ($2 is true or not exists(\n select 1\n from pg_catalog.pg_depend\n where pg_depend.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n and pg_depend.deptype = 'e'\n and pg_depend.classid = 'pg_catalog.pg_proc'::pg_catalog.regclass\n and pg_depend.objid = pro.oid\n ))\n order by\n pro.pronamespace, pro.proname\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-class.html\n class as (\n select\n 'class' as \"kind\",\n rel.oid as \"id\",\n rel.relname as \"name\",\n rel.relkind as \"classKind\",\n dsc.description as \"description\",\n rel.relnamespace as \"namespaceId\",\n nsp.nspname as \"namespaceName\",\n rel.reltype as \"typeId\",\n -- Here we determine whether or not we can use this class in a\n -- \\`SELECT\\`’s \\`FROM\\` clause. In order to determine this we look at them\n -- \\`relkind\\` column, if it is \\`i\\` (index) or \\`c\\` (composite), we cannot\n -- select this class. Otherwise we can.\n rel.relkind not in ('i', 'c') as \"isSelectable\",\n -- Here we are determining whether we can insert/update/delete a class.\n -- This is helpful as it lets us detect non-updatable views and then\n -- exclude them from being inserted/updated/deleted into. For more info\n -- on how \\`pg_catalog.pg_relation_is_updatable\\` works:\n --\n -- - https://www.postgresql.org/message-id/CAEZATCV2_qN9P3zbvADwME_TkYf2gR_X2cLQR4R+pqkwxGxqJg@mail.gmail.com\n -- - https://github.com/postgres/postgres/blob/2410a2543e77983dab1f63f48b2adcd23dba994e/src/backend/utils/adt/misc.c#L684\n -- - https://github.com/postgres/postgres/blob/3aff33aa687e47d52f453892498b30ac98a296af/src/backend/rewrite/rewriteHandler.c#L2351\n (pg_catalog.pg_relation_is_updatable(rel.oid, true)::bit(8) operator(pg_catalog.&) B'00010000') = B'00010000' as \"isDeletable\",\n (pg_catalog.pg_relation_is_updatable(rel.oid, true)::bit(8) operator(pg_catalog.&) B'00001000') = B'00001000' as \"isInsertable\",\n (pg_catalog.pg_relation_is_updatable(rel.oid, true)::bit(8) operator(pg_catalog.&) B'00000100') = B'00000100' as \"isUpdatable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'SELECT')) as \"aclSelectable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'INSERT')) as \"aclInsertable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'UPDATE')) as \"aclUpdatable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'DELETE')) as \"aclDeletable\"\n from\n pg_catalog.pg_class as rel\n left join pg_catalog.pg_description as dsc on dsc.objoid = rel.oid and dsc.objsubid = 0 and dsc.classoid = 'pg_catalog.pg_class'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = rel.relnamespace\n where\n rel.relpersistence in ('p') and\n -- We don't want classes that will clash with GraphQL (treat them as private)\n rel.relname not like E'\\\\\\\\_\\\\\\\\_%' and\n rel.relkind in ('r', 'v', 'm', 'c', 'f') and\n ($2 is true or not exists(\n select 1\n from pg_catalog.pg_depend\n where pg_depend.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n and pg_depend.deptype = 'e'\n and pg_depend.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n and pg_depend.objid = rel.oid\n ))\n order by\n rel.relnamespace, rel.relname\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-attribute.html\n attribute as (\n select\n 'attribute' as \"kind\",\n att.attrelid as \"classId\",\n att.attnum as \"num\",\n att.attname as \"name\",\n dsc.description as \"description\",\n att.atttypid as \"typeId\",\n nullif(att.atttypmod, -1) as \"typeModifier\",\n att.attnotnull as \"isNotNull\",\n att.atthasdef as \"hasDefault\",\n ${serverVersionNum >= 100000 ? \"att.attidentity\" : \"''\"} as \"identity\",\n exists(select 1 from accessible_roles where has_column_privilege(accessible_roles.oid, att.attrelid, att.attname, 'SELECT')) as \"aclSelectable\",\n exists(select 1 from accessible_roles where has_column_privilege(accessible_roles.oid, att.attrelid, att.attname, 'INSERT')) as \"aclInsertable\",\n exists(select 1 from accessible_roles where has_column_privilege(accessible_roles.oid, att.attrelid, att.attname, 'UPDATE')) as \"aclUpdatable\",\n -- https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=c62dd80cdf149e2792b13c13777a539f5abb0370\n att.attacl is not null and exists(select 1 from aclexplode(att.attacl) aclitem where aclitem.privilege_type = 'SELECT' and grantee in (select oid from accessible_roles)) as \"columnLevelSelectGrant\"\n from\n pg_catalog.pg_attribute as att\n left join pg_catalog.pg_description as dsc on dsc.objoid = att.attrelid and dsc.objsubid = att.attnum and dsc.classoid = 'pg_catalog.pg_class'::regclass\n where\n att.attrelid in (select \"id\" from class) and\n att.attnum > 0 and\n -- We don't want attributes that will clash with GraphQL (treat them as private)\n att.attname not like E'\\\\\\\\_\\\\\\\\_%' and\n not att.attisdropped\n order by\n att.attrelid, att.attnum\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-type.html\n type as (\n -- Use another \\`WITH\\` statement here, because our \\`WHERE\\` clause will need\n -- to use it.\n with type_all as (\n select\n 'type' as \"kind\",\n typ.oid as \"id\",\n typ.typname as \"name\",\n dsc.description as \"description\",\n typ.typnamespace as \"namespaceId\",\n -- We include the namespace name in types only because we select so\n -- many types that are outside of our core set of namespaces. Having\n -- the namespace name is super helpful when generating SQL, so\n -- conditionally having namespace names for types is a pain.\n nsp.nspname as \"namespaceName\",\n typ.typtype as \"type\",\n typ.typcategory as \"category\",\n typ.typnotnull as \"domainIsNotNull\",\n nullif(typ.typelem, 0) as \"arrayItemTypeId\",\n typ.typlen as \"typeLength\",\n (typ.typelem <> 0 and typ.typlen = -1) as \"isPgArray\",\n nullif(typ.typrelid, 0) as \"classId\",\n nullif(typ.typbasetype, 0) as \"domainBaseTypeId\",\n nullif(typ.typtypmod, -1) as \"domainTypeModifier\",\n typ.typdefaultbin is not null as \"domainHasDefault\",\n -- If this type is an enum type, let’s select all of its enum variants.\n --\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-enum.html\n case\n when typ.typtype = 'e' then array(\n select enm.enumlabel\n from pg_catalog.pg_enum as enm\n where enm.enumtypid = typ.oid\n order by enm.enumsortorder\n )\n else null\n end as \"enumVariants\",\n -- If this type is a range type, we want to select the sub type of the\n -- range.\n --\n -- @see https://www.postgresql.org/docs/9.6/static/catalog-pg-range.html\n case\n when typ.typtype = 'r' then (\n select rng.rngsubtype\n from pg_catalog.pg_range as rng\n where rng.rngtypid = typ.oid\n limit 1\n )\n else null\n end as \"rangeSubTypeId\"\n from\n pg_catalog.pg_type as typ\n left join pg_catalog.pg_description as dsc on dsc.objoid = typ.oid and dsc.classoid = 'pg_catalog.pg_type'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = typ.typnamespace\n )\n select\n *\n from\n type_all as typ\n where\n typ.id in (\n select \"typeId\" from class\n union all\n select \"typeId\" from attribute\n union all\n select \"returnTypeId\" from procedure\n union all\n select unnest(\"argTypeIds\") from procedure\n union all\n -- If this type is a base type for *any* domain type, we will include it\n -- in our selection. This may mean we fetch more types than we need, but\n -- the alternative is to do some funky SQL recursion which would be hard\n -- code to read. So we prefer code readability over selecting like 3 or\n -- 4 less type rows.\n --\n -- We also do this for range sub types and array item types.\n select \"domainBaseTypeId\" from type_all\n union all\n select \"rangeSubTypeId\" from type_all\n union all\n select \"arrayItemTypeId\" from type_all\n )\n order by\n \"namespaceId\", \"name\"\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-constraint.html\n \"constraint\" as (\n select distinct on (con.conrelid, con.conkey, con.confrelid, con.confkey)\n 'constraint' as \"kind\",\n con.oid as \"id\",\n con.conname as \"name\",\n con.contype as \"type\",\n con.conrelid as \"classId\",\n nullif(con.confrelid, 0) as \"foreignClassId\",\n dsc.description as \"description\",\n con.conkey as \"keyAttributeNums\",\n con.confkey as \"foreignKeyAttributeNums\"\n from\n pg_catalog.pg_constraint as con\n inner join class on (con.conrelid = class.id)\n left join pg_catalog.pg_description as dsc on dsc.objoid = con.oid and dsc.classoid = 'pg_catalog.pg_constraint'::regclass\n where\n -- Only get constraints for classes we have selected.\n con.conrelid in (select \"id\" from class where \"namespaceId\" in (select \"id\" from namespace)) and\n case\n -- If this is a foreign key constraint, we want to ensure that the\n -- foreign class is also in the list of classes we have already\n -- selected.\n when con.contype = 'f' then con.confrelid in (select \"id\" from class where \"namespaceId\" in (select \"id\" from namespace))\n -- Otherwise, this should be true.\n else true\n end and\n -- We only want foreign key, primary key, and unique constraints. We\n -- made add support for more constraints in the future.\n con.contype in ('f', 'p', 'u')\n order by\n con.conrelid, con.conkey, con.confrelid, con.confkey, con.conname\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-extension.html\n \"extension\" as (\n select\n 'extension' as \"kind\",\n ext.oid as \"id\",\n ext.extname as \"name\",\n ext.extnamespace as \"namespaceId\",\n nsp.nspname as \"namespaceName\",\n ext.extrelocatable as \"relocatable\",\n ext.extversion as \"version\",\n ext.extconfig as \"configurationClassIds\",\n dsc.description as \"description\"\n from\n pg_catalog.pg_extension as ext\n left join pg_catalog.pg_description as dsc on dsc.objoid = ext.oid and dsc.classoid = 'pg_catalog.pg_extension'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = ext.extnamespace\n order by\n ext.extname, ext.oid\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-index.html\n \"indexes\" as (\n select\n 'index' as \"kind\",\n idx.indexrelid as \"id\",\n idx_more.relname as \"name\",\n nsp.nspname as \"namespaceName\",\n idx.indrelid as \"classId\",\n idx.indnatts as \"numberOfAttributes\",\n idx.indisunique as \"isUnique\",\n idx.indisprimary as \"isPrimary\",\n idx.indimmediate as \"isImmediate\", -- enforce uniqueness immediately on insert\n idx.indisreplident as \"isReplicaIdentity\",\n idx.indisvalid as \"isValid\", -- if false, don't use for queries\n idx.indpred is not null as \"isPartial\", -- if true, index is not on on rows.\n idx.indkey as \"attributeNums\",\n am.amname as \"indexType\",\n ${\n serverVersionNum >= 90600\n ? `\\\n (\n select array_agg(pg_index_column_has_property(idx.indexrelid,n::int2,'asc'))\n from unnest(idx.indkey) with ordinality as ord(key,n)\n ) as \"attributePropertiesAsc\",\n (\n select array_agg(pg_index_column_has_property(idx.indexrelid,n::int2,'nulls_first'))\n from unnest(idx.indkey) with ordinality as ord(key,n)\n ) as \"attributePropertiesNullsFirst\",`\n : \"\"\n }\n dsc.description as \"description\"\n from\n pg_catalog.pg_index as idx\n inner join pg_catalog.pg_class idx_more on (idx.indexrelid = idx_more.oid)\n inner join class on (idx.indrelid = class.id)\n inner join pg_catalog.pg_namespace as nsp on (nsp.oid = idx_more.relnamespace)\n inner join pg_catalog.pg_am as am on (am.oid = idx_more.relam)\n left join pg_catalog.pg_description as dsc on dsc.objoid = idx.indexrelid and dsc.objsubid = 0 and dsc.classoid = 'pg_catalog.pg_class'::regclass\n where\n idx.indislive is not false and\n idx.indisexclusion is not true and -- exclusion index\n idx.indcheckxmin is not true and -- always valid?\n idx.indpred is null -- no partial index predicate\n order by\n idx.indrelid, idx.indexrelid\n )\nselect row_to_json(x) as object from namespace as x\nunion all\nselect row_to_json(x) as object from class as x\nunion all\nselect row_to_json(x) as object from attribute as x\nunion all\nselect row_to_json(x) as object from type as x\nunion all\nselect row_to_json(x) as object from \"constraint\" as x\nunion all\nselect row_to_json(x) as object from procedure as x\nunion all\nselect row_to_json(x) as object from extension as x\nunion all\nselect row_to_json(x) as object from indexes as x\n;\n`;\n}\n\nmodule.exports = {\n makeIntrospectionQuery,\n};\n"],"file":"introspectionQuery.js"}
1
+ {"version":3,"sources":["../../src/plugins/introspectionQuery.js"],"names":["makeIntrospectionQuery","serverVersionNum","options","pgLegacyFunctionsOnly","pgIgnoreRBAC","unionRBAC","module","exports"],"mappings":";;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,sBAAT,CACEC,gBADF,EAEEC,OAGC,GAAG,EALN,EAMU;AACR,QAAM;AAAEC,IAAAA,qBAAqB,GAAG,KAA1B;AAAiCC,IAAAA,YAAY,GAAG;AAAhD,MAAyDF,OAA/D;AACA,QAAMG,SAAS,GAAI;AACrB;AACA;AACA;AACA;AACA;AACA,GANE;AAOA,SAAQ;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,CAACD,YAAD,GAAgB,WAAhB,GAA8B,EAAG;AACrC;AACA;AACA;AACA,MAAM,CAACA,YAAD,GAAgBC,SAAhB,GAA4B,EAAG;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QACQJ,gBAAgB,IAAI,MAApB,GACI,mBADJ,GAEI,kDACL;AACP,QACQE,qBAAqB,GAChB;AACb;AACA;AACA;AACA;AACA,sDAN6B,GAOhB;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4GACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQF,gBAAgB,IAAI,MAApB,GAA6B,iBAA7B,GAAiD,IAAK;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QACQA,gBAAgB,IAAI,KAApB,GACK;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CATQ,GAUI,EACL;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAvZE;AAwZD;;AAEDK,MAAM,CAACC,OAAP,GAAiB;AACfP,EAAAA;AADe,CAAjB","sourcesContent":["// @flow\n/*\n * IMPORTANT: when editing this file, ensure all operators (e.g. `@>`) are\n * specified in the correct namespace (e.g. `operator(pg_catalog.@>)`). It looks\n * weird, but it prevents clashes with extensions or user code that may\n * overload operators, e.g. extension `intarray` overloads `@>`.\n *\n * NOTE: I'm not doing this with `=` because that way lies madness.\n */\nfunction makeIntrospectionQuery(\n serverVersionNum: number,\n options: {\n pgLegacyFunctionsOnly?: boolean,\n pgIgnoreRBAC?: boolean,\n } = {}\n): string {\n const { pgLegacyFunctionsOnly = false, pgIgnoreRBAC = true } = options;\n const unionRBAC = `\n union all\n select pg_roles.oid _oid, pg_roles.*\n from pg_roles, accessible_roles, pg_auth_members\n where pg_auth_members.roleid = pg_roles.oid\n and pg_auth_members.member = accessible_roles._oid \n `;\n return `\\\n-- @see https://www.postgresql.org/docs/9.5/static/catalogs.html\n-- @see https://github.com/graphile/graphile-engine/blob/master/packages/graphile-build-pg/src/plugins/introspectionQuery.js\n--\n-- ## Parameters\n-- - \\`$1\\`: An array of strings that represent the namespaces we are introspecting.\n-- - \\`$2\\`: set true to include functions/tables/etc that come from extensions\nwith\n ${!pgIgnoreRBAC ? \"recursive\" : \"\"} accessible_roles as (\n select oid _oid, pg_roles.*\n from pg_roles\n where rolname = current_user\n ${!pgIgnoreRBAC ? unionRBAC : \"\"}\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-namespace.html\n namespace as (\n select\n 'namespace' as \"kind\",\n nsp.oid as \"id\",\n nsp.nspname as \"name\",\n dsc.description as \"description\"\n from\n pg_catalog.pg_namespace as nsp\n left join pg_catalog.pg_description as dsc on dsc.objoid = nsp.oid and dsc.classoid = 'pg_catalog.pg_namespace'::regclass\n where\n nsp.nspname = any ($1)\n order by\n nsp.nspname\n ),\n -- Select all of the remote procedures we can use in this schema. This comes\n -- first so that we can select types and classes using the information we get\n -- from it.\n --\n -- @see https://www.postgresql.org/docs/9.6/static/catalog-pg-proc.html\n procedure as (\n select\n 'procedure' as \"kind\",\n pro.oid as \"id\",\n pro.proname as \"name\",\n dsc.description as \"description\",\n pro.pronamespace as \"namespaceId\",\n nsp.nspname as \"namespaceName\",\n pro.proisstrict as \"isStrict\",\n pro.proretset as \"returnsSet\",\n case\n when pro.provolatile = 'i' then true\n when pro.provolatile = 's' then true\n else false\n end as \"isStable\",\n pro.prorettype as \"returnTypeId\",\n coalesce(pro.proallargtypes, pro.proargtypes) as \"argTypeIds\",\n coalesce(pro.proargmodes, array[]::text[]) as \"argModes\",\n coalesce(pro.proargnames, array[]::text[]) as \"argNames\",\n pro.pronargs as \"inputArgsCount\",\n pro.pronargdefaults as \"argDefaultsNum\",\n pro.procost as \"cost\",\n exists(select 1 from accessible_roles where has_function_privilege(accessible_roles.oid, pro.oid, 'EXECUTE')) as \"aclExecutable\",\n (select lanname from pg_catalog.pg_language where pg_language.oid = pro.prolang) as \"language\"\n from\n pg_catalog.pg_proc as pro\n left join pg_catalog.pg_description as dsc on dsc.objoid = pro.oid and dsc.classoid = 'pg_catalog.pg_proc'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = pro.pronamespace\n where\n pro.pronamespace in (select \"id\" from namespace) and\n -- Currently we don’t support functions with variadic arguments. In the\n -- future we may, but for now let’s just ignore functions with variadic\n -- arguments.\n -- TODO: Variadic arguments.\n pro.provariadic = 0 and\n -- Filter our aggregate functions and window functions.\n ${\n serverVersionNum >= 110000\n ? \"pro.prokind = 'f'\"\n : \"pro.proisagg = false and pro.proiswindow = false\"\n } and\n ${\n pgLegacyFunctionsOnly\n ? `\\\n -- We want to make sure the argument mode for all of our arguments is\n -- \\`IN\\` which means \\`proargmodes\\` will be null.\n pro.proargmodes is null and\n -- Do not select procedures that return \\`RECORD\\` (oid 2249).\n pro.prorettype operator(pg_catalog.<>) 2249 and`\n : `\\\n -- We want to make sure the argument modes for all of our arguments are\n -- \\`IN\\`, \\`OUT\\`, \\`INOUT\\`, or \\`TABLE\\` (not \\`VARIADIC\\`).\n (pro.proargmodes is null or pro.proargmodes operator(pg_catalog.<@) array['i','o','b','t']::\"char\"[]) and\n -- Do not select procedures that return \\`RECORD\\` (oid 2249) unless they\n -- have \\`OUT\\`, \\`INOUT\\`, or \\`TABLE\\` arguments to define the return type.\n (pro.prorettype operator(pg_catalog.<>) 2249 or pro.proargmodes && array['o','b','t']::\"char\"[]) and\n -- Do not select procedures that have \\`RECORD\\` arguments.\n (pro.proallargtypes is null or not (pro.proallargtypes operator(pg_catalog.@>) array[2249::oid])) and`\n }\n -- Do not select procedures that create range types. These are utility\n -- functions that really don’t need to be exposed in an API.\n pro.proname not in (\n select typ.typname\n from pg_catalog.pg_type as typ\n where typ.typtype = 'r'\n and typ.typnamespace = pro.pronamespace\n ) and\n -- Do not expose trigger functions (type trigger has oid 2279)\n pro.prorettype operator(pg_catalog.<>) 2279 and\n -- We don't want functions that will clash with GraphQL (treat them as private)\n pro.proname not like E'\\\\\\\\_\\\\\\\\_%' and\n -- We also don’t want procedures that have been defined in our namespace\n -- twice. This leads to duplicate fields in the API which throws an\n -- error. In the future we may support this case. For now though, it is\n -- too complex.\n (\n select count(pro2.*)\n from pg_catalog.pg_proc as pro2\n where pro2.pronamespace = pro.pronamespace\n and pro2.proname = pro.proname\n ) = 1 and\n ($2 is true or not exists(\n select 1\n from pg_catalog.pg_depend\n where pg_depend.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n and pg_depend.deptype = 'e'\n and pg_depend.classid = 'pg_catalog.pg_proc'::pg_catalog.regclass\n and pg_depend.objid = pro.oid\n ))\n order by\n pro.pronamespace, pro.proname\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-class.html\n class as (\n select\n 'class' as \"kind\",\n rel.oid as \"id\",\n rel.relname as \"name\",\n rel.relkind as \"classKind\",\n dsc.description as \"description\",\n rel.relnamespace as \"namespaceId\",\n nsp.nspname as \"namespaceName\",\n rel.reltype as \"typeId\",\n -- Here we determine whether or not we can use this class in a\n -- \\`SELECT\\`’s \\`FROM\\` clause. In order to determine this we look at them\n -- \\`relkind\\` column, if it is \\`i\\` (index) or \\`c\\` (composite), we cannot\n -- select this class. Otherwise we can.\n rel.relkind not in ('i', 'c') as \"isSelectable\",\n -- Here we are determining whether we can insert/update/delete a class.\n -- This is helpful as it lets us detect non-updatable views and then\n -- exclude them from being inserted/updated/deleted into. For more info\n -- on how \\`pg_catalog.pg_relation_is_updatable\\` works:\n --\n -- - https://www.postgresql.org/message-id/CAEZATCV2_qN9P3zbvADwME_TkYf2gR_X2cLQR4R+pqkwxGxqJg@mail.gmail.com\n -- - https://github.com/postgres/postgres/blob/2410a2543e77983dab1f63f48b2adcd23dba994e/src/backend/utils/adt/misc.c#L684\n -- - https://github.com/postgres/postgres/blob/3aff33aa687e47d52f453892498b30ac98a296af/src/backend/rewrite/rewriteHandler.c#L2351\n (pg_catalog.pg_relation_is_updatable(rel.oid, true)::bit(8) operator(pg_catalog.&) B'00010000') = B'00010000' as \"isDeletable\",\n (pg_catalog.pg_relation_is_updatable(rel.oid, true)::bit(8) operator(pg_catalog.&) B'00001000') = B'00001000' as \"isInsertable\",\n (pg_catalog.pg_relation_is_updatable(rel.oid, true)::bit(8) operator(pg_catalog.&) B'00000100') = B'00000100' as \"isUpdatable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'SELECT')) as \"aclSelectable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'INSERT')) as \"aclInsertable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'UPDATE')) as \"aclUpdatable\",\n exists(select 1 from accessible_roles where has_table_privilege(accessible_roles.oid, rel.oid, 'DELETE')) as \"aclDeletable\"\n from\n pg_catalog.pg_class as rel\n left join pg_catalog.pg_description as dsc on dsc.objoid = rel.oid and dsc.objsubid = 0 and dsc.classoid = 'pg_catalog.pg_class'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = rel.relnamespace\n where\n rel.relpersistence in ('p') and\n -- We don't want classes that will clash with GraphQL (treat them as private)\n rel.relname not like E'\\\\\\\\_\\\\\\\\_%' and\n rel.relkind in ('r', 'v', 'm', 'c', 'f') and\n ($2 is true or not exists(\n select 1\n from pg_catalog.pg_depend\n where pg_depend.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n and pg_depend.deptype = 'e'\n and pg_depend.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n and pg_depend.objid = rel.oid\n ))\n order by\n rel.relnamespace, rel.relname\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-attribute.html\n attribute as (\n select\n 'attribute' as \"kind\",\n att.attrelid as \"classId\",\n att.attnum as \"num\",\n att.attname as \"name\",\n dsc.description as \"description\",\n att.atttypid as \"typeId\",\n nullif(att.atttypmod, -1) as \"typeModifier\",\n att.attnotnull as \"isNotNull\",\n att.atthasdef as \"hasDefault\",\n ${serverVersionNum >= 100000 ? \"att.attidentity\" : \"''\"} as \"identity\",\n exists(select 1 from accessible_roles where has_column_privilege(accessible_roles.oid, att.attrelid, att.attname, 'SELECT')) as \"aclSelectable\",\n exists(select 1 from accessible_roles where has_column_privilege(accessible_roles.oid, att.attrelid, att.attname, 'INSERT')) as \"aclInsertable\",\n exists(select 1 from accessible_roles where has_column_privilege(accessible_roles.oid, att.attrelid, att.attname, 'UPDATE')) as \"aclUpdatable\",\n -- https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=c62dd80cdf149e2792b13c13777a539f5abb0370\n att.attacl is not null and exists(select 1 from aclexplode(att.attacl) aclitem where aclitem.privilege_type = 'SELECT' and grantee in (select oid from accessible_roles)) as \"columnLevelSelectGrant\"\n from\n pg_catalog.pg_attribute as att\n left join pg_catalog.pg_description as dsc on dsc.objoid = att.attrelid and dsc.objsubid = att.attnum and dsc.classoid = 'pg_catalog.pg_class'::regclass\n where\n att.attrelid in (select \"id\" from class) and\n att.attnum > 0 and\n -- We don't want attributes that will clash with GraphQL (treat them as private)\n att.attname not like E'\\\\\\\\_\\\\\\\\_%' and\n not att.attisdropped\n order by\n att.attrelid, att.attnum\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-type.html\n type as (\n -- Use another \\`WITH\\` statement here, because our \\`WHERE\\` clause will need\n -- to use it.\n with type_all as (\n select\n 'type' as \"kind\",\n typ.oid as \"id\",\n typ.typname as \"name\",\n dsc.description as \"description\",\n typ.typnamespace as \"namespaceId\",\n -- We include the namespace name in types only because we select so\n -- many types that are outside of our core set of namespaces. Having\n -- the namespace name is super helpful when generating SQL, so\n -- conditionally having namespace names for types is a pain.\n nsp.nspname as \"namespaceName\",\n typ.typtype as \"type\",\n typ.typcategory as \"category\",\n typ.typnotnull as \"domainIsNotNull\",\n nullif(typ.typelem, 0) as \"arrayItemTypeId\",\n typ.typlen as \"typeLength\",\n (typ.typelem <> 0 and typ.typlen = -1) as \"isPgArray\",\n nullif(typ.typrelid, 0) as \"classId\",\n nullif(typ.typbasetype, 0) as \"domainBaseTypeId\",\n nullif(typ.typtypmod, -1) as \"domainTypeModifier\",\n typ.typdefaultbin is not null as \"domainHasDefault\",\n -- If this type is an enum type, let’s select all of its enum variants.\n --\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-enum.html\n case\n when typ.typtype = 'e' then array(\n select enm.enumlabel\n from pg_catalog.pg_enum as enm\n where enm.enumtypid = typ.oid\n order by enm.enumsortorder\n )\n else null\n end as \"enumVariants\",\n -- If this type is a range type, we want to select the sub type of the\n -- range.\n --\n -- @see https://www.postgresql.org/docs/9.6/static/catalog-pg-range.html\n case\n when typ.typtype = 'r' then (\n select rng.rngsubtype\n from pg_catalog.pg_range as rng\n where rng.rngtypid = typ.oid\n limit 1\n )\n else null\n end as \"rangeSubTypeId\"\n from\n pg_catalog.pg_type as typ\n left join pg_catalog.pg_description as dsc on dsc.objoid = typ.oid and dsc.classoid = 'pg_catalog.pg_type'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = typ.typnamespace\n )\n select\n *\n from\n type_all as typ\n where\n typ.id in (\n select \"typeId\" from class\n union all\n select \"typeId\" from attribute\n union all\n select \"returnTypeId\" from procedure\n union all\n select unnest(\"argTypeIds\") from procedure\n union all\n -- If this type is a base type for *any* domain type, we will include it\n -- in our selection. This may mean we fetch more types than we need, but\n -- the alternative is to do some funky SQL recursion which would be hard\n -- code to read. So we prefer code readability over selecting like 3 or\n -- 4 less type rows.\n --\n -- We also do this for range sub types and array item types.\n select \"domainBaseTypeId\" from type_all\n union all\n select \"rangeSubTypeId\" from type_all\n union all\n select \"arrayItemTypeId\" from type_all\n )\n order by\n \"namespaceId\", \"name\"\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-constraint.html\n \"constraint\" as (\n select distinct on (con.conrelid, con.conkey, con.confrelid, con.confkey)\n 'constraint' as \"kind\",\n con.oid as \"id\",\n con.conname as \"name\",\n con.contype as \"type\",\n con.conrelid as \"classId\",\n nullif(con.confrelid, 0) as \"foreignClassId\",\n dsc.description as \"description\",\n con.conkey as \"keyAttributeNums\",\n con.confkey as \"foreignKeyAttributeNums\"\n from\n pg_catalog.pg_constraint as con\n inner join class on (con.conrelid = class.id)\n left join pg_catalog.pg_description as dsc on dsc.objoid = con.oid and dsc.classoid = 'pg_catalog.pg_constraint'::regclass\n where\n -- Only get constraints for classes we have selected.\n con.conrelid in (select \"id\" from class where \"namespaceId\" in (select \"id\" from namespace)) and\n case\n -- If this is a foreign key constraint, we want to ensure that the\n -- foreign class is also in the list of classes we have already\n -- selected.\n when con.contype = 'f' then con.confrelid in (select \"id\" from class where \"namespaceId\" in (select \"id\" from namespace))\n -- Otherwise, this should be true.\n else true\n end and\n -- We only want foreign key, primary key, and unique constraints. We\n -- made add support for more constraints in the future.\n con.contype in ('f', 'p', 'u')\n order by\n con.conrelid, con.conkey, con.confrelid, con.confkey, con.conname\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-extension.html\n \"extension\" as (\n select\n 'extension' as \"kind\",\n ext.oid as \"id\",\n ext.extname as \"name\",\n ext.extnamespace as \"namespaceId\",\n nsp.nspname as \"namespaceName\",\n ext.extrelocatable as \"relocatable\",\n ext.extversion as \"version\",\n ext.extconfig as \"configurationClassIds\",\n dsc.description as \"description\"\n from\n pg_catalog.pg_extension as ext\n left join pg_catalog.pg_description as dsc on dsc.objoid = ext.oid and dsc.classoid = 'pg_catalog.pg_extension'::regclass\n left join pg_catalog.pg_namespace as nsp on nsp.oid = ext.extnamespace\n order by\n ext.extname, ext.oid\n ),\n -- @see https://www.postgresql.org/docs/9.5/static/catalog-pg-index.html\n \"indexes\" as (\n select\n 'index' as \"kind\",\n idx.indexrelid as \"id\",\n idx_more.relname as \"name\",\n nsp.nspname as \"namespaceName\",\n idx.indrelid as \"classId\",\n idx.indnatts as \"numberOfAttributes\",\n idx.indisunique as \"isUnique\",\n idx.indisprimary as \"isPrimary\",\n idx.indimmediate as \"isImmediate\", -- enforce uniqueness immediately on insert\n idx.indisreplident as \"isReplicaIdentity\",\n idx.indisvalid as \"isValid\", -- if false, don't use for queries\n idx.indpred is not null as \"isPartial\", -- if true, index is not on on rows.\n idx.indkey as \"attributeNums\",\n am.amname as \"indexType\",\n ${\n serverVersionNum >= 90600\n ? `\\\n (\n select array_agg(pg_index_column_has_property(idx.indexrelid,n::int2,'asc'))\n from unnest(idx.indkey) with ordinality as ord(key,n)\n ) as \"attributePropertiesAsc\",\n (\n select array_agg(pg_index_column_has_property(idx.indexrelid,n::int2,'nulls_first'))\n from unnest(idx.indkey) with ordinality as ord(key,n)\n ) as \"attributePropertiesNullsFirst\",`\n : \"\"\n }\n dsc.description as \"description\"\n from\n pg_catalog.pg_index as idx\n inner join pg_catalog.pg_class idx_more on (idx.indexrelid = idx_more.oid)\n inner join class on (idx.indrelid = class.id)\n inner join pg_catalog.pg_namespace as nsp on (nsp.oid = idx_more.relnamespace)\n inner join pg_catalog.pg_am as am on (am.oid = idx_more.relam)\n left join pg_catalog.pg_description as dsc on dsc.objoid = idx.indexrelid and dsc.objsubid = 0 and dsc.classoid = 'pg_catalog.pg_class'::regclass\n where\n idx.indislive is not false and\n idx.indisexclusion is not true and -- exclusion index\n idx.indcheckxmin is not true and -- always valid?\n idx.indpred is null -- no partial index predicate\n order by\n idx.indrelid, idx.indexrelid\n )\nselect row_to_json(x) as object from namespace as x\nunion all\nselect row_to_json(x) as object from class as x\nunion all\nselect row_to_json(x) as object from attribute as x\nunion all\nselect row_to_json(x) as object from type as x\nunion all\nselect row_to_json(x) as object from \"constraint\" as x\nunion all\nselect row_to_json(x) as object from procedure as x\nunion all\nselect row_to_json(x) as object from extension as x\nunion all\nselect row_to_json(x) as object from indexes as x\n;\n`;\n}\n\nmodule.exports = {\n makeIntrospectionQuery,\n};\n"],"file":"introspectionQuery.js"}
@@ -3,8 +3,8 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.procFieldDetails = procFieldDetails;
7
6
  exports.default = makeProcField;
7
+ exports.procFieldDetails = procFieldDetails;
8
8
 
9
9
  var _debugSql = _interopRequireDefault(require("./debugSql"));
10
10
 
@@ -56,8 +56,8 @@ function procFieldDetails(proc, build, options) {
56
56
  proc.argModes[idx] === "i" || // this arg is `in`
57
57
  proc.argModes[idx] === "b") // this arg is `inout`
58
58
  ) {
59
- prev.push(proc.argNames[idx] || "");
60
- }
59
+ prev.push(proc.argNames[idx] || "");
60
+ }
61
61
 
62
62
  return prev;
63
63
  }, []);
@@ -67,8 +67,8 @@ function procFieldDetails(proc, build, options) {
67
67
  proc.argModes[idx] === "i" || // this arg is `in`
68
68
  proc.argModes[idx] === "b") // this arg is `inout`
69
69
  ) {
70
- prev.push(introspectionResultsByKind.typeById[typeId]);
71
- }
70
+ prev.push(introspectionResultsByKind.typeById[typeId]);
71
+ }
72
72
 
73
73
  return prev;
74
74
  }, []);
@@ -252,12 +252,8 @@ export default function makeProcField(
252
252
  pgPrepareAndRun,
253
253
  } = build;
254
254
 
255
- const {
256
- inputs,
257
- makeSqlFunctionCall,
258
- outputArgNames,
259
- outputArgTypes,
260
- } = procFieldDetails(proc, build, options);
255
+ const { inputs, makeSqlFunctionCall, outputArgNames, outputArgTypes } =
256
+ procFieldDetails(proc, build, options);
261
257
  let args = inputs;
262
258
 
263
259
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/makeProcField.js"],"names":["nullableIf","GraphQLNonNull","condition","Type","firstValue","obj","firstKey","k","procFieldDetails","proc","build","options","computed","isMutation","pgIntrospectionResultsByKind","introspectionResultsByKind","pgGetGqlInputTypeByTypeIdAndModifier","pgSql","sql","gql2pg","pgStrictFunctions","strictFunctions","graphql","inflection","describePgEntity","sqlCommentByAddingTags","Error","sliceAmount","argNames","argTypeIds","reduce","prev","_","idx","argModes","length","push","argTypes","typeId","typeById","argModesWithOutput","outputArgNames","includes","outputArgTypes","requiredArgCount","Math","max","argDefaultsNum","variantFromName","name","match","variantFromTags","tags","variant","parseInt","notNullArgCount","isStrict","argGqlTypes","map","type","id","hint","class","chalk","bold","green","inputs","memo","argName","argIndex","gqlArgName","argument","makeSqlFunctionCall","rawArgs","implicitArgs","unnest","args","input","sqlArgValues","haveNames","value","sqlValue","sqlArgName","identifier","unshift","fragment","functionCall","namespace","join","makeProcField","fieldName","fieldWithHooks","isRootQuery","forceList","aggregateWrapper","description","overrideDescription","pgTypeAndModifierModifier","pgGetGqlTypeByTypeIdAndModifier","getTypeByName","parseResolveInfo","getSafeAliasFromResolveInfo","getSafeAliasFromAlias","pg2gql","newWithHooks","pgTweakFragmentForTypeAndModifier","GraphQLList","GraphQLString","GraphQLObjectType","GraphQLInputObjectType","getNamedType","isCompositeType","pgQueryFromResolveData","queryFromResolveData","pgAddStartEndCursor","addStartEndCursor","pgViaTemporaryTable","viaTemporaryTable","pgField","subscriptions","pgForbidSetofFunctionsToReturnNull","pgPrepareAndRun","baseReturnType","returnTypeId","rawReturnType","returnType","isPgArray","arrayItemType","returnTypeTable","classById","classId","fieldScope","payloadTypeScope","pgFieldIntrospection","pgIntrospection","returnFirstValueAsValue","TableType","isTableLike","isRecordLike","returnsSet","innerType","isPgFieldSimpleCollection","ConnectionType","connection","isPgFieldConnection","pgFieldIntrospectionTable","pgIntrospectionTable","RecordType","recordFunctionReturnType","recordFunctionConnection","connectionTypeName","scalarFunctionConnection","addDataGenerator","getDataFromParsedResolveInfoFragment","addArgDataGenerator","addPgCursorPrefix","pgCursorPrefix","literal","makeQuery","parsedResolveInfoFragment","ReturnType","sqlMutationQuery","functionAlias","parentQueryBuilder","resolveContext","resolveInfo","resolveData","isConnection","query","useAsterisk","language","withPagination","withPaginationAsFields","asJson","asJsonAggregate","addNullCase","innerQueryBuilder","select","primaryKeyConstraint","selectIdentifiers","context","rootValue","pgQuery","queryBuilder","parentTableAlias","getTableAlias","Symbol","sqlFunctionCall","alias","PayloadType","resultFieldName","functionMutationResultFieldName","isNotVoid","String","functionPayloadType","wrapDescription","functionMutationName","fields","Object","assign","clientMutationId","resolve","data","pgType","__origin","isMutationPayload","InputType","functionInputType","isMutationInput","scalarAwarePg2gql","v","notNull","_args","liveRecord","safeAlias","makeRecordLive","record","__identifiers","_record","records","pgClient","queryResultRows","intermediateIdentifier","isVoid","isPgRecord","isPgClass","namespaceName","e","text","values","compile","debugSql","enabled","queryResult","rows","row","result","fv"],"mappings":";;;;;;;;AAOA;;AACA;;;;AAPA,MAAMA,UAAU,GAAG,CAACC,cAAD,EAAiBC,SAAjB,EAA4BC,IAA5B,KACjBD,SAAS,GAAGC,IAAH,GAAU,IAAIF,cAAJ,CAAmBE,IAAnB,CADrB;;AAyBA,MAAMC,UAAU,GAAGC,GAAG,IAAI;AACxB,MAAIC,QAAJ;;AACA,OAAK,MAAMC,CAAX,IAAgBF,GAAhB,EAAqB;AACnB,QAAIE,CAAC,CAAC,CAAD,CAAD,KAAS,GAAT,IAAgBA,CAAC,CAAC,CAAD,CAAD,KAAS,GAA7B,EAAkC;AAChCD,MAAAA,QAAQ,GAAGC,CAAX;AACD;AACF;;AACD,SAAOF,GAAG,CAACC,QAAD,CAAV;AACD,CARD;;AAUO,SAASE,gBAAT,CACLC,IADK,EAELC,KAFK,EAGLC,OAHK,EAOL;AACA,QAAM;AAAEC,IAAAA,QAAQ,GAAG,KAAb;AAAoBC,IAAAA,UAAU,GAAG;AAAjC,MAA2CF,OAAjD;AACA,QAAM;AACJG,IAAAA,4BAA4B,EAAEC,0BAD1B;AAEJC,IAAAA,oCAFI;AAGJC,IAAAA,KAAK,EAAEC,GAHH;AAIJC,IAAAA,MAJI;AAKJC,IAAAA,iBAAiB,EAAEC,eALf;AAMJC,IAAAA,OAAO,EAAE;AAAErB,MAAAA;AAAF,KANL;AAOJsB,IAAAA,UAPI;AAQJC,IAAAA,gBARI;AASJC,IAAAA;AATI,MAUFf,KAVJ;;AAYA,MAAIE,QAAQ,IAAIC,UAAhB,EAA4B;AAC1B,UAAM,IAAIa,KAAJ,CAAU,uCAAV,CAAN;AACD;;AAED,QAAMC,WAAW,GAAGf,QAAQ,GAAG,CAAH,GAAO,CAAnC;AACA,QAAMgB,QAAQ,GAAGnB,IAAI,CAACoB,UAAL,CAAg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G,IAAI,CAAChL,GAAL,CAASiL,GAAG,IAAI;AACrBpB,gBAAAA,cAAc,CAACoB,GAAD,CAAd;AACA,uBAAOpI,MAAM,CAACoI,GAAD,EAAM9G,UAAN,CAAb;AACD,eAHM,CAAP;AAID,aANM,MAMA;AACL;AACA0F,cAAAA,cAAc,CAACoB,GAAD,CAAd;AACA,qBAAOpI,MAAM,CAACoI,GAAD,EAAM9G,UAAN,CAAb;AACD;AACF;AACF,SAzDc,GAAf;;AA0DA,YAAIhH,UAAJ,EAAgB;AACd,iBAAO;AACL2L,YAAAA,gBAAgB,EAAE5H,IAAI,CAACC,KAAL,CAAW2H,gBADxB;AAELE,YAAAA,IAAI,EAAEkC;AAFD,WAAP;AAID,SALD,MAKO;AACL,iBAAOA,MAAP;AACD;AACF;AAhOA,KAAP;AAkOD,GAzdkB,EA0dnBzG,UA1dmB,CAArB;AA4dD","sourcesContent":["// @flow\nconst nullableIf = (GraphQLNonNull, condition, Type) =>\n condition ? Type : new GraphQLNonNull(Type);\n\nimport type { Build, FieldWithHooksFunction } from \"graphile-build\";\nimport type { PgProc, PgType } from \"./PgIntrospectionPlugin\";\nimport type { SQL } from \"pg-sql2\";\nimport debugSql from \"./debugSql\";\nimport chalk from \"chalk\";\n\ntype ProcFieldOptions = {\n fieldWithHooks: FieldWithHooksFunction,\n computed?: boolean,\n isMutation?: boolean,\n isRootQuery?: boolean,\n forceList?: boolean,\n aggregateWrapper?: null | ((sql: SQL) => SQL),\n description?: string,\n pgTypeAndModifierModifier?:\n | null\n | ((\n pgType: PgType,\n pgTypeModifier: null | string | number\n ) => [PgType, null | string | number]),\n};\n\nconst firstValue = obj => {\n let firstKey;\n for (const k in obj) {\n if (k[0] !== \"_\" && k[1] !== \"_\") {\n firstKey = k;\n }\n }\n return obj[firstKey];\n};\n\nexport function procFieldDetails(\n proc: PgProc,\n build: {| ...Build |},\n options: {\n computed?: boolean,\n isMutation?: boolean,\n }\n) {\n const { computed = false, isMutation = false } = options;\n const {\n pgIntrospectionResultsByKind: introspectionResultsByKind,\n pgGetGqlInputTypeByTypeIdAndModifier,\n pgSql: sql,\n gql2pg,\n pgStrictFunctions: strictFunctions,\n graphql: { GraphQLNonNull },\n inflection,\n describePgEntity,\n sqlCommentByAddingTags,\n } = build;\n\n if (computed && isMutation) {\n throw new Error(\"Mutation procedure cannot be computed\");\n }\n\n const sliceAmount = computed ? 1 : 0;\n const argNames = proc.argTypeIds.reduce((prev, _, idx) => {\n if (\n idx >= sliceAmount && // Was a .slice() call\n (proc.argModes.length === 0 || // all args are `in`\n proc.argModes[idx] === \"i\" || // this arg is `in`\n proc.argModes[idx] === \"b\") // this arg is `inout`\n ) {\n prev.push(proc.argNames[idx] || \"\");\n }\n return prev;\n }, []);\n const argTypes = proc.argTypeIds.reduce((prev, typeId, idx) => {\n if (\n idx >= sliceAmount && // Was a .slice() call\n (proc.argModes.length === 0 || // all args are `in`\n proc.argModes[idx] === \"i\" || // this arg is `in`\n proc.argModes[idx] === \"b\") // this arg is `inout`\n ) {\n prev.push(introspectionResultsByKind.typeById[typeId]);\n }\n return prev;\n }, []);\n const argModesWithOutput = [\n \"o\", // OUT,\n \"b\", // INOUT\n \"t\", // TABLE\n ];\n const outputArgNames = proc.argTypeIds.reduce((prev, _, idx) => {\n if (argModesWithOutput.includes(proc.argModes[idx])) {\n prev.push(proc.argNames[idx] || \"\");\n }\n return prev;\n }, []);\n const outputArgTypes = proc.argTypeIds.reduce((prev, typeId, idx) => {\n if (argModesWithOutput.includes(proc.argModes[idx])) {\n prev.push(introspectionResultsByKind.typeById[typeId]);\n }\n return prev;\n }, []);\n const requiredArgCount = Math.max(0, argNames.length - proc.argDefaultsNum);\n const variantFromName = name => {\n if (name.match(/(_p|P)atch$/)) {\n return \"patch\";\n }\n return null;\n };\n const variantFromTags = (tags, idx) => {\n const variant = tags[`arg${idx}variant`];\n if (variant && variant.match && variant.match(/^[0-9]+$/)) {\n return parseInt(variant, 10);\n }\n return variant;\n };\n const notNullArgCount =\n proc.isStrict || strictFunctions ? requiredArgCount : 0;\n const argGqlTypes = argTypes.map((type, idx) => {\n // TODO: PG10 doesn't support the equivalent of pg_attribute.atttypemod on function return values, but maybe a later version might\n const variant =\n variantFromTags(proc.tags, idx) || variantFromName(argNames[idx]);\n const Type = pgGetGqlInputTypeByTypeIdAndModifier(type.id, variant);\n if (!Type) {\n const hint = type.class\n ? `; this might be because no INSERT column privileges are granted on ${describePgEntity(\n type.class\n )}. You can use 'Smart Comments' to tell PostGraphile to instead use the \"${chalk.bold.green(\n \"base\"\n )}\" input type which includes all columns:\\n\\n ${sqlCommentByAddingTags(\n proc,\n {\n [`arg${idx}variant`]: \"base\",\n }\n )}\\n`\n : \"\";\n throw new Error(\n `Could not determine type for argument ${idx} ('${\n argNames[idx]\n }') of function ${describePgEntity(proc)}${hint}`\n );\n }\n if (idx >= notNullArgCount) {\n return Type;\n } else {\n return new GraphQLNonNull(Type);\n }\n });\n // This wants to be compatible with both being field arguments and being\n // input object fields (e.g. for the aggregates plugin).\n const inputs = argNames.reduce((memo, argName, argIndex) => {\n const gqlArgName = inflection.argument(argName, argIndex);\n memo[gqlArgName] = {\n type: argGqlTypes[argIndex],\n };\n return memo;\n }, {});\n\n function makeSqlFunctionCall(\n rawArgs = {},\n { implicitArgs = [], unnest = false } = {}\n ): SQL {\n const args = isMutation ? rawArgs.input : rawArgs;\n const sqlArgValues = [];\n let haveNames = true;\n for (let argIndex = argNames.length - 1; argIndex >= 0; argIndex--) {\n const argName = argNames[argIndex];\n const gqlArgName = inflection.argument(argName, argIndex);\n const value = args[gqlArgName];\n const variant =\n variantFromTags(proc.tags, argIndex) ||\n variantFromName(argNames[argIndex]);\n\n const sqlValue = gql2pg(value, argTypes[argIndex], variant);\n\n if (argIndex + 1 > requiredArgCount && haveNames && value == null) {\n // No need to pass argument to function\n continue;\n } else if (argIndex + 1 > requiredArgCount && haveNames) {\n const sqlArgName = argName ? sql.identifier(argName) : null;\n if (sqlArgName) {\n sqlArgValues.unshift(sql.fragment`${sqlArgName} := ${sqlValue}`);\n } else {\n haveNames = false;\n sqlArgValues.unshift(sqlValue);\n }\n } else {\n sqlArgValues.unshift(sqlValue);\n }\n }\n const functionCall = sql.fragment`${sql.identifier(\n proc.namespace.name,\n proc.name\n )}(${sql.join([...implicitArgs, ...sqlArgValues], \", \")})`;\n return unnest ? sql.fragment`unnest(${functionCall})` : functionCall;\n }\n\n return {\n inputs,\n makeSqlFunctionCall,\n outputArgNames,\n outputArgTypes,\n };\n}\n\nexport default function makeProcField(\n fieldName: string,\n proc: PgProc,\n build: {| ...Build |},\n options: ProcFieldOptions\n) {\n const {\n fieldWithHooks,\n computed = false,\n isMutation = false,\n isRootQuery = false,\n forceList = false,\n aggregateWrapper = null,\n description: overrideDescription = null,\n pgTypeAndModifierModifier = null,\n } = options;\n const {\n pgIntrospectionResultsByKind: introspectionResultsByKind,\n pgGetGqlTypeByTypeIdAndModifier,\n getTypeByName,\n pgSql: sql,\n parseResolveInfo,\n getSafeAliasFromResolveInfo,\n getSafeAliasFromAlias,\n pg2gql,\n newWithHooks,\n pgTweakFragmentForTypeAndModifier,\n graphql: {\n GraphQLNonNull,\n GraphQLList,\n GraphQLString,\n GraphQLObjectType,\n GraphQLInputObjectType,\n getNamedType,\n isCompositeType,\n },\n inflection,\n pgQueryFromResolveData: queryFromResolveData,\n pgAddStartEndCursor: addStartEndCursor,\n pgViaTemporaryTable: viaTemporaryTable,\n describePgEntity,\n sqlCommentByAddingTags,\n pgField,\n options: {\n subscriptions = false,\n pgForbidSetofFunctionsToReturnNull = false,\n },\n pgPrepareAndRun,\n } = build;\n\n const {\n inputs,\n makeSqlFunctionCall,\n outputArgNames,\n outputArgTypes,\n } = procFieldDetails(proc, build, options);\n let args = inputs;\n\n /**\n * This is the return type the function claims to have; we\n * should not use it anywhere but these next few lines.\n */\n const baseReturnType = introspectionResultsByKind.typeById[proc.returnTypeId];\n\n /**\n * This is the return type we treat it as having, e.g. in\n * case it was modified by wrapping it in an aggregate or\n * similar.\n */\n const rawReturnType = pgTypeAndModifierModifier\n ? pgTypeAndModifierModifier(baseReturnType, null)[0]\n : baseReturnType;\n\n /**\n * This is the type without the array wrapper.\n */\n const returnType = rawReturnType.isPgArray\n ? rawReturnType.arrayItemType\n : rawReturnType;\n const returnTypeTable =\n introspectionResultsByKind.classById[returnType.classId];\n if (!returnType) {\n throw new Error(\n `Could not determine return type for function '${proc.name}'`\n );\n }\n let type;\n const fieldScope = {};\n const payloadTypeScope = {};\n fieldScope.pgFieldIntrospection = proc;\n payloadTypeScope.pgIntrospection = proc;\n let returnFirstValueAsValue = false;\n const TableType =\n returnTypeTable &&\n pgGetGqlTypeByTypeIdAndModifier(returnTypeTable.type.id, null);\n\n const isTableLike: boolean =\n (TableType && isCompositeType(TableType)) || false;\n const isRecordLike = returnType.id === \"2249\";\n if (isTableLike) {\n if (proc.returnsSet) {\n if (isMutation) {\n const innerType = pgForbidSetofFunctionsToReturnNull\n ? new GraphQLNonNull(TableType)\n : TableType;\n type = new GraphQLList(innerType);\n } else if (forceList) {\n const innerType = pgForbidSetofFunctionsToReturnNull\n ? new GraphQLNonNull(TableType)\n : TableType;\n type = new GraphQLList(innerType);\n fieldScope.isPgFieldSimpleCollection = true;\n } else {\n const ConnectionType = getTypeByName(\n inflection.connection(TableType.name)\n );\n if (!ConnectionType) {\n throw new Error(\n `Do not have a connection type '${inflection.connection(\n TableType.name\n )}' for '${TableType.name}' so cannot create procedure field`\n );\n }\n type = ConnectionType;\n fieldScope.isPgFieldConnection = true;\n }\n fieldScope.pgFieldIntrospectionTable = returnTypeTable;\n payloadTypeScope.pgIntrospectionTable = returnTypeTable;\n } else {\n type = TableType;\n if (rawReturnType.isPgArray) {\n // Not implementing pgForbidSetofFunctionsToReturnNull here because it's not a set\n type = new GraphQLList(type);\n }\n fieldScope.pgFieldIntrospectionTable = returnTypeTable;\n payloadTypeScope.pgIntrospectionTable = returnTypeTable;\n }\n } else if (isRecordLike) {\n const RecordType = getTypeByName(inflection.recordFunctionReturnType(proc));\n if (!RecordType) {\n throw new Error(\n `Do not have a record type '${inflection.recordFunctionReturnType(\n proc\n )}' for '${proc.name}' so cannot create procedure field`\n );\n }\n if (proc.returnsSet) {\n if (isMutation) {\n type = new GraphQLList(RecordType);\n } else if (forceList) {\n type = new GraphQLList(RecordType);\n fieldScope.isPgFieldSimpleCollection = true;\n } else {\n const ConnectionType = getTypeByName(\n inflection.recordFunctionConnection(proc)\n );\n if (!ConnectionType) {\n throw new Error(\n `Do not have a connection type '${inflection.recordFunctionConnection(\n proc\n )}' for '${RecordType.name}' so cannot create procedure field`\n );\n }\n type = ConnectionType;\n fieldScope.isPgFieldConnection = true;\n }\n } else {\n type = RecordType;\n if (rawReturnType.isPgArray) {\n type = new GraphQLList(type);\n }\n }\n } else {\n // TODO: PG10 doesn't support the equivalent of pg_attribute.atttypemod on function return values, but maybe a later version might\n const Type =\n pgGetGqlTypeByTypeIdAndModifier(returnType.id, null) || GraphQLString;\n\n if (proc.returnsSet) {\n const connectionTypeName = inflection.scalarFunctionConnection(proc);\n const ConnectionType = getTypeByName(connectionTypeName);\n if (isMutation) {\n // Cannot return a connection because it would have to run the mutation again\n type = new GraphQLList(Type);\n returnFirstValueAsValue = true;\n } else if (forceList || !ConnectionType) {\n type = new GraphQLList(Type);\n returnFirstValueAsValue = true;\n fieldScope.isPgFieldSimpleCollection = true;\n } else {\n type = ConnectionType;\n fieldScope.isPgFieldConnection = true;\n // We don't return the first value as the value here because it gets\n // sent down into PgScalarFunctionConnectionPlugin so the relevant\n // EdgeType can return cursor / node; i.e. we might want to add an\n // `__cursor` field so we can't just use a scalar.\n }\n } else {\n returnFirstValueAsValue = true;\n type = Type;\n if (rawReturnType.isPgArray) {\n type = new GraphQLList(type);\n }\n }\n }\n return fieldWithHooks(\n fieldName,\n ({\n addDataGenerator,\n getDataFromParsedResolveInfoFragment,\n addArgDataGenerator,\n }) => {\n if (\n proc.returnsSet &&\n !isTableLike &&\n !returnFirstValueAsValue &&\n !isMutation\n ) {\n // Natural ordering\n addArgDataGenerator(function addPgCursorPrefix() {\n return {\n pgCursorPrefix: sql.literal(\"natural\"),\n };\n });\n }\n function makeQuery(\n parsedResolveInfoFragment,\n ReturnType,\n sqlMutationQuery,\n functionAlias,\n parentQueryBuilder,\n resolveContext,\n resolveInfo\n ) {\n const resolveData = getDataFromParsedResolveInfoFragment(\n parsedResolveInfoFragment,\n ReturnType\n );\n const isConnection = !forceList && !isMutation && proc.returnsSet;\n const query = queryFromResolveData(\n sqlMutationQuery,\n functionAlias,\n resolveData,\n {\n useAsterisk:\n !isMutation &&\n (isTableLike || isRecordLike) &&\n (forceList || proc.returnsSet || rawReturnType.isPgArray) && // only bother with lists\n proc.language !== \"sql\", // sql functions can be inlined, so GRANTs still apply\n withPagination: isConnection,\n withPaginationAsFields: isConnection && !computed,\n asJson:\n computed &&\n (forceList || (!proc.returnsSet && !returnFirstValueAsValue)),\n asJsonAggregate:\n computed &&\n (forceList || (!proc.returnsSet && rawReturnType.isPgArray)),\n addNullCase:\n !proc.returnsSet &&\n !rawReturnType.isPgArray &&\n (isTableLike || isRecordLike),\n },\n innerQueryBuilder => {\n innerQueryBuilder.parentQueryBuilder = parentQueryBuilder;\n if (!isTableLike) {\n if (returnTypeTable) {\n innerQueryBuilder.select(\n pgTweakFragmentForTypeAndModifier(\n sql.fragment`${functionAlias}`,\n returnTypeTable.type,\n null,\n resolveData\n ),\n \"value\"\n );\n } else {\n innerQueryBuilder.select(\n pgTweakFragmentForTypeAndModifier(\n sql.fragment`${functionAlias}`,\n returnType,\n null, // We can't determine a type modifier for functions\n resolveData\n ),\n \"value\"\n );\n }\n } else if (\n subscriptions &&\n returnTypeTable &&\n !isConnection &&\n returnTypeTable.primaryKeyConstraint\n ) {\n innerQueryBuilder.selectIdentifiers(returnTypeTable);\n }\n },\n parentQueryBuilder ? parentQueryBuilder.context : resolveContext,\n parentQueryBuilder\n ? parentQueryBuilder.rootValue\n : resolveInfo && resolveInfo.rootValue\n );\n return query;\n }\n if (computed) {\n addDataGenerator((parsedResolveInfoFragment, ReturnType) => {\n return {\n pgQuery: queryBuilder => {\n queryBuilder.select(() => {\n const parentTableAlias = queryBuilder.getTableAlias();\n const functionAlias = sql.identifier(Symbol());\n const sqlFunctionCall = makeSqlFunctionCall(\n parsedResolveInfoFragment.args,\n {\n implicitArgs: [parentTableAlias],\n unnest: rawReturnType.isPgArray,\n }\n );\n if (aggregateWrapper) {\n return aggregateWrapper(sqlFunctionCall);\n } else {\n const query = makeQuery(\n parsedResolveInfoFragment,\n ReturnType,\n sqlFunctionCall,\n functionAlias,\n queryBuilder\n );\n return sql.fragment`(${query})`;\n }\n }, getSafeAliasFromAlias(parsedResolveInfoFragment.alias));\n },\n };\n });\n }\n\n let ReturnType = type;\n let PayloadType;\n if (isMutation) {\n const resultFieldName = inflection.functionMutationResultFieldName(\n proc,\n getNamedType(type),\n proc.returnsSet || rawReturnType.isPgArray,\n outputArgNames\n );\n const isNotVoid = String(returnType.id) !== \"2278\";\n // If set then plural name\n PayloadType = newWithHooks(\n GraphQLObjectType,\n {\n name: inflection.functionPayloadType(proc),\n description: build.wrapDescription(\n `The output of our \\`${inflection.functionMutationName(\n proc\n )}\\` mutation.`,\n \"type\"\n ),\n fields: ({ fieldWithHooks }) => {\n return Object.assign(\n {},\n {\n clientMutationId: {\n type: GraphQLString,\n },\n },\n isNotVoid\n ? {\n [resultFieldName]: pgField(\n build,\n fieldWithHooks,\n resultFieldName,\n {\n type: type,\n ...(returnFirstValueAsValue\n ? {\n resolve(data) {\n return data.data;\n },\n }\n : null),\n },\n {},\n false,\n {\n pgType: returnType,\n }\n ),\n // Result\n }\n : null\n );\n },\n },\n {\n __origin: `Adding mutation function payload type for ${describePgEntity(\n proc\n )}. You can rename the function's GraphQL field (and its dependent types) via a 'Smart Comment':\\n\\n ${sqlCommentByAddingTags(\n proc,\n {\n name: \"newNameHere\",\n }\n )}`,\n isMutationPayload: true,\n ...payloadTypeScope,\n }\n );\n ReturnType = PayloadType;\n const InputType = newWithHooks(\n GraphQLInputObjectType,\n {\n name: inflection.functionInputType(proc),\n description: build.wrapDescription(\n `All input for the \\`${inflection.functionMutationName(\n proc\n )}\\` mutation.`,\n \"type\"\n ),\n fields: {\n clientMutationId: {\n type: GraphQLString,\n },\n ...args,\n },\n },\n {\n __origin: `Adding mutation function input type for ${describePgEntity(\n proc\n )}. You can rename the function's GraphQL field (and its dependent types) via a 'Smart Comment':\\n\\n ${sqlCommentByAddingTags(\n proc,\n {\n name: \"newNameHere\",\n }\n )}`,\n isMutationInput: true,\n }\n );\n args = {\n input: {\n type: new GraphQLNonNull(InputType),\n },\n };\n }\n // If this is a table we can process it directly; but if it's a scalar\n // setof function we must dereference '.value' from it, because this\n // makes space for '__cursor' to exist alongside it (whereas on a table\n // the '__cursor' can just be on the table object itself)\n const scalarAwarePg2gql = v =>\n isTableLike\n ? pg2gql(v, returnType)\n : {\n ...v,\n value: pg2gql(v.value, returnType),\n };\n\n return {\n description: overrideDescription\n ? overrideDescription\n : proc.description\n ? proc.description\n : isMutation\n ? null\n : isTableLike && proc.returnsSet\n ? build.wrapDescription(\n `Reads and enables pagination through a set of \\`${TableType.name}\\`.`,\n \"field\"\n )\n : null,\n type: nullableIf(\n GraphQLNonNull,\n !proc.tags.notNull &&\n (!fieldScope.isPgFieldConnection || isMutation || isRootQuery),\n ReturnType\n ),\n args: args,\n resolve: computed\n ? (data, _args, resolveContext, resolveInfo) => {\n const liveRecord =\n resolveInfo.rootValue && resolveInfo.rootValue.liveRecord;\n const safeAlias = getSafeAliasFromResolveInfo(resolveInfo);\n const value = data[safeAlias];\n if (returnFirstValueAsValue) {\n // Is not table like; is not record like.\n if (proc.returnsSet && !forceList) {\n // EITHER `isMutation` is true, or `ConnectionType` does not\n // exist - either way, we're not returning a connection.\n return value.data.map(v => pg2gql(firstValue(v), returnType));\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n return value.map(v => pg2gql(firstValue(v), returnType));\n } else {\n return pg2gql(value, returnType);\n }\n } else {\n const makeRecordLive =\n subscriptions && isTableLike && returnTypeTable && liveRecord\n ? record => {\n if (record) {\n liveRecord(\n \"pg\",\n returnTypeTable,\n record.__identifiers\n );\n }\n }\n : _record => {};\n if (proc.returnsSet && !isMutation && !forceList) {\n // Connection - do not make live (the connection will handle this)\n return addStartEndCursor({\n ...value,\n data: value.data ? value.data.map(scalarAwarePg2gql) : null,\n });\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n // List\n const records = value.map(v => {\n makeRecordLive(v);\n return pg2gql(v, returnType);\n });\n return records;\n } else {\n // Object\n if (value) {\n makeRecordLive(value);\n }\n return pg2gql(value, returnType);\n }\n }\n }\n : async (data, args, resolveContext, resolveInfo) => {\n const { pgClient } = resolveContext;\n const liveRecord =\n resolveInfo.rootValue && resolveInfo.rootValue.liveRecord;\n const parsedResolveInfoFragment = parseResolveInfo(resolveInfo);\n parsedResolveInfoFragment.args = args; // Allow overriding via makeWrapResolversPlugin\n const functionAlias = sql.identifier(Symbol());\n const sqlFunctionCall = makeSqlFunctionCall(\n parsedResolveInfoFragment.args,\n {\n unnest: rawReturnType.isPgArray,\n }\n );\n\n let queryResultRows;\n if (isMutation) {\n const query = makeQuery(\n parsedResolveInfoFragment,\n resolveInfo.returnType,\n functionAlias,\n functionAlias,\n null,\n resolveContext,\n resolveInfo\n );\n const intermediateIdentifier = sql.identifier(Symbol());\n const isVoid = returnType.id === \"2278\";\n const isPgRecord = returnType.id === \"2249\";\n const isPgClass =\n !isPgRecord &&\n (!returnFirstValueAsValue || returnTypeTable || false);\n try {\n await pgClient.query(\"SAVEPOINT graphql_mutation\");\n queryResultRows = await viaTemporaryTable(\n pgClient,\n isVoid\n ? null\n : sql.identifier(\n returnType.namespaceName,\n returnType.name\n ),\n sql.query`select ${\n isPgClass\n ? sql.query`${intermediateIdentifier}.*`\n : isPgRecord\n ? sql.query`${intermediateIdentifier}.*`\n : sql.query`${intermediateIdentifier} as ${functionAlias}`\n } from ${sqlFunctionCall} ${intermediateIdentifier}`,\n functionAlias,\n query,\n isPgClass,\n isPgRecord\n ? {\n outputArgTypes,\n outputArgNames,\n }\n : null\n );\n await pgClient.query(\"RELEASE SAVEPOINT graphql_mutation\");\n } catch (e) {\n await pgClient.query(\n \"ROLLBACK TO SAVEPOINT graphql_mutation\"\n );\n throw e;\n }\n } else {\n const query = makeQuery(\n parsedResolveInfoFragment,\n resolveInfo.returnType,\n sqlFunctionCall,\n functionAlias,\n null,\n resolveContext,\n resolveInfo\n );\n const { text, values } = sql.compile(query);\n if (debugSql.enabled) debugSql(text);\n const queryResult = await pgPrepareAndRun(\n pgClient,\n text,\n values\n );\n queryResultRows = queryResult.rows;\n }\n const rows = queryResultRows;\n const [row] = rows;\n const result = (() => {\n const makeRecordLive =\n subscriptions && isTableLike && returnTypeTable && liveRecord\n ? record => {\n if (record) {\n liveRecord(\n \"pg\",\n returnTypeTable,\n record.__identifiers\n );\n }\n }\n : _record => {};\n if (returnFirstValueAsValue) {\n // `returnFirstValueAsValue` implies either `isMutation` is\n // true, or `ConnectionType` does not exist - either way,\n // we're not returning a connection.\n if (proc.returnsSet && !isMutation && !forceList) {\n return row.data.map(v => {\n const fv = firstValue(v);\n makeRecordLive(fv);\n return pg2gql(fv, returnType);\n });\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n return rows.map(v => {\n const fv = firstValue(v);\n makeRecordLive(fv);\n return pg2gql(fv, returnType);\n });\n } else {\n const fv = firstValue(row);\n makeRecordLive(fv);\n const record = pg2gql(fv, returnType);\n return record;\n }\n } else {\n if (proc.returnsSet && !isMutation && !forceList) {\n // Connection\n const data = row.data\n ? row.data.map(scalarAwarePg2gql)\n : null;\n return addStartEndCursor({\n ...row,\n data,\n });\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n // List\n return rows.map(row => {\n makeRecordLive(row);\n return pg2gql(row, returnType);\n });\n } else {\n // Object\n makeRecordLive(row);\n return pg2gql(row, returnType);\n }\n }\n })();\n if (isMutation) {\n return {\n clientMutationId: args.input.clientMutationId,\n data: result,\n };\n } else {\n return result;\n }\n },\n };\n },\n fieldScope\n );\n}\n"],"file":"makeProcField.js"}
1
+ {"version":3,"sources":["../../src/plugins/makeProcField.js"],"names":["nullableIf","GraphQLNonNull","condition","Type","firstValue","obj","firstKey","k","procFieldDetails","proc","build","options","computed","isMutation","pgIntrospectionResultsByKind","introspectionResultsByKind","pgGetGqlInputTypeByTypeIdAndModifier","pgSql","sql","gql2pg","pgStrictFunctions","strictFunctions","graphql","inflection","describePgEntity","sqlCommentByAddingTags","Error","sliceAmount","argNames","argTypeIds","reduce","prev","_","idx","argModes","length","push","argTypes","typeId","typeById","argModesWithOutput","outputArgNames","includes","outputArgTypes","requiredArgCount","Math","max","argDefaultsNum","variantFromName","name","match","variantFromTags","tags","variant","parseInt","notNullArgCount","isStrict","argGqlTypes","map","type","id","hint","class","chalk","bold","green","inputs","memo","argName","argIndex","gqlArgName","argument","makeSqlFunctionCall","rawArgs","implicitArgs","unnest","args","input","sqlArgValues","haveNames","value","sqlValue","sqlArgName","identifier","unshift","fragment","functionCall","namespace","join","makeProcField","fieldName","fieldWithHooks","isRootQuery","forceList","aggregateWrapper","description","overrideDescription","pgTypeAndModifierModifier","pgGetGqlTypeByTypeIdAndModifier","getTypeByName","parseResolveInfo","getSafeAliasFromResolveInfo","getSafeAliasFromAlias","pg2gql","newWithHooks","pgTweakFragmentForTypeAndModifier","GraphQLList","GraphQLString","GraphQLObjectType","GraphQLInputObjectType","getNamedType","isCompositeType","pgQueryFromResolveData","queryFromResolveData","pgAddStartEndCursor","addStartEndCursor","pgViaTemporaryTable","viaTemporaryTable","pgField","subscriptions","pgForbidSetofFunctionsToReturnNull","pgPrepareAndRun","baseReturnType","returnTypeId","rawReturnType","returnType","isPgArray","arrayItemType","returnTypeTable","classById","classId","fieldScope","payloadTypeScope","pgFieldIntrospection","pgIntrospection","returnFirstValueAsValue","TableType","isTableLike","isRecordLike","returnsSet","innerType","isPgFieldSimpleCollection","ConnectionType","connection","isPgFieldConnection","pgFieldIntrospectionTable","pgIntrospectionTable","RecordType","recordFunctionReturnType","recordFunctionConnection","connectionTypeName","scalarFunctionConnection","addDataGenerator","getDataFromParsedResolveInfoFragment","addArgDataGenerator","addPgCursorPrefix","pgCursorPrefix","literal","makeQuery","parsedResolveInfoFragment","ReturnType","sqlMutationQuery","functionAlias","parentQueryBuilder","resolveContext","resolveInfo","resolveData","isConnection","query","useAsterisk","language","withPagination","withPaginationAsFields","asJson","asJsonAggregate","addNullCase","innerQueryBuilder","select","primaryKeyConstraint","selectIdentifiers","context","rootValue","pgQuery","queryBuilder","parentTableAlias","getTableAlias","Symbol","sqlFunctionCall","alias","PayloadType","resultFieldName","functionMutationResultFieldName","isNotVoid","String","functionPayloadType","wrapDescription","functionMutationName","fields","Object","assign","clientMutationId","resolve","data","pgType","__origin","isMutationPayload","InputType","functionInputType","isMutationInput","scalarAwarePg2gql","v","notNull","_args","liveRecord","safeAlias","makeRecordLive","record","__identifiers","_record","records","pgClient","queryResultRows","intermediateIdentifier","isVoid","isPgRecord","isPgClass","namespaceName","e","text","values","compile","debugSql","enabled","queryResult","rows","row","result","fv"],"mappings":";;;;;;;;AAOA;;AACA;;;;AAPA,MAAMA,UAAU,GAAG,CAACC,cAAD,EAAiBC,SAAjB,EAA4BC,IAA5B,KACjBD,SAAS,GAAGC,IAAH,GAAU,IAAIF,cAAJ,CAAmBE,IAAnB,CADrB;;AAyBA,MAAMC,UAAU,GAAGC,GAAG,IAAI;AACxB,MAAIC,QAAJ;;AACA,OAAK,MAAMC,CAAX,IAAgBF,GAAhB,EAAqB;AACnB,QAAIE,CAAC,CAAC,CAAD,CAAD,KAAS,GAAT,IAAgBA,CAAC,CAAC,CAAD,CAAD,KAAS,GAA7B,EAAkC;AAChCD,MAAAA,QAAQ,GAAGC,CAAX;AACD;AACF;;AACD,SAAOF,GAAG,CAACC,QAAD,CAAV;AACD,CARD;;AAUO,SAASE,gBAAT,CACLC,IADK,EAELC,KAFK,EAG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) =>\n condition ? Type : new GraphQLNonNull(Type);\n\nimport type { Build, FieldWithHooksFunction } from \"graphile-build\";\nimport type { PgProc, PgType } from \"./PgIntrospectionPlugin\";\nimport type { SQL } from \"pg-sql2\";\nimport debugSql from \"./debugSql\";\nimport chalk from \"chalk\";\n\ntype ProcFieldOptions = {\n fieldWithHooks: FieldWithHooksFunction,\n computed?: boolean,\n isMutation?: boolean,\n isRootQuery?: boolean,\n forceList?: boolean,\n aggregateWrapper?: null | ((sql: SQL) => SQL),\n description?: string,\n pgTypeAndModifierModifier?:\n | null\n | ((\n pgType: PgType,\n pgTypeModifier: null | string | number\n ) => [PgType, null | string | number]),\n};\n\nconst firstValue = obj => {\n let firstKey;\n for (const k in obj) {\n if (k[0] !== \"_\" && k[1] !== \"_\") {\n firstKey = k;\n }\n }\n return obj[firstKey];\n};\n\nexport function procFieldDetails(\n proc: PgProc,\n build: {| ...Build |},\n options: {\n computed?: boolean,\n isMutation?: boolean,\n }\n) {\n const { computed = false, isMutation = false } = options;\n const {\n pgIntrospectionResultsByKind: introspectionResultsByKind,\n pgGetGqlInputTypeByTypeIdAndModifier,\n pgSql: sql,\n gql2pg,\n pgStrictFunctions: strictFunctions,\n graphql: { GraphQLNonNull },\n inflection,\n describePgEntity,\n sqlCommentByAddingTags,\n } = build;\n\n if (computed && isMutation) {\n throw new Error(\"Mutation procedure cannot be computed\");\n }\n\n const sliceAmount = computed ? 1 : 0;\n const argNames = proc.argTypeIds.reduce((prev, _, idx) => {\n if (\n idx >= sliceAmount && // Was a .slice() call\n (proc.argModes.length === 0 || // all args are `in`\n proc.argModes[idx] === \"i\" || // this arg is `in`\n proc.argModes[idx] === \"b\") // this arg is `inout`\n ) {\n prev.push(proc.argNames[idx] || \"\");\n }\n return prev;\n }, []);\n const argTypes = proc.argTypeIds.reduce((prev, typeId, idx) => {\n if (\n idx >= sliceAmount && // Was a .slice() call\n (proc.argModes.length === 0 || // all args are `in`\n proc.argModes[idx] === \"i\" || // this arg is `in`\n proc.argModes[idx] === \"b\") // this arg is `inout`\n ) {\n prev.push(introspectionResultsByKind.typeById[typeId]);\n }\n return prev;\n }, []);\n const argModesWithOutput = [\n \"o\", // OUT,\n \"b\", // INOUT\n \"t\", // TABLE\n ];\n const outputArgNames = proc.argTypeIds.reduce((prev, _, idx) => {\n if (argModesWithOutput.includes(proc.argModes[idx])) {\n prev.push(proc.argNames[idx] || \"\");\n }\n return prev;\n }, []);\n const outputArgTypes = proc.argTypeIds.reduce((prev, typeId, idx) => {\n if (argModesWithOutput.includes(proc.argModes[idx])) {\n prev.push(introspectionResultsByKind.typeById[typeId]);\n }\n return prev;\n }, []);\n const requiredArgCount = Math.max(0, argNames.length - proc.argDefaultsNum);\n const variantFromName = name => {\n if (name.match(/(_p|P)atch$/)) {\n return \"patch\";\n }\n return null;\n };\n const variantFromTags = (tags, idx) => {\n const variant = tags[`arg${idx}variant`];\n if (variant && variant.match && variant.match(/^[0-9]+$/)) {\n return parseInt(variant, 10);\n }\n return variant;\n };\n const notNullArgCount =\n proc.isStrict || strictFunctions ? requiredArgCount : 0;\n const argGqlTypes = argTypes.map((type, idx) => {\n // TODO: PG10 doesn't support the equivalent of pg_attribute.atttypemod on function return values, but maybe a later version might\n const variant =\n variantFromTags(proc.tags, idx) || variantFromName(argNames[idx]);\n const Type = pgGetGqlInputTypeByTypeIdAndModifier(type.id, variant);\n if (!Type) {\n const hint = type.class\n ? `; this might be because no INSERT column privileges are granted on ${describePgEntity(\n type.class\n )}. You can use 'Smart Comments' to tell PostGraphile to instead use the \"${chalk.bold.green(\n \"base\"\n )}\" input type which includes all columns:\\n\\n ${sqlCommentByAddingTags(\n proc,\n {\n [`arg${idx}variant`]: \"base\",\n }\n )}\\n`\n : \"\";\n throw new Error(\n `Could not determine type for argument ${idx} ('${\n argNames[idx]\n }') of function ${describePgEntity(proc)}${hint}`\n );\n }\n if (idx >= notNullArgCount) {\n return Type;\n } else {\n return new GraphQLNonNull(Type);\n }\n });\n // This wants to be compatible with both being field arguments and being\n // input object fields (e.g. for the aggregates plugin).\n const inputs = argNames.reduce((memo, argName, argIndex) => {\n const gqlArgName = inflection.argument(argName, argIndex);\n memo[gqlArgName] = {\n type: argGqlTypes[argIndex],\n };\n return memo;\n }, {});\n\n function makeSqlFunctionCall(\n rawArgs = {},\n { implicitArgs = [], unnest = false } = {}\n ): SQL {\n const args = isMutation ? rawArgs.input : rawArgs;\n const sqlArgValues = [];\n let haveNames = true;\n for (let argIndex = argNames.length - 1; argIndex >= 0; argIndex--) {\n const argName = argNames[argIndex];\n const gqlArgName = inflection.argument(argName, argIndex);\n const value = args[gqlArgName];\n const variant =\n variantFromTags(proc.tags, argIndex) ||\n variantFromName(argNames[argIndex]);\n\n const sqlValue = gql2pg(value, argTypes[argIndex], variant);\n\n if (argIndex + 1 > requiredArgCount && haveNames && value == null) {\n // No need to pass argument to function\n continue;\n } else if (argIndex + 1 > requiredArgCount && haveNames) {\n const sqlArgName = argName ? sql.identifier(argName) : null;\n if (sqlArgName) {\n sqlArgValues.unshift(sql.fragment`${sqlArgName} := ${sqlValue}`);\n } else {\n haveNames = false;\n sqlArgValues.unshift(sqlValue);\n }\n } else {\n sqlArgValues.unshift(sqlValue);\n }\n }\n const functionCall = sql.fragment`${sql.identifier(\n proc.namespace.name,\n proc.name\n )}(${sql.join([...implicitArgs, ...sqlArgValues], \", \")})`;\n return unnest ? sql.fragment`unnest(${functionCall})` : functionCall;\n }\n\n return {\n inputs,\n makeSqlFunctionCall,\n outputArgNames,\n outputArgTypes,\n };\n}\n\nexport default function makeProcField(\n fieldName: string,\n proc: PgProc,\n build: {| ...Build |},\n options: ProcFieldOptions\n) {\n const {\n fieldWithHooks,\n computed = false,\n isMutation = false,\n isRootQuery = false,\n forceList = false,\n aggregateWrapper = null,\n description: overrideDescription = null,\n pgTypeAndModifierModifier = null,\n } = options;\n const {\n pgIntrospectionResultsByKind: introspectionResultsByKind,\n pgGetGqlTypeByTypeIdAndModifier,\n getTypeByName,\n pgSql: sql,\n parseResolveInfo,\n getSafeAliasFromResolveInfo,\n getSafeAliasFromAlias,\n pg2gql,\n newWithHooks,\n pgTweakFragmentForTypeAndModifier,\n graphql: {\n GraphQLNonNull,\n GraphQLList,\n GraphQLString,\n GraphQLObjectType,\n GraphQLInputObjectType,\n getNamedType,\n isCompositeType,\n },\n inflection,\n pgQueryFromResolveData: queryFromResolveData,\n pgAddStartEndCursor: addStartEndCursor,\n pgViaTemporaryTable: viaTemporaryTable,\n describePgEntity,\n sqlCommentByAddingTags,\n pgField,\n options: {\n subscriptions = false,\n pgForbidSetofFunctionsToReturnNull = false,\n },\n pgPrepareAndRun,\n } = build;\n\n const { inputs, makeSqlFunctionCall, outputArgNames, outputArgTypes } =\n procFieldDetails(proc, build, options);\n let args = inputs;\n\n /**\n * This is the return type the function claims to have; we\n * should not use it anywhere but these next few lines.\n */\n const baseReturnType = introspectionResultsByKind.typeById[proc.returnTypeId];\n\n /**\n * This is the return type we treat it as having, e.g. in\n * case it was modified by wrapping it in an aggregate or\n * similar.\n */\n const rawReturnType = pgTypeAndModifierModifier\n ? pgTypeAndModifierModifier(baseReturnType, null)[0]\n : baseReturnType;\n\n /**\n * This is the type without the array wrapper.\n */\n const returnType = rawReturnType.isPgArray\n ? rawReturnType.arrayItemType\n : rawReturnType;\n const returnTypeTable =\n introspectionResultsByKind.classById[returnType.classId];\n if (!returnType) {\n throw new Error(\n `Could not determine return type for function '${proc.name}'`\n );\n }\n let type;\n const fieldScope = {};\n const payloadTypeScope = {};\n fieldScope.pgFieldIntrospection = proc;\n payloadTypeScope.pgIntrospection = proc;\n let returnFirstValueAsValue = false;\n const TableType =\n returnTypeTable &&\n pgGetGqlTypeByTypeIdAndModifier(returnTypeTable.type.id, null);\n\n const isTableLike: boolean =\n (TableType && isCompositeType(TableType)) || false;\n const isRecordLike = returnType.id === \"2249\";\n if (isTableLike) {\n if (proc.returnsSet) {\n if (isMutation) {\n const innerType = pgForbidSetofFunctionsToReturnNull\n ? new GraphQLNonNull(TableType)\n : TableType;\n type = new GraphQLList(innerType);\n } else if (forceList) {\n const innerType = pgForbidSetofFunctionsToReturnNull\n ? new GraphQLNonNull(TableType)\n : TableType;\n type = new GraphQLList(innerType);\n fieldScope.isPgFieldSimpleCollection = true;\n } else {\n const ConnectionType = getTypeByName(\n inflection.connection(TableType.name)\n );\n if (!ConnectionType) {\n throw new Error(\n `Do not have a connection type '${inflection.connection(\n TableType.name\n )}' for '${TableType.name}' so cannot create procedure field`\n );\n }\n type = ConnectionType;\n fieldScope.isPgFieldConnection = true;\n }\n fieldScope.pgFieldIntrospectionTable = returnTypeTable;\n payloadTypeScope.pgIntrospectionTable = returnTypeTable;\n } else {\n type = TableType;\n if (rawReturnType.isPgArray) {\n // Not implementing pgForbidSetofFunctionsToReturnNull here because it's not a set\n type = new GraphQLList(type);\n }\n fieldScope.pgFieldIntrospectionTable = returnTypeTable;\n payloadTypeScope.pgIntrospectionTable = returnTypeTable;\n }\n } else if (isRecordLike) {\n const RecordType = getTypeByName(inflection.recordFunctionReturnType(proc));\n if (!RecordType) {\n throw new Error(\n `Do not have a record type '${inflection.recordFunctionReturnType(\n proc\n )}' for '${proc.name}' so cannot create procedure field`\n );\n }\n if (proc.returnsSet) {\n if (isMutation) {\n type = new GraphQLList(RecordType);\n } else if (forceList) {\n type = new GraphQLList(RecordType);\n fieldScope.isPgFieldSimpleCollection = true;\n } else {\n const ConnectionType = getTypeByName(\n inflection.recordFunctionConnection(proc)\n );\n if (!ConnectionType) {\n throw new Error(\n `Do not have a connection type '${inflection.recordFunctionConnection(\n proc\n )}' for '${RecordType.name}' so cannot create procedure field`\n );\n }\n type = ConnectionType;\n fieldScope.isPgFieldConnection = true;\n }\n } else {\n type = RecordType;\n if (rawReturnType.isPgArray) {\n type = new GraphQLList(type);\n }\n }\n } else {\n // TODO: PG10 doesn't support the equivalent of pg_attribute.atttypemod on function return values, but maybe a later version might\n const Type =\n pgGetGqlTypeByTypeIdAndModifier(returnType.id, null) || GraphQLString;\n\n if (proc.returnsSet) {\n const connectionTypeName = inflection.scalarFunctionConnection(proc);\n const ConnectionType = getTypeByName(connectionTypeName);\n if (isMutation) {\n // Cannot return a connection because it would have to run the mutation again\n type = new GraphQLList(Type);\n returnFirstValueAsValue = true;\n } else if (forceList || !ConnectionType) {\n type = new GraphQLList(Type);\n returnFirstValueAsValue = true;\n fieldScope.isPgFieldSimpleCollection = true;\n } else {\n type = ConnectionType;\n fieldScope.isPgFieldConnection = true;\n // We don't return the first value as the value here because it gets\n // sent down into PgScalarFunctionConnectionPlugin so the relevant\n // EdgeType can return cursor / node; i.e. we might want to add an\n // `__cursor` field so we can't just use a scalar.\n }\n } else {\n returnFirstValueAsValue = true;\n type = Type;\n if (rawReturnType.isPgArray) {\n type = new GraphQLList(type);\n }\n }\n }\n return fieldWithHooks(\n fieldName,\n ({\n addDataGenerator,\n getDataFromParsedResolveInfoFragment,\n addArgDataGenerator,\n }) => {\n if (\n proc.returnsSet &&\n !isTableLike &&\n !returnFirstValueAsValue &&\n !isMutation\n ) {\n // Natural ordering\n addArgDataGenerator(function addPgCursorPrefix() {\n return {\n pgCursorPrefix: sql.literal(\"natural\"),\n };\n });\n }\n function makeQuery(\n parsedResolveInfoFragment,\n ReturnType,\n sqlMutationQuery,\n functionAlias,\n parentQueryBuilder,\n resolveContext,\n resolveInfo\n ) {\n const resolveData = getDataFromParsedResolveInfoFragment(\n parsedResolveInfoFragment,\n ReturnType\n );\n const isConnection = !forceList && !isMutation && proc.returnsSet;\n const query = queryFromResolveData(\n sqlMutationQuery,\n functionAlias,\n resolveData,\n {\n useAsterisk:\n !isMutation &&\n (isTableLike || isRecordLike) &&\n (forceList || proc.returnsSet || rawReturnType.isPgArray) && // only bother with lists\n proc.language !== \"sql\", // sql functions can be inlined, so GRANTs still apply\n withPagination: isConnection,\n withPaginationAsFields: isConnection && !computed,\n asJson:\n computed &&\n (forceList || (!proc.returnsSet && !returnFirstValueAsValue)),\n asJsonAggregate:\n computed &&\n (forceList || (!proc.returnsSet && rawReturnType.isPgArray)),\n addNullCase:\n !proc.returnsSet &&\n !rawReturnType.isPgArray &&\n (isTableLike || isRecordLike),\n },\n innerQueryBuilder => {\n innerQueryBuilder.parentQueryBuilder = parentQueryBuilder;\n if (!isTableLike) {\n if (returnTypeTable) {\n innerQueryBuilder.select(\n pgTweakFragmentForTypeAndModifier(\n sql.fragment`${functionAlias}`,\n returnTypeTable.type,\n null,\n resolveData\n ),\n \"value\"\n );\n } else {\n innerQueryBuilder.select(\n pgTweakFragmentForTypeAndModifier(\n sql.fragment`${functionAlias}`,\n returnType,\n null, // We can't determine a type modifier for functions\n resolveData\n ),\n \"value\"\n );\n }\n } else if (\n subscriptions &&\n returnTypeTable &&\n !isConnection &&\n returnTypeTable.primaryKeyConstraint\n ) {\n innerQueryBuilder.selectIdentifiers(returnTypeTable);\n }\n },\n parentQueryBuilder ? parentQueryBuilder.context : resolveContext,\n parentQueryBuilder\n ? parentQueryBuilder.rootValue\n : resolveInfo && resolveInfo.rootValue\n );\n return query;\n }\n if (computed) {\n addDataGenerator((parsedResolveInfoFragment, ReturnType) => {\n return {\n pgQuery: queryBuilder => {\n queryBuilder.select(() => {\n const parentTableAlias = queryBuilder.getTableAlias();\n const functionAlias = sql.identifier(Symbol());\n const sqlFunctionCall = makeSqlFunctionCall(\n parsedResolveInfoFragment.args,\n {\n implicitArgs: [parentTableAlias],\n unnest: rawReturnType.isPgArray,\n }\n );\n if (aggregateWrapper) {\n return aggregateWrapper(sqlFunctionCall);\n } else {\n const query = makeQuery(\n parsedResolveInfoFragment,\n ReturnType,\n sqlFunctionCall,\n functionAlias,\n queryBuilder\n );\n return sql.fragment`(${query})`;\n }\n }, getSafeAliasFromAlias(parsedResolveInfoFragment.alias));\n },\n };\n });\n }\n\n let ReturnType = type;\n let PayloadType;\n if (isMutation) {\n const resultFieldName = inflection.functionMutationResultFieldName(\n proc,\n getNamedType(type),\n proc.returnsSet || rawReturnType.isPgArray,\n outputArgNames\n );\n const isNotVoid = String(returnType.id) !== \"2278\";\n // If set then plural name\n PayloadType = newWithHooks(\n GraphQLObjectType,\n {\n name: inflection.functionPayloadType(proc),\n description: build.wrapDescription(\n `The output of our \\`${inflection.functionMutationName(\n proc\n )}\\` mutation.`,\n \"type\"\n ),\n fields: ({ fieldWithHooks }) => {\n return Object.assign(\n {},\n {\n clientMutationId: {\n type: GraphQLString,\n },\n },\n isNotVoid\n ? {\n [resultFieldName]: pgField(\n build,\n fieldWithHooks,\n resultFieldName,\n {\n type: type,\n ...(returnFirstValueAsValue\n ? {\n resolve(data) {\n return data.data;\n },\n }\n : null),\n },\n {},\n false,\n {\n pgType: returnType,\n }\n ),\n // Result\n }\n : null\n );\n },\n },\n {\n __origin: `Adding mutation function payload type for ${describePgEntity(\n proc\n )}. You can rename the function's GraphQL field (and its dependent types) via a 'Smart Comment':\\n\\n ${sqlCommentByAddingTags(\n proc,\n {\n name: \"newNameHere\",\n }\n )}`,\n isMutationPayload: true,\n ...payloadTypeScope,\n }\n );\n ReturnType = PayloadType;\n const InputType = newWithHooks(\n GraphQLInputObjectType,\n {\n name: inflection.functionInputType(proc),\n description: build.wrapDescription(\n `All input for the \\`${inflection.functionMutationName(\n proc\n )}\\` mutation.`,\n \"type\"\n ),\n fields: {\n clientMutationId: {\n type: GraphQLString,\n },\n ...args,\n },\n },\n {\n __origin: `Adding mutation function input type for ${describePgEntity(\n proc\n )}. You can rename the function's GraphQL field (and its dependent types) via a 'Smart Comment':\\n\\n ${sqlCommentByAddingTags(\n proc,\n {\n name: \"newNameHere\",\n }\n )}`,\n isMutationInput: true,\n }\n );\n args = {\n input: {\n type: new GraphQLNonNull(InputType),\n },\n };\n }\n // If this is a table we can process it directly; but if it's a scalar\n // setof function we must dereference '.value' from it, because this\n // makes space for '__cursor' to exist alongside it (whereas on a table\n // the '__cursor' can just be on the table object itself)\n const scalarAwarePg2gql = v =>\n isTableLike\n ? pg2gql(v, returnType)\n : {\n ...v,\n value: pg2gql(v.value, returnType),\n };\n\n return {\n description: overrideDescription\n ? overrideDescription\n : proc.description\n ? proc.description\n : isMutation\n ? null\n : isTableLike && proc.returnsSet\n ? build.wrapDescription(\n `Reads and enables pagination through a set of \\`${TableType.name}\\`.`,\n \"field\"\n )\n : null,\n type: nullableIf(\n GraphQLNonNull,\n !proc.tags.notNull &&\n (!fieldScope.isPgFieldConnection || isMutation || isRootQuery),\n ReturnType\n ),\n args: args,\n resolve: computed\n ? (data, _args, resolveContext, resolveInfo) => {\n const liveRecord =\n resolveInfo.rootValue && resolveInfo.rootValue.liveRecord;\n const safeAlias = getSafeAliasFromResolveInfo(resolveInfo);\n const value = data[safeAlias];\n if (returnFirstValueAsValue) {\n // Is not table like; is not record like.\n if (proc.returnsSet && !forceList) {\n // EITHER `isMutation` is true, or `ConnectionType` does not\n // exist - either way, we're not returning a connection.\n return value.data.map(v => pg2gql(firstValue(v), returnType));\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n return value.map(v => pg2gql(firstValue(v), returnType));\n } else {\n return pg2gql(value, returnType);\n }\n } else {\n const makeRecordLive =\n subscriptions && isTableLike && returnTypeTable && liveRecord\n ? record => {\n if (record) {\n liveRecord(\n \"pg\",\n returnTypeTable,\n record.__identifiers\n );\n }\n }\n : _record => {};\n if (proc.returnsSet && !isMutation && !forceList) {\n // Connection - do not make live (the connection will handle this)\n return addStartEndCursor({\n ...value,\n data: value.data ? value.data.map(scalarAwarePg2gql) : null,\n });\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n // List\n const records = value.map(v => {\n makeRecordLive(v);\n return pg2gql(v, returnType);\n });\n return records;\n } else {\n // Object\n if (value) {\n makeRecordLive(value);\n }\n return pg2gql(value, returnType);\n }\n }\n }\n : async (data, args, resolveContext, resolveInfo) => {\n const { pgClient } = resolveContext;\n const liveRecord =\n resolveInfo.rootValue && resolveInfo.rootValue.liveRecord;\n const parsedResolveInfoFragment = parseResolveInfo(resolveInfo);\n parsedResolveInfoFragment.args = args; // Allow overriding via makeWrapResolversPlugin\n const functionAlias = sql.identifier(Symbol());\n const sqlFunctionCall = makeSqlFunctionCall(\n parsedResolveInfoFragment.args,\n {\n unnest: rawReturnType.isPgArray,\n }\n );\n\n let queryResultRows;\n if (isMutation) {\n const query = makeQuery(\n parsedResolveInfoFragment,\n resolveInfo.returnType,\n functionAlias,\n functionAlias,\n null,\n resolveContext,\n resolveInfo\n );\n const intermediateIdentifier = sql.identifier(Symbol());\n const isVoid = returnType.id === \"2278\";\n const isPgRecord = returnType.id === \"2249\";\n const isPgClass =\n !isPgRecord &&\n (!returnFirstValueAsValue || returnTypeTable || false);\n try {\n await pgClient.query(\"SAVEPOINT graphql_mutation\");\n queryResultRows = await viaTemporaryTable(\n pgClient,\n isVoid\n ? null\n : sql.identifier(\n returnType.namespaceName,\n returnType.name\n ),\n sql.query`select ${\n isPgClass\n ? sql.query`${intermediateIdentifier}.*`\n : isPgRecord\n ? sql.query`${intermediateIdentifier}.*`\n : sql.query`${intermediateIdentifier} as ${functionAlias}`\n } from ${sqlFunctionCall} ${intermediateIdentifier}`,\n functionAlias,\n query,\n isPgClass,\n isPgRecord\n ? {\n outputArgTypes,\n outputArgNames,\n }\n : null\n );\n await pgClient.query(\"RELEASE SAVEPOINT graphql_mutation\");\n } catch (e) {\n await pgClient.query(\n \"ROLLBACK TO SAVEPOINT graphql_mutation\"\n );\n throw e;\n }\n } else {\n const query = makeQuery(\n parsedResolveInfoFragment,\n resolveInfo.returnType,\n sqlFunctionCall,\n functionAlias,\n null,\n resolveContext,\n resolveInfo\n );\n const { text, values } = sql.compile(query);\n if (debugSql.enabled) debugSql(text);\n const queryResult = await pgPrepareAndRun(\n pgClient,\n text,\n values\n );\n queryResultRows = queryResult.rows;\n }\n const rows = queryResultRows;\n const [row] = rows;\n const result = (() => {\n const makeRecordLive =\n subscriptions && isTableLike && returnTypeTable && liveRecord\n ? record => {\n if (record) {\n liveRecord(\n \"pg\",\n returnTypeTable,\n record.__identifiers\n );\n }\n }\n : _record => {};\n if (returnFirstValueAsValue) {\n // `returnFirstValueAsValue` implies either `isMutation` is\n // true, or `ConnectionType` does not exist - either way,\n // we're not returning a connection.\n if (proc.returnsSet && !isMutation && !forceList) {\n return row.data.map(v => {\n const fv = firstValue(v);\n makeRecordLive(fv);\n return pg2gql(fv, returnType);\n });\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n return rows.map(v => {\n const fv = firstValue(v);\n makeRecordLive(fv);\n return pg2gql(fv, returnType);\n });\n } else {\n const fv = firstValue(row);\n makeRecordLive(fv);\n const record = pg2gql(fv, returnType);\n return record;\n }\n } else {\n if (proc.returnsSet && !isMutation && !forceList) {\n // Connection\n const data = row.data\n ? row.data.map(scalarAwarePg2gql)\n : null;\n return addStartEndCursor({\n ...row,\n data,\n });\n } else if (proc.returnsSet || rawReturnType.isPgArray) {\n // List\n return rows.map(row => {\n makeRecordLive(row);\n return pg2gql(row, returnType);\n });\n } else {\n // Object\n makeRecordLive(row);\n return pg2gql(row, returnType);\n }\n }\n })();\n if (isMutation) {\n return {\n clientMutationId: args.input.clientMutationId,\n data: result,\n };\n } else {\n return result;\n }\n },\n };\n },\n fieldScope\n );\n}\n"],"file":"makeProcField.js"}
@@ -34,10 +34,8 @@ export default function pgField(
34
34
  "pgField call omits options.pgType for a leaf type; certain tweaks may not be applied!"
35
35
  );
36
36
  }
37
- const {
38
- getDataFromParsedResolveInfoFragment,
39
- addDataGenerator,
40
- } = fieldContext;
37
+ const { getDataFromParsedResolveInfoFragment, addDataGenerator } =
38
+ fieldContext;
41
39
  addDataGenerator(parsedResolveInfoFragment => {
42
40
  const safeAlias = getSafeAliasFromAlias(
43
41
  parsedResolveInfoFragment.alias
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/pgField.js"],"names":["pgField","build","fieldWithHooks","fieldName","fieldSpecGenerator","fieldScope","whereFrom","options","pgSql","sql","pgQueryFromResolveData","queryFromResolveData","getSafeAliasFromAlias","getSafeAliasFromResolveInfo","pgTweakFragmentForTypeAndModifier","fieldContext","fieldSpec","type","FieldType","nullableType","graphql","getNullableType","namedType","getNamedType","isListType","constructor","GraphQLList","isLeafType","pgType","Error","getDataFromParsedResolveInfoFragment","addDataGenerator","parsedResolveInfoFragment","safeAlias","alias","resolveData","hoistCursor","usesCursor","length","pgQuery","queryBuilder","select","tableAlias","getTableAlias","identifier","Symbol","query","pgTypeModifier","onlyJsonField","asJson","innerQueryBuilder","parentQueryBuilder","withQueryBuilder","context","rootValue","fragment","resolve","data","_args","_context","resolveInfo","map","d"],"mappings":";;;;;;;AAAe,SAASA,OAAT,CACbC,KADa,EAEbC,cAFa,EAGbC,SAHa,EAIbC,kBAJa,EAKbC,UAAU,GAAG,EALA,EAMbC,SAAS,GAAG,KANC,EAObC,OAAO,GAAG,EAPG,EAQb;AACA,QAAM;AACJC,IAAAA,KAAK,EAAEC,GADH;AAEJC,IAAAA,sBAAsB,EAAEC,oBAFpB;AAGJC,IAAAA,qBAHI;AAIJC,IAAAA,2BAJI;AAKJC,IAAAA;AALI,MAMFb,KANJ;AAOA,SAAOC,cAAc,CACnBC,SADmB,EAEnBY,YAAY,IAAI;AACd,UAAMC,SAAS,GACb,OAAOZ,kBAAP,KAA8B,UAA9B,GACIA,kBAAkB,CAACW,YAAD,CADtB,GAEIX,kBAHN;AAIA,UAAM;AAAEa,MAAAA,IAAI,EAAEC;AAAR,QAAsBF,SAA5B;AACA,UAAMG,YAAY,GAAGlB,KAAK,CAACmB,OAAN,CAAcC,eAAd,CAA8BH,SAA9B,CAArB;AACA,UAAMI,SAAS,GAAGrB,KAAK,CAACmB,OAAN,CAAcG,YAAd,CAA2BL,SAA3B,CAAlB;AACA,UAAMM,UAAU,GACdL,YAAY,KAAKG,SAAjB,IACAH,YAAY,CAACM,WAAb,KAA6BxB,KAAK,CAACmB,OAAN,CAAcM,WAF7C;AAGA,UAAMC,UAAU,GAAG1B,KAAK,CAACmB,OAAN,CAAcO,UAAd,CAAyBT,SAAzB,CAAnB;;AACA,QAAIS,UAAU,IAAI,CAACpB,OAAO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lB,GAAuCX,YAAvC;;AACA,kBAAI,OAAOjC,OAAO,CAAC6C,gBAAf,KAAoC,UAAxC,EAAoD;AAClD7C,gBAAAA,OAAO,CAAC6C,gBAAR,CAAyBF,iBAAzB,EAA4C;AAC1ClB,kBAAAA;AAD0C,iBAA5C;AAGD;AACF,aArB+B,EAsBhCQ,YAAY,CAACa,OAtBmB,EAuBhCb,YAAY,CAACc,SAvBmB,CAAlC;AAyBA,mBAAO7C,GAAG,CAAC8C,QAAS,IAAGT,KAAM,GAA7B;AACD,WA/BD,EA+BGb,SA/BH;AAgCD;AAvCI,OAAP;AAyCD,KAjDe,CAAhB;AAmDA,WAAO;AACLuB,MAAAA,OAAO,CAACC,IAAD,EAAOC,KAAP,EAAcC,QAAd,EAAwBC,WAAxB,EAAqC;AAC1C,cAAM3B,SAAS,GAAGpB,2BAA2B,CAAC+C,WAAD,CAA7C;AACA,YAAIH,IAAI,CAACA,IAAL,IAAa,IAAjB,EAAuB,OAAO,IAAP;;AACvB,YAAIjC,UAAJ,EAAgB;AACd,iBAAOiC,IAAI,CAACA,IAAL,CAAUI,GAAV,CAAcC,CAAC,IAAKA,CAAC,IAAI,IAAL,GAAYA,CAAC,CAAC7B,SAAD,CAAb,GAA2B,IAA/C,CAAP;AACD,SAFD,MAEO;AACL,iBAAOwB,IAAI,CAACA,IAAL,CAAUxB,SAAV,CAAP;AACD;AACF,OATI;;AAUL,SAAGjB;AAVE,KAAP;AAYD,GAvFkB,EAwFnBX,UAxFmB,CAArB;AA0FD","sourcesContent":["export default function pgField(\n build,\n fieldWithHooks,\n fieldName,\n fieldSpecGenerator,\n fieldScope = {},\n whereFrom = false,\n options = {}\n) {\n const {\n pgSql: sql,\n pgQueryFromResolveData: queryFromResolveData,\n getSafeAliasFromAlias,\n getSafeAliasFromResolveInfo,\n pgTweakFragmentForTypeAndModifier,\n } = build;\n return fieldWithHooks(\n fieldName,\n fieldContext => {\n const fieldSpec =\n typeof fieldSpecGenerator === \"function\"\n ? fieldSpecGenerator(fieldContext)\n : fieldSpecGenerator;\n const { type: FieldType } = fieldSpec;\n const nullableType = build.graphql.getNullableType(FieldType);\n const namedType = build.graphql.getNamedType(FieldType);\n const isListType =\n nullableType !== namedType &&\n nullableType.constructor === build.graphql.GraphQLList;\n const isLeafType = build.graphql.isLeafType(FieldType);\n if (isLeafType && !options.pgType) {\n // eslint-disable-next-line no-console\n throw new Error(\n \"pgField call omits options.pgType for a leaf type; certain tweaks may not be applied!\"\n );\n }\n const {\n getDataFromParsedResolveInfoFragment,\n addDataGenerator,\n } = fieldContext;\n addDataGenerator(parsedResolveInfoFragment => {\n const safeAlias = getSafeAliasFromAlias(\n parsedResolveInfoFragment.alias\n );\n const resolveData = getDataFromParsedResolveInfoFragment(\n parsedResolveInfoFragment,\n FieldType\n );\n return {\n ...(options.hoistCursor &&\n resolveData.usesCursor &&\n resolveData.usesCursor.length\n ? { usesCursor: [true] }\n : null),\n pgQuery: queryBuilder => {\n queryBuilder.select(() => {\n const tableAlias =\n whereFrom === false\n ? queryBuilder.getTableAlias()\n : sql.identifier(Symbol());\n const query = queryFromResolveData(\n whereFrom ? whereFrom(queryBuilder) : sql.identifier(Symbol()),\n isLeafType && options.pgType\n ? pgTweakFragmentForTypeAndModifier(\n tableAlias,\n options.pgType,\n options.pgTypeModifier,\n {}\n )\n : tableAlias,\n resolveData,\n whereFrom === false\n ? { onlyJsonField: true }\n : { asJson: true },\n innerQueryBuilder => {\n innerQueryBuilder.parentQueryBuilder = queryBuilder;\n if (typeof options.withQueryBuilder === \"function\") {\n options.withQueryBuilder(innerQueryBuilder, {\n parsedResolveInfoFragment,\n });\n }\n },\n queryBuilder.context,\n queryBuilder.rootValue\n );\n return sql.fragment`(${query})`;\n }, safeAlias);\n },\n };\n });\n\n return {\n resolve(data, _args, _context, resolveInfo) {\n const safeAlias = getSafeAliasFromResolveInfo(resolveInfo);\n if (data.data == null) return null;\n if (isListType) {\n return data.data.map(d => (d != null ? d[safeAlias] : null));\n } else {\n return data.data[safeAlias];\n }\n },\n ...fieldSpec,\n };\n },\n fieldScope\n );\n}\n"],"file":"pgField.js"}
1
+ {"version":3,"sources":["../../src/plugins/pgField.js"],"names":["pgField","build","fieldWithHooks","fieldName","fieldSpecGenerator","fieldScope","whereFrom","options","pgSql","sql","pgQueryFromResolveData","queryFromResolveData","getSafeAliasFromAlias","getSafeAliasFromResolveInfo","pgTweakFragmentForTypeAndModifier","fieldContext","fieldSpec","type","FieldType","nullableType","graphql","getNullableType","namedType","getNamedType","isListType","constructor","GraphQLList","isLeafType","pgType","Error","getDataFromParsedResolveInfoFragment","addDataGenerator","parsedResolveInfoFragment","safeAlias","alias","resolveData","hoistCursor","usesCursor","length","pgQuery","queryBuilder","select","tableAlias","getTableAlias","identifier","Symbol","query","pgTypeModifier","onlyJsonField","asJson","innerQueryBuilder","parentQueryBuilder","withQueryBuilder","context","rootValue","fragment","resolve","data","_args","_context","resolveInfo","map","d"],"mappings":";;;;;;;AAAe,SAASA,OAAT,CACbC,KADa,EAEbC,cAFa,EAGbC,SAHa,EAIbC,kBAJa,EAKbC,UAAU,GAAG,EALA,EAMbC,SAAS,GAAG,KANC,EAObC,OAAO,GAAG,EAPG,EAQb;AACA,QAAM;AACJC,IAAAA,KAAK,EAAEC,GADH;AAEJC,IAAAA,sBAAsB,EAAEC,oBAFpB;AAGJC,IAAAA,qBAHI;AAIJC,IAAAA,2BAJI;AAKJC,IAAAA;AALI,MAMFb,KANJ;AAOA,SAAOC,cAAc,CACnBC,SADmB,EAEnBY,YAAY,IAAI;AACd,UAAMC,SAAS,GACb,OAAOZ,kBAAP,KAA8B,UAA9B,GACIA,kBAAkB,CAACW,YAAD,CADtB,GAEIX,kBAHN;AAIA,UAAM;AAAEa,MAAAA,IAAI,EAAEC;AAAR,QAAsBF,SAA5B;AACA,UAAMG,YAAY,GAAGlB,KAAK,CAACmB,OAAN,CAAcC,eAAd,CAA8BH,SAA9B,CAArB;AACA,UAAMI,SAAS,GAAGrB,KAAK,CAACmB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\n build,\n fieldWithHooks,\n fieldName,\n fieldSpecGenerator,\n fieldScope = {},\n whereFrom = false,\n options = {}\n) {\n const {\n pgSql: sql,\n pgQueryFromResolveData: queryFromResolveData,\n getSafeAliasFromAlias,\n getSafeAliasFromResolveInfo,\n pgTweakFragmentForTypeAndModifier,\n } = build;\n return fieldWithHooks(\n fieldName,\n fieldContext => {\n const fieldSpec =\n typeof fieldSpecGenerator === \"function\"\n ? fieldSpecGenerator(fieldContext)\n : fieldSpecGenerator;\n const { type: FieldType } = fieldSpec;\n const nullableType = build.graphql.getNullableType(FieldType);\n const namedType = build.graphql.getNamedType(FieldType);\n const isListType =\n nullableType !== namedType &&\n nullableType.constructor === build.graphql.GraphQLList;\n const isLeafType = build.graphql.isLeafType(FieldType);\n if (isLeafType && !options.pgType) {\n // eslint-disable-next-line no-console\n throw new Error(\n \"pgField call omits options.pgType for a leaf type; certain tweaks may not be applied!\"\n );\n }\n const { getDataFromParsedResolveInfoFragment, addDataGenerator } =\n fieldContext;\n addDataGenerator(parsedResolveInfoFragment => {\n const safeAlias = getSafeAliasFromAlias(\n parsedResolveInfoFragment.alias\n );\n const resolveData = getDataFromParsedResolveInfoFragment(\n parsedResolveInfoFragment,\n FieldType\n );\n return {\n ...(options.hoistCursor &&\n resolveData.usesCursor &&\n resolveData.usesCursor.length\n ? { usesCursor: [true] }\n : null),\n pgQuery: queryBuilder => {\n queryBuilder.select(() => {\n const tableAlias =\n whereFrom === false\n ? queryBuilder.getTableAlias()\n : sql.identifier(Symbol());\n const query = queryFromResolveData(\n whereFrom ? whereFrom(queryBuilder) : sql.identifier(Symbol()),\n isLeafType && options.pgType\n ? pgTweakFragmentForTypeAndModifier(\n tableAlias,\n options.pgType,\n options.pgTypeModifier,\n {}\n )\n : tableAlias,\n resolveData,\n whereFrom === false\n ? { onlyJsonField: true }\n : { asJson: true },\n innerQueryBuilder => {\n innerQueryBuilder.parentQueryBuilder = queryBuilder;\n if (typeof options.withQueryBuilder === \"function\") {\n options.withQueryBuilder(innerQueryBuilder, {\n parsedResolveInfoFragment,\n });\n }\n },\n queryBuilder.context,\n queryBuilder.rootValue\n );\n return sql.fragment`(${query})`;\n }, safeAlias);\n },\n };\n });\n\n return {\n resolve(data, _args, _context, resolveInfo) {\n const safeAlias = getSafeAliasFromResolveInfo(resolveInfo);\n if (data.data == null) return null;\n if (isListType) {\n return data.data.map(d => (d != null ? d[safeAlias] : null));\n } else {\n return data.data[safeAlias];\n }\n },\n ...fieldSpec,\n };\n },\n fieldScope\n );\n}\n"],"file":"pgField.js"}
@@ -11,9 +11,9 @@ var _debugSql = _interopRequireDefault(require("./debugSql"));
11
11
 
12
12
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
13
 
14
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
14
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
15
 
16
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
16
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
17
 
18
18
  /*
19
19
  * Originally we tried this with a CTE, but:
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/viaTemporaryTable.js"],"names":["viaTemporaryTable","pgClient","sqlTypeIdentifier","sqlMutationQuery","sqlResultSourceAlias","sqlResultQuery","isPgClassLike","pgRecordInfo","undefined","isPgRecord","outputArgTypes","outputArgNames","performQuery","sqlQuery","text","values","sql","compile","debugSql","enabled","query","rows","selectionField","join","map","outputArgName","idx","identifier","result","firstNonNullRow","find","row","firstKey","Object","keys","rawValues","filter","rawValue","sqlValuesAlias","Symbol","convertFieldBack","value","literal","isFake","namespaceName","name","filteredValuesResults","length","finalRows","__isNull","shift"],"mappings":";;;;;;;AAEA;;AAGA;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8Be,eAAeA,iBAAf,CACbC,QADa,EAEbC,iBAFa,EAGbC,gBAHa,EAIbC,oBAJa,EAKbC,cALa,EAMbC,aAAsB,GAAG,IANZ,EAObC,YAIC,GAAGC,SAXS,EAYb;AACA,QAAMC,UAAU,GAAGF,YAAY,IAAI,IAAnC;AACA,QAAM;AAAEG,IAAAA,cAAF;AAAkBC,IAAAA;AAAlB,MAAqCJ,YAAY,IAAI,EAA3D;;AAEA,iBAAeK,YAAf,CAA4BX,QAA5B,EAA8CY,QAA9C,EAAkE;AAChE;AACA,UAAM;AAAEC,MAAAA,IAAF;AAAQC,MAAAA;AAAR,QAAmB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AIzB,GAAG,CAACI,KAAM,IAAGJ,GAAG,CAACyB,KAAJ,CAAUA,KAAV,CAAiB,WAAlD,CADK,EAEL,IAFK,CAGL,QAAOH,cAAe,qBA1Bd,GA2BVtB,GAAG,CAACI,KAAM;cACJlB,iBAAkB,OAAME,oBAAqB;eAC5CY,GAAG,CAACyB,KAAJ,CAAU1B,MAAV,CAAkB,gBAjC7B;AAkCA,UAAM;AAAEM,MAAAA,IAAI,EAAEyB;AAAR,QACJ/B,MAAM,CAACgC,MAAP,GAAgB,CAAhB,GACI,MAAMnC,YAAY,CAChBX,QADgB,EAEhBe,GAAG,CAACI,KAAM,QAAOhB,oBAAqB,QAAOoC,gBAAiB,KAAInC,cAAe,EAFjE,CADtB,GAKI;AAAEgB,MAAAA,IAAI,EAAE;AAAR,KANN;AAOA,UAAM2B,SAAS,GAAGb,SAAS,CAACX,GAAV,CAAca,QAAQ;AACtC;;;;;;AAMAA,IAAAA,QAAQ,KAAK,IAAb,GAAoB;AAAEY,MAAAA,QAAQ,EAAE;AAAZ,KAApB,GAAyCH,qBAAqB,CAACI,KAAtB,EAPzB,CAAlB;AASA,WAAOF,SAAP;AACD;AACF","sourcesContent":["// @flow\n\nimport * as sql from \"pg-sql2\";\nimport type { Client } from \"pg\";\nimport type { SQL, SQLQuery } from \"pg-sql2\";\nimport debugSql from \"./debugSql\";\n\n/*\n * Originally we tried this with a CTE, but:\n *\n * > The sub-statements in WITH are executed concurrently with each other and\n * > with the main query. Therefore, when using data-modifying statements in\n * > WITH, the order in which the specified updates actually happen is\n * > unpredictable. All the statements are executed with the same snapshot (see\n * > Chapter 13), so they cannot \"see\" one another's effects on the target\n * > tables. This alleviates the effects of the unpredictability of the actual\n * > order of row updates, and means that RETURNING data is the only way to\n * > communicate changes between different WITH sub-statements and the main\n * > query.\n *\n * -- https://www.postgresql.org/docs/9.6/static/queries-with.html\n *\n * This caused issues with computed columns that themselves went off and\n * performed selects - because the data within those selects used the old\n * snapshot and thus returned stale data.\n *\n * To solve this, we tried using temporary tables to ensure the mutation and\n * the select execute in different statments. This worked, but temporary tables\n * require elevated priviliges and thus don't work everywhere. We needed a more\n * generic solution.\n *\n * In the end we settled for sending the data we received from the mutations\n * straight back into the PostgreSQL server. It's a bit wasteful but it works.\n *\n * If you can come up with a better solution please open a pull request!\n */\n\nexport default async function viaTemporaryTable(\n pgClient: Client,\n sqlTypeIdentifier: ?SQL,\n sqlMutationQuery: SQL,\n sqlResultSourceAlias: SQL,\n sqlResultQuery: SQL,\n isPgClassLike: boolean = true,\n pgRecordInfo: ?{\n // eslint-disable-next-line flowtype/no-weak-types\n outputArgTypes: Array<any>,\n outputArgNames: Array<string>,\n } = undefined\n) {\n const isPgRecord = pgRecordInfo != null;\n const { outputArgTypes, outputArgNames } = pgRecordInfo || {};\n\n async function performQuery(pgClient: Client, sqlQuery: SQLQuery) {\n // TODO: look into rowMode = 'array'\n const { text, values } = sql.compile(sqlQuery);\n if (debugSql.enabled) debugSql(text);\n return pgClient.query(text, values);\n }\n\n if (!sqlTypeIdentifier) {\n // It returns void, just perform the query!\n const { rows } = await performQuery(\n pgClient,\n sql.query`with ${sqlResultSourceAlias} as (${sqlMutationQuery}) ${sqlResultQuery}`\n );\n return rows;\n } else {\n /*\n * In this code we're converting the rows to a string representation within\n * PostgreSQL itself, then we can send it back into PostgreSQL and have it\n * re-interpret the results cleanly (using it's own serializer/parser\n * combination) so we should be fairly confident that it will work\n * correctly every time assuming none of the PostgreSQL types are broken.\n *\n * If you have a way to improve this, I'd love to see a PR - but please\n * make sure that the integration tests pass with your solution first as\n * there are a log of potential pitfalls!\n */\n const selectionField = isPgClassLike\n ? /*\n * This `when foo is null then null` check might *seem* redundant, but it\n * is not - e.g. the compound type `(,,,,,,,)::my_type` and\n * `null::my_type` differ; however the former also returns true to `foo\n * is null`. We use this check to coalesce both into the canonical `null`\n * representation to make it easier to deal with below.\n */\n sql.query`(case when ${sqlResultSourceAlias} is null then null else ${sqlResultSourceAlias} end)`\n : isPgRecord\n ? sql.query`array[${sql.join(\n outputArgNames.map(\n (outputArgName, idx) =>\n sql.query`${sqlResultSourceAlias}.${sql.identifier(\n // According to https://www.postgresql.org/docs/10/static/sql-createfunction.html,\n // \"If you omit the name for an output argument, the system will choose a default column name.\"\n // In PG 9.x and 10, the column names appear to be assigned with a `column` prefix.\n outputArgName !== \"\" ? outputArgName : `column${idx + 1}`\n )}::text`\n ),\n \" ,\"\n )}]`\n : sql.query`(${sqlResultSourceAlias}.${sqlResultSourceAlias})::${sqlTypeIdentifier}`;\n const result = await performQuery(\n pgClient,\n sql.query`with ${sqlResultSourceAlias} as (${sqlMutationQuery}) select (${selectionField})::text from ${sqlResultSourceAlias}`\n );\n const { rows } = result;\n const firstNonNullRow = rows.find(row => row !== null);\n // TODO: we should be able to have `pg` not interpret the results as\n // objects and instead just return them as arrays - then we can just do\n // `row[0]`. PR welcome!\n const firstKey = firstNonNullRow && Object.keys(firstNonNullRow)[0];\n const rawValues = rows.map(row => row && row[firstKey]);\n const values = rawValues.filter(rawValue => rawValue !== null);\n const sqlValuesAlias = sql.identifier(Symbol());\n const convertFieldBack = isPgClassLike\n ? sql.query`\\\nselect (str::${sqlTypeIdentifier}).*\nfrom unnest((${sql.value(values)})::text[]) str`\n : isPgRecord\n ? sql.query`\\\nselect ${sql.join(\n outputArgNames.map(\n (outputArgName, idx) =>\n sql.query`(${sqlValuesAlias}.output_value_list)[${sql.literal(\n idx + 1\n )}]::${\n outputArgTypes[idx].isFake\n ? sql.identifier(\"unknown\")\n : sql.identifier(\n outputArgTypes[idx].namespaceName,\n outputArgTypes[idx].name\n )\n } as ${sql.identifier(\n // According to https://www.postgresql.org/docs/10/static/sql-createfunction.html,\n // \"If you omit the name for an output argument, the system will choose a default column name.\"\n // In PG 9.x and 10, the column names appear to be assigned with a `column` prefix.\n outputArgName !== \"\" ? outputArgName : `column${idx + 1}`\n )}`\n ),\n \", \"\n )}\nfrom (values ${sql.join(\n values.map(value => sql.query`(${sql.value(value)}::text[])`),\n \", \"\n )}) as ${sqlValuesAlias}(output_value_list)`\n : sql.query`\\\nselect str::${sqlTypeIdentifier} as ${sqlResultSourceAlias}\nfrom unnest((${sql.value(values)})::text[]) str`;\n const { rows: filteredValuesResults } =\n values.length > 0\n ? await performQuery(\n pgClient,\n sql.query`with ${sqlResultSourceAlias} as (${convertFieldBack}) ${sqlResultQuery}`\n )\n : { rows: [] };\n const finalRows = rawValues.map(rawValue =>\n /*\n * We can't simply return 'null' here because this is expected to have\n * come from PG, and that would never return 'null' for a row - only\n * the fields within said row. Using `__isNull` here is a simple\n * workaround to this, that's caught by `pg2gql`.\n */\n rawValue === null ? { __isNull: true } : filteredValuesResults.shift()\n );\n return finalRows;\n }\n}\n"],"file":"viaTemporaryTable.js"}
1
+ {"version":3,"sources":["../../src/plugins/viaTemporaryTable.js"],"names":["viaTemporaryTable","pgClient","sqlTypeIdentifier","sqlMutationQuery","sqlResultSourceAlias","sqlResultQuery","isPgClassLike","pgRecordInfo","undefined","isPgRecord","outputArgTypes","outputArgNames","performQuery","sqlQuery","text","values","sql","compile","debugSql","enabled","query","rows","selectionField","join","map","outputArgName","idx","identifier","result","firstNonNullRow","find","row","firstKey","Object","keys","rawValues","filter","rawValue","sqlValuesAlias","Symbol","convertFieldBack","value","literal","isFake","namespaceName","name","filteredValuesResults","length","finalRows","__isNull","shift"],"mappings":";;;;;;;AAEA;;AAGA;;;;;;;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEe,eAAeA,iBAAf,CACbC,QADa,EAEbC,iBAFa,EAGbC,gBAHa,EAIbC,oBAJa,EAKbC,cALa,EAMbC,aAAsB,GAAG,IANZ,EAObC,YAIC,GAAGC,SAXS,EAYb;AACA,QAAMC,UAAU,GAAGF,YAAY,IAAI,IAAnC;AACA,QAAM;AAAEG,IAAAA,cAAF;AAA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tB,CAIL,OAAM7B,GAAG,CAACW,UAAJ,EACL;AACA;AACA;AACAF,IAAAA,aAAa,KAAK,EAAlB,GAAuBA,aAAvB,GAAwC,SAAQC,GAAG,GAAG,CAAE,EAJnD,CAKL,EAhBN,CADD,EAmBC,IAnBD,CAoBC;AACV,eAAeV,GAAG,CAACO,IAAJ,CACLR,MAAM,CAACS,GAAP,CAAWiB,KAAK,IAAIzB,GAAG,CAACI,KAAM,IAAGJ,GAAG,CAACyB,KAAJ,CAAUA,KAAV,CAAiB,WAAlD,CADK,EAEL,IAFK,CAGL,QAAOH,cAAe,qBA1Bd,GA2BVtB,GAAG,CAACI,KAAM;AAClB,cAAclB,iBAAkB,OAAME,oBAAqB;AAC3D,eAAeY,GAAG,CAACyB,KAAJ,CAAU1B,MAAV,CAAkB,gBAjC7B;AAkCA,UAAM;AAAEM,MAAAA,IAAI,EAAEyB;AAAR,QACJ/B,MAAM,CAACgC,MAAP,GAAgB,CAAhB,GACI,MAAMnC,YAAY,CAChBX,QADgB,EAEhBe,GAAG,CAACI,KAAM,QAAOhB,oBAAqB,QAAOoC,gBAAiB,KAAInC,cAAe,EAFjE,CADtB,GAKI;AAAEgB,MAAAA,IAAI,EAAE;AAAR,KANN;AAOA,UAAM2B,SAAS,GAAGb,SAAS,CAACX,GAAV,CAAca,QAAQ;AACtC;AACN;AACA;AACA;AACA;AACA;AACMA,IAAAA,QAAQ,KAAK,IAAb,GAAoB;AAAEY,MAAAA,QAAQ,EAAE;AAAZ,KAApB,GAAyCH,qBAAqB,CAACI,KAAtB,EAPzB,CAAlB;AASA,WAAOF,SAAP;AACD;AACF","sourcesContent":["// @flow\n\nimport * as sql from \"pg-sql2\";\nimport type { Client } from \"pg\";\nimport type { SQL, SQLQuery } from \"pg-sql2\";\nimport debugSql from \"./debugSql\";\n\n/*\n * Originally we tried this with a CTE, but:\n *\n * > The sub-statements in WITH are executed concurrently with each other and\n * > with the main query. Therefore, when using data-modifying statements in\n * > WITH, the order in which the specified updates actually happen is\n * > unpredictable. All the statements are executed with the same snapshot (see\n * > Chapter 13), so they cannot \"see\" one another's effects on the target\n * > tables. This alleviates the effects of the unpredictability of the actual\n * > order of row updates, and means that RETURNING data is the only way to\n * > communicate changes between different WITH sub-statements and the main\n * > query.\n *\n * -- https://www.postgresql.org/docs/9.6/static/queries-with.html\n *\n * This caused issues with computed columns that themselves went off and\n * performed selects - because the data within those selects used the old\n * snapshot and thus returned stale data.\n *\n * To solve this, we tried using temporary tables to ensure the mutation and\n * the select execute in different statments. This worked, but temporary tables\n * require elevated priviliges and thus don't work everywhere. We needed a more\n * generic solution.\n *\n * In the end we settled for sending the data we received from the mutations\n * straight back into the PostgreSQL server. It's a bit wasteful but it works.\n *\n * If you can come up with a better solution please open a pull request!\n */\n\nexport default async function viaTemporaryTable(\n pgClient: Client,\n sqlTypeIdentifier: ?SQL,\n sqlMutationQuery: SQL,\n sqlResultSourceAlias: SQL,\n sqlResultQuery: SQL,\n isPgClassLike: boolean = true,\n pgRecordInfo: ?{\n // eslint-disable-next-line flowtype/no-weak-types\n outputArgTypes: Array<any>,\n outputArgNames: Array<string>,\n } = undefined\n) {\n const isPgRecord = pgRecordInfo != null;\n const { outputArgTypes, outputArgNames } = pgRecordInfo || {};\n\n async function performQuery(pgClient: Client, sqlQuery: SQLQuery) {\n // TODO: look into rowMode = 'array'\n const { text, values } = sql.compile(sqlQuery);\n if (debugSql.enabled) debugSql(text);\n return pgClient.query(text, values);\n }\n\n if (!sqlTypeIdentifier) {\n // It returns void, just perform the query!\n const { rows } = await performQuery(\n pgClient,\n sql.query`with ${sqlResultSourceAlias} as (${sqlMutationQuery}) ${sqlResultQuery}`\n );\n return rows;\n } else {\n /*\n * In this code we're converting the rows to a string representation within\n * PostgreSQL itself, then we can send it back into PostgreSQL and have it\n * re-interpret the results cleanly (using it's own serializer/parser\n * combination) so we should be fairly confident that it will work\n * correctly every time assuming none of the PostgreSQL types are broken.\n *\n * If you have a way to improve this, I'd love to see a PR - but please\n * make sure that the integration tests pass with your solution first as\n * there are a log of potential pitfalls!\n */\n const selectionField = isPgClassLike\n ? /*\n * This `when foo is null then null` check might *seem* redundant, but it\n * is not - e.g. the compound type `(,,,,,,,)::my_type` and\n * `null::my_type` differ; however the former also returns true to `foo\n * is null`. We use this check to coalesce both into the canonical `null`\n * representation to make it easier to deal with below.\n */\n sql.query`(case when ${sqlResultSourceAlias} is null then null else ${sqlResultSourceAlias} end)`\n : isPgRecord\n ? sql.query`array[${sql.join(\n outputArgNames.map(\n (outputArgName, idx) =>\n sql.query`${sqlResultSourceAlias}.${sql.identifier(\n // According to https://www.postgresql.org/docs/10/static/sql-createfunction.html,\n // \"If you omit the name for an output argument, the system will choose a default column name.\"\n // In PG 9.x and 10, the column names appear to be assigned with a `column` prefix.\n outputArgName !== \"\" ? outputArgName : `column${idx + 1}`\n )}::text`\n ),\n \" ,\"\n )}]`\n : sql.query`(${sqlResultSourceAlias}.${sqlResultSourceAlias})::${sqlTypeIdentifier}`;\n const result = await performQuery(\n pgClient,\n sql.query`with ${sqlResultSourceAlias} as (${sqlMutationQuery}) select (${selectionField})::text from ${sqlResultSourceAlias}`\n );\n const { rows } = result;\n const firstNonNullRow = rows.find(row => row !== null);\n // TODO: we should be able to have `pg` not interpret the results as\n // objects and instead just return them as arrays - then we can just do\n // `row[0]`. PR welcome!\n const firstKey = firstNonNullRow && Object.keys(firstNonNullRow)[0];\n const rawValues = rows.map(row => row && row[firstKey]);\n const values = rawValues.filter(rawValue => rawValue !== null);\n const sqlValuesAlias = sql.identifier(Symbol());\n const convertFieldBack = isPgClassLike\n ? sql.query`\\\nselect (str::${sqlTypeIdentifier}).*\nfrom unnest((${sql.value(values)})::text[]) str`\n : isPgRecord\n ? sql.query`\\\nselect ${sql.join(\n outputArgNames.map(\n (outputArgName, idx) =>\n sql.query`(${sqlValuesAlias}.output_value_list)[${sql.literal(\n idx + 1\n )}]::${\n outputArgTypes[idx].isFake\n ? sql.identifier(\"unknown\")\n : sql.identifier(\n outputArgTypes[idx].namespaceName,\n outputArgTypes[idx].name\n )\n } as ${sql.identifier(\n // According to https://www.postgresql.org/docs/10/static/sql-createfunction.html,\n // \"If you omit the name for an output argument, the system will choose a default column name.\"\n // In PG 9.x and 10, the column names appear to be assigned with a `column` prefix.\n outputArgName !== \"\" ? outputArgName : `column${idx + 1}`\n )}`\n ),\n \", \"\n )}\nfrom (values ${sql.join(\n values.map(value => sql.query`(${sql.value(value)}::text[])`),\n \", \"\n )}) as ${sqlValuesAlias}(output_value_list)`\n : sql.query`\\\nselect str::${sqlTypeIdentifier} as ${sqlResultSourceAlias}\nfrom unnest((${sql.value(values)})::text[]) str`;\n const { rows: filteredValuesResults } =\n values.length > 0\n ? await performQuery(\n pgClient,\n sql.query`with ${sqlResultSourceAlias} as (${convertFieldBack}) ${sqlResultQuery}`\n )\n : { rows: [] };\n const finalRows = rawValues.map(rawValue =>\n /*\n * We can't simply return 'null' here because this is expected to have\n * come from PG, and that would never return 'null' for a row - only\n * the fields within said row. Using `__isNull` here is a simple\n * workaround to this, that's caught by `pg2gql`.\n */\n rawValue === null ? { __isNull: true } : filteredValuesResults.shift()\n );\n return finalRows;\n }\n}\n"],"file":"viaTemporaryTable.js"}