package postgres import ( "git.tek.govt.hu/dowerx/chat/server/model" "git.tek.govt.hu/dowerx/chat/server/util" "github.com/jmoiron/sqlx" ) type ChannelDAOPG struct { pgDAO } // Create a new channel func (d ChannelDAOPG) Create(channel model.Channel) *util.ChatError { _, err := d.db.NamedExec(`call add_channel(:name, :description)`, &channel) return util.MakeError(err, util.DATABASE_QUERY_FAULT) } // Read returns a channel by ID func (d ChannelDAOPG) Read(channel model.Channel) (model.Channel, *util.ChatError) { var rows *sqlx.Rows var err error rows, err = d.db.NamedQuery(`select * from "channel" where "id" = :id`, &channel) if err != nil { return channel, util.MakeError(err, util.DATABASE_QUERY_FAULT) } defer rows.Close() if !rows.Next() { return channel, &util.ChatError{Message: "", Code: util.NOT_FOUND} } err = rows.StructScan(&channel) return channel, util.MakeError(err, util.DATABASE_QUERY_FAULT) } // List all channels func (d ChannelDAOPG) List() ([]model.Channel, *util.ChatError) { rows, err := d.db.Queryx(`select * from "channel" order by "name"`) if err != nil { return nil, util.MakeError(err, util.DATABASE_QUERY_FAULT) } defer rows.Close() channels := make([]model.Channel, 0) for rows.Next() { channel := model.Channel{} err = rows.StructScan(&channel) if err != nil { break } channels = append(channels, channel) } return channels, util.MakeError(err, util.DATABASE_QUERY_FAULT) } // Update sets all the fields of the Channel with the given ID func (d ChannelDAOPG) Update(channel model.Channel) *util.ChatError { _, err := d.db.NamedExec(`update "channel" set "name" = :name, "description" = :description where "id" = :id`, &channel) return util.MakeError(err, util.DATABASE_QUERY_FAULT) } // Delete removes a channel by ID func (d ChannelDAOPG) Delete(channel model.Channel) *util.ChatError { var err error _, err = d.db.NamedExec(`delete from "channel" where "id" = :id`, &channel) return util.MakeError(err, util.DATABASE_QUERY_FAULT) } func (d ChannelDAOPG) Ready() bool { return d.db != nil } func MakeChannelDAO() (ChannelDAOPG, *util.ChatError) { dao := ChannelDAOPG{} conn, err := getDatabase() if err != nil { return dao, err } dao.db = conn return dao, nil }