pg#PoolClient TypeScript Examples

The following examples show how to use pg#PoolClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: db.ts    From posthog-foss with MIT License 6 votes vote down vote up
// Postgres

    public postgresQuery<R extends QueryResultRow = any, I extends any[] = any[]>(
        queryString: string,
        values: I | undefined,
        tag: string,
        client?: PoolClient
    ): Promise<QueryResult<R>> {
        return instrumentQuery(this.statsd, 'query.postgres', tag, async () => {
            let fullQuery = ''
            try {
                fullQuery = getFinalPostgresQuery(queryString, values as any[])
            } catch {}
            const timeout = timeoutGuard('Postgres slow query warning after 30 sec', {
                queryString,
                values,
                fullQuery,
            })

            // Annotate query string to give context when looking at DB logs
            queryString = `/* plugin-server:${tag} */ ${queryString}`
            try {
                if (client) {
                    return await client.query(queryString, values)
                } else {
                    return await this.postgres.query(queryString, values)
                }
            } finally {
                clearTimeout(timeout)
            }
        })
    }
Example #2
Source File: index.ts    From Hybooru with MIT License 6 votes vote down vote up
async function importOptions(hydrus: Database, postgres: PoolClient) {
  printProgress(false, "Importing options... ");
  
  let { options } = hydrus.prepare('SELECT options FROM options').get();
  (global as any).YAML_SILENCE_WARNINGS = true;
  options = YAML.parse(options);
  (global as any).YAML_SILENCE_WARNINGS = false;
  
  const namespaceColours: Record<string, [number, number, number]> = options.namespace_colours;
  
  const namespaces = Object.entries(namespaceColours)
                           .map(([name, color], id) => ({
                             id,
                             name,
                             color: "#" + (color[0] * 256 * 256 + color[1] * 256 + color[2]).toString(16).padStart(6, "0"),
                           }));
  
  await postgres.query(SQL`
    INSERT INTO namespaces(id, name, color)
    SELECT id, name, color
    FROM json_to_recordset(${JSON.stringify(namespaces)})
      AS x(
        id INTEGER,
        name TEXT,
        color TEXT
      )
  `);
  
  printProgress(true, "Importing options... ");
  
  return options;
}
Example #3
Source File: container_user_invite_mapper.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
public async Create(input: ContainerUserInvite, transaction?: PoolClient): Promise<Result<ContainerUserInvite>> {
        const r = await super.run(this.createStatement(input), {
            transaction,
            resultClass,
        });
        if (r.isError) return Promise.resolve(Result.Pass(r));

        return Promise.resolve(Result.Success(r.value[0]));
    }
Example #4
Source File: db.ts    From posthog-foss with MIT License 5 votes vote down vote up
public async updatePersonDeprecated(
        person: Person,
        update: Partial<Person>,
        client: PoolClient
    ): Promise<ProducerRecord[]>
Example #5
Source File: migrate.ts    From graphile-scheduler with MIT License 5 votes vote down vote up
export async function migrate(options: RunnerOptions, client: PoolClient) {
  const { escapedWorkerSchema, escapedSchedulerSchema } = processOptions(
    options
  );

  let latestMigration: number | null = null;
  try {
    const {
      rows: [row],
    } = await client.query(
      `select id from ${escapedSchedulerSchema}.migrations order by id desc limit 1;`
    );
    if (row) {
      latestMigration = row.id;
    }
  } catch (e) {
    if (e.code === "42P01") {
      await client.query(`
        create extension if not exists pgcrypto with schema public;
        create schema if not exists ${escapedSchedulerSchema};
        create table ${escapedSchedulerSchema}.migrations(
          id int primary key,
          ts timestamptz default now() not null
        );
      `);
    } else {
      throw e;
    }
  }
  const migrationFiles = (await readdir(`${__dirname}/../sql`))
    .filter(f => f.match(/^[0-9]{6}\.sql$/))
    .sort();

  for (const migrationFile of migrationFiles) {
    const migrationNumber = parseInt(migrationFile.substr(0, 6), 10);
    if (latestMigration == null || migrationNumber > latestMigration) {
      const rawText = await readFile(
        `${__dirname}/../sql/${migrationFile}`,
        "utf8"
      );
      const text = rawText
        .replace(/:GRAPHILE_WORKER_SCHEMA\b/g, escapedWorkerSchema)
        .replace(/:GRAPHILE_SCHEDULER_SCHEMA\b/g, escapedSchedulerSchema);

      await client.query("begin");
      try {
        await client.query({
          text,
        });
        await client.query({
          text: `insert into ${escapedSchedulerSchema}.migrations (id) values ($1)`,
          values: [migrationNumber],
        });
        await client.query("commit");
      } catch (e) {
        await client.query("rollback");
        throw e;
      }
    }
  }
}