CAUTION, THIS IS JUST PROOF OF CONCEPT THAT I QUICKLY MADE WITH HELP OF GITHUB COPILOT, NOT MEANT FOR PRODUCTION, IT IS NOT THROUGHLY TESTED YET!
A lightweight ORM for Go inspired by Dapper, designed to work with PostgreSQL.
- Built on top of Go's standard
database/sqlpackage - Simple API for mapping SQL query results to Go structs
- Support for parameterized queries
- Auto-mapping of column names to struct fields
- Handles common data types including strings, integers, floats, booleans, and time.Time
go get github.com/noonlord/go-micro-ormimport (
"github.com/noonlord/go-micro-orm/orm"
_ "github.com/lib/pq"
)
func main() { // Connect to PostgreSQL
db, err := orm.Open("postgres", "postgres://username:password@localhost/dbname?sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
}// Define a struct that matches your table schema
type User struct {
Id int64
Username string
Email string
Created time.Time
}
// Query multiple rows
var users []User
err := db.Query(&users, "SELECT id, username, email, created FROM users WHERE active = $1", true)
if err != nil {
log.Fatal(err)
}
// Use the results
for _, user := range users {
fmt.Printf("User: %s (%s)\n", user.Username, user.Email)
}// Query a single row
var user User
err := db.QueryRow(&user, "SELECT id, username, email, created FROM users WHERE id = $1", 1)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found user: %s\n", user.Username)// Execute a command
rowsAffected, err := db.Execute("UPDATE users SET active = $1 WHERE last_login < $2",
false, time.Now().AddDate(0, -3, 0))
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deactivated %d users\n", rowsAffected)- Column names are automatically mapped to struct field names with the first letter capitalized
- The ORM uses reflection to handle the mapping between database columns and struct fields
- Null values from the database are handled properly and won't cause errors
MIT