import { psql } from "./names";
import type { Sql } from "./quote";
import { runShell } from "./runShell";

/**
 * Runs a psql with the provided SQL query (or queries) passed as stdin. Returns
 * an array of rows (rows are newline-separated in the output), each row is an
 * array of values.
 */
export async function runSql(
  dsn: string,
  query: Sql,
  comment?: string,
): Promise<string[][]> {
  const out = await runShell(`${psql(dsn)} -zq`, query.toString(), comment);
  return out
    .split("\n")
    .filter((line) => line !== "")
    .map((line) => line.split("\x00" /* -z */));
}

runSql.column = async (
  dsn: string,
  query: Sql,
  comment?: string,
): Promise<string[]> => {
  const lines = await runSql(dsn, query, comment);
  return lines.map((line) => line[0] ?? "");
};

runSql.row = async (
  dsn: string,
  query: Sql,
  comment?: string,
): Promise<string[]> => {
  const lines = await runSql(dsn, query, comment);
  return lines[0] ?? [];
};

runSql.one = async (
  dsn: string,
  query: Sql,
  comment?: string,
): Promise<string> => {
  const lines = await runSql.column(dsn, query, comment);
  return lines[0] ?? "";
};
