Browse Source

Workaround libpq not supporting string arrays

Toni Fadjukoff 6 years ago
parent
commit
ea85271750
1 changed files with 14 additions and 4 deletions
  1. 14 4
      db.go

+ 14 - 4
db.go View File

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