|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "time" |
| 5 | + |
| 6 | + "gorm.io/driver/sqlite" |
| 7 | + "gorm.io/gorm" |
| 8 | +) |
| 9 | + |
| 10 | +// User represents a user in the system |
| 11 | +type User struct { |
| 12 | + ID uint `gorm:"primaryKey"` |
| 13 | + Name string `gorm:"not null"` |
| 14 | + Email string `gorm:"unique;not null"` |
| 15 | + Age int `gorm:"check:age > 0"` |
| 16 | + CreatedAt time.Time |
| 17 | + UpdatedAt time.Time |
| 18 | +} |
| 19 | + |
| 20 | +// ConnectDB establishes a connection to the SQLite database |
| 21 | +func ConnectDB() (*gorm.DB, error) { |
| 22 | + db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{}) |
| 23 | + if err != nil { |
| 24 | + return nil, err |
| 25 | + } |
| 26 | + |
| 27 | + // Auto-migrate the User model |
| 28 | + err = db.AutoMigrate(&User{}) |
| 29 | + if err != nil { |
| 30 | + return nil, err |
| 31 | + } |
| 32 | + |
| 33 | + return db, nil |
| 34 | +} |
| 35 | + |
| 36 | +// CreateUser creates a new user in the database |
| 37 | +func CreateUser(db *gorm.DB, user *User) error { |
| 38 | + result := db.Create(user) |
| 39 | + return result.Error |
| 40 | +} |
| 41 | + |
| 42 | +// GetUserByID retrieves a user by their ID |
| 43 | +func GetUserByID(db *gorm.DB, id uint) (*User, error) { |
| 44 | + var user User |
| 45 | + result := db.First(&user, id) |
| 46 | + if result.Error != nil { |
| 47 | + return nil, result.Error |
| 48 | + } |
| 49 | + return &user, nil |
| 50 | +} |
| 51 | + |
| 52 | +// GetAllUsers retrieves all users from the database |
| 53 | +func GetAllUsers(db *gorm.DB) ([]User, error) { |
| 54 | + var users []User |
| 55 | + result := db.Find(&users) |
| 56 | + if result.Error != nil { |
| 57 | + return nil, result.Error |
| 58 | + } |
| 59 | + return users, nil |
| 60 | +} |
| 61 | + |
| 62 | +// UpdateUser updates an existing user's information |
| 63 | +func UpdateUser(db *gorm.DB, user *User) error { |
| 64 | + // First check if the user exists |
| 65 | + var existingUser User |
| 66 | + result := db.First(&existingUser, user.ID) |
| 67 | + if result.Error != nil { |
| 68 | + return result.Error |
| 69 | + } |
| 70 | + |
| 71 | + // Now update the user |
| 72 | + result = db.Save(user) |
| 73 | + return result.Error |
| 74 | +} |
| 75 | + |
| 76 | +// DeleteUser removes a user from the database |
| 77 | +func DeleteUser(db *gorm.DB, id uint) error { |
| 78 | + result := db.Delete(&User{}, id) |
| 79 | + if result.Error != nil { |
| 80 | + return result.Error |
| 81 | + } |
| 82 | + |
| 83 | + // Check if any rows were affected |
| 84 | + if result.RowsAffected == 0 { |
| 85 | + return gorm.ErrRecordNotFound |
| 86 | + } |
| 87 | + |
| 88 | + return nil |
| 89 | +} |
| 90 | + |
| 91 | + |
0 commit comments