66 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			66 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
package main
 | 
						|
 | 
						|
import (
 | 
						|
	"fmt"
 | 
						|
	"log"
 | 
						|
)
 | 
						|
 | 
						|
type AssociationService struct {
 | 
						|
	db *DB
 | 
						|
}
 | 
						|
type AssociationServiceQuery struct {
 | 
						|
	LHSID  *int64 `db:"lhs"`
 | 
						|
	RHSID  *int64 `db:"rhs"`
 | 
						|
	NoteID *int64 `db:"note"`
 | 
						|
	ID     *int64 `db:"id"`
 | 
						|
}
 | 
						|
 | 
						|
func (as *AssociationService) Query(query AssociationServiceQuery) ([]Association, error) {
 | 
						|
	res := []Association{}
 | 
						|
	sqlQuery := "SELECT id, lhs, rhs, note FROM association"
 | 
						|
	whereQuery := BuildWhereQuery(query)
 | 
						|
	if whereQuery != "" {
 | 
						|
		sqlQuery += " " + whereQuery
 | 
						|
	}
 | 
						|
 | 
						|
	rows, err := as.db.readConn.Query(sqlQuery)
 | 
						|
	if err != nil {
 | 
						|
		return res, fmt.Errorf("failed getting associations for query %q: %v", sqlQuery, err)
 | 
						|
	}
 | 
						|
	defer rows.Close()
 | 
						|
 | 
						|
	for rows.Next() {
 | 
						|
		association := Association{}
 | 
						|
		err := rows.Scan(&association.ID, &association.LHS.ID, &association.RHS.ID, &association.Note)
 | 
						|
		if err != nil {
 | 
						|
			return res, fmt.Errorf("failed scanning association: %v", err)
 | 
						|
		}
 | 
						|
		res = append(res, association)
 | 
						|
	}
 | 
						|
 | 
						|
	return res, nil
 | 
						|
}
 | 
						|
 | 
						|
func (as *AssociationService) Create(lhs Player, rhs Player, note string) (Association, error) {
 | 
						|
	log.Printf("Creating association between %d and %d with note %s", lhs.ID, rhs.ID, note)
 | 
						|
	association := Association{}
 | 
						|
	res, err := as.db.writeConn.Exec("insert into association (lhs, rhs, note) values (?, ?, ?)", lhs.ID, rhs.ID, note)
 | 
						|
	if err != nil {
 | 
						|
		return association, fmt.Errorf("failed to insert association: %v", err)
 | 
						|
	}
 | 
						|
 | 
						|
	id, err := res.LastInsertId()
 | 
						|
	if err != nil {
 | 
						|
		return association, fmt.Errorf("failed to get last insert id: %v", err)
 | 
						|
	}
 | 
						|
	log.Printf("Created association between %d and %d with note %s with id %d", lhs.ID, rhs.ID, note, id)
 | 
						|
 | 
						|
	qres, err := as.Query(AssociationServiceQuery{ID: &id})
 | 
						|
	if err != nil {
 | 
						|
		return association, fmt.Errorf("failed getting association for id %d: %v", id, err)
 | 
						|
	}
 | 
						|
	if len(qres) > 1 {
 | 
						|
		return association, fmt.Errorf("more than one association found for id %d", id)
 | 
						|
	}
 | 
						|
	return qres[0], nil
 | 
						|
} |