@@ -134,6 +134,71 @@ func (d DB) GetConfigs(since configs.ID) (map[string]configs.View, error) {
134134 })
135135}
136136
137+ // GetRulesConfig gets the latest alertmanager config for a user.
138+ func (d DB ) GetRulesConfig (userID string ) (configs.VersionedRulesConfig , error ) {
139+ current , err := d .GetConfig (userID )
140+ if err != nil {
141+ return configs.VersionedRulesConfig {}, err
142+ }
143+ return current .GetVersionedRulesConfig (), nil
144+ }
145+
146+ // SetRulesConfig sets the current alertmanager config for a user.
147+ func (d DB ) SetRulesConfig (userID string , config configs.RulesConfig ) error {
148+ current , err := d .GetConfig (userID )
149+ if err != nil {
150+ return err
151+ }
152+ new := configs.Config {
153+ AlertmanagerConfig : current .Config .AlertmanagerConfig ,
154+ RulesFiles : config ,
155+ }
156+ return d .SetConfig (userID , new )
157+ }
158+
159+ func (d DB ) findRulesConfigs (filter squirrel.Sqlizer ) (map [string ]configs.VersionedRulesConfig , error ) {
160+ rows , err := d .Select ("id" , "owner_id" , "config ->> 'rules_files'" ).
161+ Options ("DISTINCT ON (owner_id)" ).
162+ From ("configs" ).
163+ Where (filter ).
164+ Where ("config ->> 'rules_files' <> '{}'" ).
165+ OrderBy ("owner_id, id DESC" ).
166+ Query ()
167+ if err != nil {
168+ return nil , err
169+ }
170+ defer rows .Close ()
171+ cfgs := map [string ]configs.VersionedRulesConfig {}
172+ for rows .Next () {
173+ var cfg configs.VersionedRulesConfig
174+ var userID string
175+ var cfgBytes []byte
176+ err = rows .Scan (& cfg .ID , & userID , & cfgBytes )
177+ if err != nil {
178+ return nil , err
179+ }
180+ err = json .Unmarshal (cfgBytes , & cfg .Config )
181+ if err != nil {
182+ return nil , err
183+ }
184+ cfgs [userID ] = cfg
185+ }
186+ return cfgs , nil
187+ }
188+
189+ // GetAllRulesConfigs gets all alertmanager configs for all users.
190+ func (d DB ) GetAllRulesConfigs () (map [string ]configs.VersionedRulesConfig , error ) {
191+ return d .findRulesConfigs (activeConfig )
192+ }
193+
194+ // GetRulesConfigs gets all the alertmanager configs that have changed since a given config.
195+ func (d DB ) GetRulesConfigs (since configs.ID ) (map [string ]configs.VersionedRulesConfig , error ) {
196+ return d .findRulesConfigs (squirrel.And {
197+ activeConfig ,
198+ squirrel.Gt {"id" : since },
199+ })
200+ }
201+
137202// Transaction runs the given function in a postgres transaction. If fn returns
138203// an error the txn will be rolled back.
139204func (d DB ) Transaction (f func (DB ) error ) error {
0 commit comments