Skip to content

Instantly share code, notes, and snippets.

@moio
Created July 28, 2025 09:51
Show Gist options
  • Select an option

  • Save moio/10e19b4496ecf71707d1b6d52e6db292 to your computer and use it in GitHub Desktop.

Select an option

Save moio/10e19b4496ecf71707d1b6d52e6db292 to your computer and use it in GitHub Desktop.
GORM example: use SQL generation without the rest of the ORM
package main
import (
"fmt"
"log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func main() {
// 1. Initialize GORM in DryRun mode.
// We use an in-memory sqlite connection just to specify the SQL dialect.
// It will not actually be used
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
DryRun: true,
})
if err != nil {
log.Fatalf("failed to initialize gorm in dry run mode: %v", err)
}
// 2. Use .Table("users") to specify the table name directly.
stmt := db.Table("users").
Where("user_name = ?", "John").
Where("active = ?", true).
Order("created_at desc").
Limit(10).
Find(&map[string]interface{}{}).Statement // A destination is still required for Find()
// 3. Retrieve the generated SQL and its arguments
sqlString := stmt.SQL.String()
sqlVars := stmt.Vars
// 4. Print the results
fmt.Println("📄 Generated SQL:")
fmt.Println(sqlString)
fmt.Println("\n❓ Arguments:")
fmt.Println(sqlVars)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment