// Delete the common puzzles func deleteSamples(tx *pgx.Tx) error { // first remove the puzzle summaries from the database _, err := tx.Exec( "DELETE from sessionEntries where sessionId = $1", SampleSessionName) if err != nil { return fmt.Errorf("Database error deleting sample session: %v", err) } // then remove the session _, err = tx.Exec( "DELETE from sessions where sessionId = $1", SampleSessionName) if err != nil { return fmt.Errorf("Database error deleting sample session: %v", err) } // then remove the puzzles themselves for i, hash := range sampleHashes { _, err := tx.Exec( "DELETE from puzzles where puzzleId = $1", hash) if err != nil { return fmt.Errorf("Database error deleting sample puzzle %d: %v", i, err) } } return nil }
// Create and insert the sample puzzles and sample session func insertSamples(tx *pgx.Tx) error { // idempotency: if the sample session already exists, we are done var count int64 row := tx.QueryRow("SELECT COUNT(*) FROM sessions "+ "WHERE sessionId = $1", SampleSessionName) if err := row.Scan(&count); err != nil { return fmt.Errorf("Database error looking for session %q: %v", SampleSessionName, err) } if count > 0 { return nil } // get the timestamp of this load now := time.Now() // first save the puzzles for i, sum := range samplePuzzles { values := make([]int32, len(sum.Values)) for i, v := range sum.Values { values[i] = int32(v) // use 4-byte ints in database } _, err := tx.Exec( "INSERT INTO puzzles (puzzleId, geometry, sideLength, valueList, created) "+ "VALUES ($1, $2, $3, $4, $5)", sampleHashes[i], sum.Geometry, int32(sum.SideLength), values, now) if err != nil { return fmt.Errorf("Database error saving sample puzzle %d: %v", i, err) } } // next save the session _, err := tx.Exec( "INSERT INTO sessions (sessionId, created, updated, active) "+ "VALUES ($1, $2, $3, $4)", SampleSessionName, now, now, sampleHashes[0]) if err != nil { return fmt.Errorf("Database error saving sample session: %v", err) } // next save the session entries for i := range samplePuzzles { _, err := tx.Exec( "INSERT INTO sessionEntries (sessionId, puzzleId, puzzleName, lastView) "+ "VALUES ($1, $2, $3, $4)", SampleSessionName, sampleHashes[i], sampleNames[i], now) if err != nil { return fmt.Errorf("Database error saving sample session puzzle %d: %v", i, err) } } return nil }