import { assert } from "../../../shared/src/asserts.js";
import { mapEntries } from "../../../shared/src/objects.js";
import { JSON, JSONB } from "../types/pg-types.js";
const INT4_ARRAY_TYPE = 1007;
const JSON_TYPE = String(JSON);
const JSONB_TYPE = String(JSONB);
async function getTypeParsers(db, { returnJsonAsString } = {}) {
  if (!db.options.parsers[INT4_ARRAY_TYPE]) {
    assert(db.options.fetch_types, `Supplied db must fetch_types`);
    await db`SELECT 1`.simple();
    assert(
      db.options.parsers[INT4_ARRAY_TYPE],
      `array types not fetched ${Object.keys(db.options.parsers)}`
    );
  }
  const parsers = mapEntries(db.options.parsers, (type, parse) => {
    if ((type === JSON_TYPE || type === JSONB_TYPE) && returnJsonAsString) {
      return [type, (x) => x];
    }
    const isArrayType = parse.array;
    return [
      type,
      isArrayType ? (val) => parse(val.substring(1)) : parse
    ];
  });
  return {
    // A type OID for which a parser is not explicitly defined
    // is parsed as a String.
    // https://github.com/porsager/postgres/blob/b0d8c8f363e006a74472d76f859da60c52a80368/src/connection.js#L494
    //
    // This is also consistent with the `pg` library, in which the absence of a
    // TypeParser defaults to "noParse":
    // https://github.com/brianc/node-pg-types/blob/5b26b826466cff4a9092b8c9e31960fe293ef3d9/index.js#L15
    getTypeParser: (typeOID) => parsers[typeOID] ?? String
  };
}
export {
  getTypeParsers
};
//# sourceMappingURL=pg-type-parser.js.map
