Getting Started
Quick Start

Quick Start

This guide will get you running with go-lightning in 5 minutes.

1. Define Your Model

Create a struct that maps to your database table:

type User struct {
    Id        int
    FirstName string
    LastName  string
    Email     string
}

Field names are automatically converted to snake_case column names:

  • Idid
  • FirstNamefirst_name
  • LastNamelast_name

2. Create Your Table

Create the corresponding table in your database:

-- PostgreSQL
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL
);
-- MySQL
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL
);

3. Register the Model

At application startup, register your model with the appropriate driver:

import "github.com/tracewayapp/go-lightning/lit"
 
func init() {
    lit.RegisterModel[User](lit.PostgreSQL)
    // or for MySQL:
    // lit.RegisterModel[User](lit.MySQL)
}

Registration only happens once and caches INSERT/UPDATE queries for optimal performance.

We recommend registering the models in a centralized place that you invoke in your main function:

import "github.com/tracewayapp/go-lightning/lit"
 
func RegisterModels() {
    lit.RegisterModel[User](lit.PostgreSQL)
    lit.RegisterModel[Invoice](lit.PostgreSQL)
    // ... register other models
}
 
func main() {
    // init config etc...
 
    RegisterModels()
 
    // start your server/the rest of your application code...
}

4. Connect to Database

import (
    "database/sql"
    _ "github.com/lib/pq"  // PostgreSQL driver
)
 
db, err := sql.Open("postgres", "postgres://user:pass@localhost/mydb?sslmode=disable")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

5. Perform CRUD Operations

Create

user := User{
    FirstName: "John",
    LastName:  "Doe",
    Email:     "john@example.com",
}
id, err := lit.Insert(db, &user)

Read

// Select all
users, err := lit.Select[User](db,
    "SELECT id, first_name, last_name, email FROM users")
 
// Select single
user, err := lit.SelectSingle[User](db,
    "SELECT id, first_name, last_name, email FROM users WHERE id = $1", id)

Update

user.FirstName = "Jane"
err := lit.Update(db, &user, "id = $1", user.Id)

Delete

err := lit.Delete(db, "DELETE FROM users WHERE id = $1", id)

MySQL Differences

When using MySQL, use ? placeholders instead of $1, $2, etc:

// MySQL uses ? placeholders
user, err := lit.SelectSingle[User](db,
    "SELECT id, first_name, last_name, email FROM users WHERE id = ?", id)
 
err := lit.Update(db, &user, "id = ?", user.Id)
 
err := lit.Delete(db, "DELETE FROM users WHERE id = ?", id)

Next Steps