eintopf.info@v0.13.16/service/action/store.go (about) 1 // Copyright (C) 2024 The Eintopf authors 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <https://www.gnu.org/licenses/>. 15 16 package action 17 18 import ( 19 "context" 20 21 "eintopf.info/internal/crud" 22 "eintopf.info/service/dbmigration" 23 "github.com/jmoiron/sqlx" 24 ) 25 26 func actionFromAction(action *Action, id string) *Action { return action } 27 func newID(action *Action) string { return action.Name } 28 29 // NewMemoryStore returns a new in memory store. 30 func NewMemoryStore() *crud.MemoryStore[Action, Action, Filters] { 31 return crud.NewMemoryStore[Action, Action, Filters](actionFromAction, newID) 32 } 33 34 // NewSqlStore returns a new sql store for notifications. 35 func NewSqlStore(db *sqlx.DB, migrationService dbmigration.Service) (*SqlStore, error) { 36 store := &SqlStore{ 37 db, 38 migrationService, 39 crud.NewSqlStore(db, table, actionFromAction, newID), 40 } 41 if err := store.runMigrations(context.Background()); err != nil { 42 return nil, err 43 } 44 return store, nil 45 } 46 47 type SqlStore struct { 48 db *sqlx.DB 49 migrationService dbmigration.Service 50 51 *crud.SqlStore[Action, Action, Filters] 52 } 53 54 func (s *SqlStore) runMigrations(ctx context.Context) error { 55 return s.migrationService.RunMigrations(ctx, []dbmigration.Migration{ 56 dbmigration.NewMigration("createActionTable", s.createActionTable, nil), 57 }) 58 } 59 60 func (s *SqlStore) createActionTable(ctx context.Context) error { 61 _, err := s.db.ExecContext(ctx, ` 62 CREATE TABLE IF NOT EXISTS actions ( 63 name VARCHAR(64) NOT NULL PRIMARY KEY UNIQUE, 64 calls INT NOT NULL DEFAULT 0, 65 last_call DATETIME, 66 last_called_by VARCHAR(64), 67 error TEXT 68 ); 69 `) 70 return err 71 } 72 73 var table = crud.SqlTable[Filters]{ 74 Table: "actions", 75 IDField: "name", 76 Fields: []string{"name", "calls", "last_call", "last_called_by", "error"}, 77 SortableFields: []string{"name", "calls", "last_call", "error"}, 78 }