eintopf.info@v0.13.16/service/user/store_sql.go (about) 1 // Copyright (C) 2022 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 user 17 18 import ( 19 "context" 20 21 "github.com/jmoiron/sqlx" 22 23 "eintopf.info/internal/crud" 24 "eintopf.info/service/dbmigration" 25 ) 26 27 // NewSqlStore returns a new sql db user store. 28 func NewSqlStore(db *sqlx.DB, migrationService dbmigration.Service) (*SqlStore, error) { 29 store := &SqlStore{ 30 db, 31 crud.NewSqlStore(db, table, UserFromNewUser, nil), 32 } 33 err := store.runMigrations(migrationService) 34 if err != nil { 35 return nil, err 36 } 37 return store, nil 38 } 39 40 type SqlStore struct { 41 db *sqlx.DB 42 43 *crud.SqlStore[NewUser, User, FindFilters] 44 } 45 46 func (s *SqlStore) runMigrations(migrationService dbmigration.Service) error { 47 return migrationService.RunMigrations(context.Background(), []dbmigration.Migration{ 48 dbmigration.NewMigration("createUserTable", s.createUserTable, nil), 49 }) 50 } 51 52 func (s *SqlStore) createUserTable(ctx context.Context) error { 53 _, err := s.db.ExecContext(ctx, ` 54 CREATE TABLE IF NOT EXISTS users ( 55 id varchar(32) NOT NULL PRIMARY KEY UNIQUE, 56 deactivated boolean DEFAULT FALSE, 57 created_at timestamp, 58 email VARCHAR(128), 59 nickname VARCHAR(128), 60 password VARCHAR(128), 61 role VARCHAR(32) 62 ); 63 `) 64 return err 65 } 66 67 var table = crud.SqlTable[FindFilters]{ 68 Table: "users", 69 IDField: "id", 70 Fields: []string{"id", "deactivated", "created_at", "email", "nickname", "password", "role"}, 71 SortableFields: []string{"id", "deactivated", "created_at", "email", "nickname", "role"}, 72 }