Bladeren bron

Workaround libpq not supporting string arrays

Toni Fadjukoff 6 jaren geleden
bovenliggende
commit
ea85271750
1 gewijzigde bestanden met toevoegingen van 14 en 4 verwijderingen
  1. 14 4
      db.go

+ 14 - 4
db.go Bestand weergeven

@@ -2,6 +2,7 @@ package main
2 2
 
3 3
 import (
4 4
 	"database/sql"
5
+	"encoding/json"
5 6
 	"errors"
6 7
 	_ "github.com/lib/pq"
7 8
 	"log"
@@ -185,12 +186,17 @@ func (db *DB) FindAllPanels() ([]string, error) {
185 186
 
186 187
 func (db *DB) FindPlaylistBySection(sectionName string) ([]string, error) {
187 188
 	query := `
188
-	SELECT pl.tracks FROM public.round_playlist pl 
189
+	SELECT array_to_json(pl.tracks) FROM public.round_playlist pl
189 190
 	JOIN public.round r ON pl.round_id = r.id
190 191
 	WHERE r.section = $1`
191 192
 	row := db.database.QueryRow(query, sectionName)
193
+	var tracksJson []byte
192 194
 	var tracks []string
193
-	err := row.Scan(&tracks)
195
+	err := row.Scan(&tracksJson)
196
+	if err != nil {
197
+		return nil, err
198
+	}
199
+	err = json.Unmarshal(tracksJson, tracks)
194 200
 	if err != nil {
195 201
 		return nil, err
196 202
 	}
@@ -198,13 +204,17 @@ func (db *DB) FindPlaylistBySection(sectionName string) ([]string, error) {
198 204
 }
199 205
 
200 206
 func (db *DB) UpdatePlaylistBySection(sectionName string, tracks []string) (bool, error) {
207
+	tracksJson, err := json.Marshal(tracks)
208
+	if err != nil {
209
+		return false, err
210
+	}
201 211
 	query := `
202 212
 	INSERT INTO public.round_playlist pl
203
-	SELECT r.id, $2
213
+	SELECT r.id, json_to_array($2)
204 214
 	FROM public.round r 
205 215
 	WHERE r.section = $1
206 216
 	ON CONFLICT (pl.round_id) DO UPDATE SET tracks = EXCLUDED.tracks`
207
-	res, err := db.database.Exec(query, sectionName, tracks)
217
+	res, err := db.database.Exec(query, sectionName, tracksJson)
208 218
 
209 219
 	if err != nil {
210 220
 		return false, err