/*

Package dbtrace allows a service owner to emit trace events relating to SQL
database access.

*/
package dbtrace

import (
	"unicode/utf8"

	"code.justin.tv/common/chitin/internal/trace"
	"code.justin.tv/release/trace/common"
	"code.justin.tv/release/trace/events"
	"code.justin.tv/release/trace/pglex"
	"golang.org/x/net/context"
)

// BasicRequestHeadPrepared emits a trace event to announce that a query is
// about to be sent to the database.
func BasicRequestHeadPrepared(ctx context.Context, peer, name, user, query string) {
	norm := truncate(pglex.Normalize(query), 1024)

	ev := &events.Event{
		Kind: common.Kind_REQUEST_HEAD_PREPARED,
		Extra: &events.Extra{
			Peer: peer,
			Sql: &events.ExtraSQL{
				StrippedQuery: norm,
				DatabaseName:  name,
				DatabaseUser:  user,
			},
		},
	}

	trace.SendEvent(ctx, ev)
}

func truncate(in string, limit int) string {
	if len(in) <= limit {
		return in
	}
	for i := limit; i >= 0; i-- {
		if utf8.RuneStart(in[i]) {
			return in[:i]
		}
	}
	return ""
}

// BasicResponseHeadReceived emits a trace event to announce that a query has
// been processed by the database, and that the results (if any) are ready for
// consumption.
func BasicResponseHeadReceived(ctx context.Context) {
	// TODO: include some indication of query success when possible

	trace.SendEvent(ctx, &events.Event{
		Kind:  common.Kind_RESPONSE_HEAD_RECEIVED,
		Extra: nil,
	})
}
