export function buildLatestSnapshotViewQuery()

in firestore-bigquery-export/firestore-bigquery-change-tracker/src/bigquery/snapshot.ts [38:87]


export function buildLatestSnapshotViewQuery(
  datasetId: string,
  tableName: string,
  timestampColumnName: string,
  groupByColumns: string[]
): string {
  if (datasetId === "" || tableName === "" || timestampColumnName === "") {
    throw Error(`Missing some query parameters!`);
  }
  for (let columnName in groupByColumns) {
    if (columnName === "") {
      throw Error(`Found empty group by column!`);
    }
  }
  const query = sqlFormatter.format(
    ` -- Retrieves the latest document change events for all live documents.
    --   timestamp: The Firestore timestamp at which the event took place.
    --   operation: One of INSERT, UPDATE, DELETE, IMPORT.
    --   event_id: The id of the event that triggered the cloud function mirrored the event.
    --   data: A raw JSON payload of the current state of the document.
    --   document_id: The document id as defined in the Firestore database
    SELECT
    document_name,
    document_id${groupByColumns.length > 0 ? `,` : ``}
      ${groupByColumns.join(",")}
    FROM (
      SELECT
        document_name,
        document_id,
        ${groupByColumns
          .map(
            (columnName) =>
              `FIRST_VALUE(${columnName})
            OVER(PARTITION BY document_name ORDER BY ${timestampColumnName} DESC)
            AS ${columnName}`
          )
          .join(",")}${groupByColumns.length > 0 ? `,` : ``}
        FIRST_VALUE(operation)
          OVER(PARTITION BY document_name ORDER BY ${timestampColumnName} DESC) = "DELETE"
          AS is_deleted
      FROM \`${process.env.PROJECT_ID}.${datasetId}.${tableName}\`
      ORDER BY document_name, ${timestampColumnName} DESC
    )
    WHERE NOT is_deleted
    GROUP BY document_name, document_id${
      groupByColumns.length > 0 ? `, ` : ``
    }${groupByColumns.join(",")}`
  );
  return query;
}