views.js 773 Bytes
import pointsBalanceView from './db/tables/points_balance_view.cjs'

/**
 * Recreate billing-owned derived views.
 *
 * This is explicit schema maintenance for dev/test sync scripts, not runtime app startup.
 * @param {import('knex').Knex} db
 */
export async function recreateBillingViews(db) {
  await recreateView(db, pointsBalanceView)
}

/**
 * @param {import('knex').Knex} db
 * @param {{ viewName: string, createViewSql: () => string }} view
 */
async function recreateView(db, view) {
  await db.raw(`DROP VIEW IF EXISTS ${quoteIdent(view.viewName)}`)
  await db.raw(view.createViewSql())
}

/**
 * @param {string} name
 */
function quoteIdent(name) {
  if (!/^[A-Za-z0-9_]+$/.test(name)) throw new Error(`invalid SQL identifier: ${name}`)
  return `\`${name}\``
}