// Package models contains the types for schema 'public'.
package models

// Code generated by xo. DO NOT EDIT.

import (
	"database/sql"
)

// DatabaseWaitEvents represents a row from '[custom database_wait_events]'.
type DatabaseWaitEvents struct {
	Relname       Name           // relname
	Relkind       uint8          // relkind
	WaitEventType sql.NullString // wait_event_type
	WaitEvent     sql.NullString // wait_event
	Datname       Name           // datname
	Count         sql.NullInt64  // count
}

// GetDatabaseWaitEvents runs a custom query, returning results as DatabaseWaitEvents.
func GetDatabaseWaitEvents(db XODB) ([]*DatabaseWaitEvents, error) {
	var err error

	// sql query
	sqlstr := `SELECT c.relname, c.relkind, d.wait_event_type, d.wait_event, b.datname, count(*) ` +
		`FROM pg_locks a ` +
		`JOIN pg_stat_database b ON a.database=b.datid ` +
		`JOIN pg_class c ON a.relation=c.oid ` +
		`JOIN pg_stat_activity d ON a.pid = d.pid ` +
		`WHERE a.relation IS NOT NULL ` +
		`AND a.database IS NOT NULL ` +
		`AND (d.wait_event_type IS NOT NULL OR d.wait_event IS NOT NULL) ` +
		`GROUP BY 1,2,3,4,5`

	// run query
	XOLog(sqlstr)
	q, err := db.Query(sqlstr)
	if err != nil {
		return nil, err
	}
	defer q.Close()

	// load results
	res := []*DatabaseWaitEvents{}
	for q.Next() {
		dwe := DatabaseWaitEvents{}

		// scan
		err = q.Scan(&dwe.Relname, &dwe.Relkind, &dwe.WaitEventType, &dwe.WaitEvent, &dwe.Datname, &dwe.Count)
		if err != nil {
			return nil, err
		}

		res = append(res, &dwe)
	}

	return res, nil
}
