github.com/k0marov/go-socnet@v0.0.0-20220715154813-90d07867c782/features/profiles/store/sql_db/sql_db.go (about) 1 package sql_db 2 3 import ( 4 "database/sql" 5 "fmt" 6 "github.com/jmoiron/sqlx" 7 "github.com/k0marov/go-socnet/core/abstract/table_name" 8 "github.com/k0marov/go-socnet/core/general/core_err" 9 "github.com/k0marov/go-socnet/core/general/core_values" 10 11 "github.com/k0marov/go-socnet/features/profiles/domain/models" 12 13 "github.com/k0marov/go-socnet/features/profiles/store" 14 ) 15 16 type SqlDB struct { 17 sql *sqlx.DB 18 TableName table_name.TableName 19 } 20 21 func NewSqlDB(sql *sqlx.DB) (*SqlDB, error) { 22 err := initSQL(sql) 23 if err != nil { 24 return nil, err 25 } 26 return &SqlDB{sql: sql, TableName: table_name.NewTableName("Profile")}, nil 27 } 28 29 func initSQL(sql *sqlx.DB) error { 30 _, err := sql.Exec(`CREATE TABLE IF NOT EXISTS Profile( 31 id INTEGER PRIMARY KEY, 32 username VARCHAR(255) NOT NULL, 33 about TEXT NOT NULL, 34 avatarPath VARCHAR(255) NOT NULL 35 );`) 36 if err != nil { 37 return core_err.Rethrow("creating Profile table", err) 38 } 39 return nil 40 } 41 42 func (db *SqlDB) CreateProfile(newProfile models.ProfileModel) error { 43 _, err := db.sql.Exec(`INSERT INTO Profile(id, username, about, avatarPath) values( 44 ?, ?, ?, ? 45 )`, newProfile.Id, newProfile.Username, newProfile.About, newProfile.AvatarPath) 46 if err != nil { 47 return fmt.Errorf("while inserting into Profile table: %v", err) 48 } 49 return nil 50 } 51 52 func (db *SqlDB) GetProfile(profileId core_values.UserId) (models.ProfileModel, error) { 53 var profile models.ProfileModel 54 err := db.sql.Get(&profile, ` 55 SELECT id, username, about, avatarPath 56 FROM Profile 57 WHERE id = ?`, 58 profileId, 59 ) 60 if err == sql.ErrNoRows { 61 return models.ProfileModel{}, core_err.ErrNotFound 62 } 63 if err != nil { 64 return models.ProfileModel{}, core_err.Rethrow("getting a profile from profile table", err) 65 } 66 67 return profile, nil 68 } 69 70 func (db *SqlDB) UpdateProfile(userId core_values.UserId, upd store.DBUpdateData) error { 71 _, err := db.sql.Exec(` 72 UPDATE Profile SET 73 avatarPath = CASE WHEN ?1 = "" THEN avatarPath ELSE ?1 END, 74 about = CASE WHEN ?2 = "" THEN about ELSE ?2 END 75 WHERE id = ?`, upd.AvatarPath, upd.About, userId) 76 if err != nil { 77 return core_err.Rethrow("updating avatarPath in db", err) 78 } 79 return nil 80 }