sqlofi

package module
v0.0.0-...-d7831b1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2025 License: MIT Imports: 8 Imported by: 0

README

SQLOFI - Simple query syntax in go

SQLOFI is a simple Go library that makes database schema generation easy through struct tag annotations. This project was created as a learning exercise in Go, aiming to explore reflection, and SQL schema generation.

Overview

SQLOFI allows you to define your database schema directly in your Go structs using tags. It parses these tags and generates appropriate SQL statements for creating tables, indexes, constraints, and relationships.

Features

  • Generate SQLite database schema from Go structs
  • Support for common SQL constraints and features:
    • Primary keys
    • Foreign keys with different actions (CASCADE, SET NULL, etc.)
    • Indexes (including unique and partial indexes)
    • Generated/computed columns
    • Default values
    • Not null constraints
    • Auto-increment
  • Automatic type mapping from Go types to SQLite types
  • Simple API for setting up database schema

Example Usage

package main

import (
	"database/sql"
	"fmt"
	"github.com/yourusername/sqlofi"
	_ "github.com/mattn/go-sqlite3"
)

type User struct {
	ID        int64  `sql:"primary key;autoincrement"`
	Username  string `sql:"NOT NULL;UNIQUE"`
	Email     string `sql:"NOT NULL;UNIQUE"`
	CreatedAt string `sql:"NOT NULL;DEFAULT:CURRENT_TIMESTAMP"`
}

type Post struct {
	ID      int64         `sql:"primary key;autoincrement"`
	Title   string        `sql:"NOT NULL"`
	Content string        `sql:"NOT NULL"`
	UserID  sql.NullInt64 `sql:"foreign key:user (id),ON DELETE CASCADE"`
	Likes   int           `sql:"DEFAULT:0"`
}

func main() {
	// Create schema from structs
	schema, err := sqlofi.CreateSchema(User{}, Post{})
	if err != nil {
		panic(err)
	}

	// Connect to database
	db, err := sql.Open("sqlite3", "./test.db")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	// Set up database schema
	schema.SetUpDB(db)

	fmt.Println("Database schema created successfully")
}

Tag Syntax

SQLOFI uses struct tags to define column properties:

type MyStruct struct {
    ID       int64  `sql:"primary key;autoincrement"`
    Name     string `sql:"NOT NULL;UNIQUE"`
    ParentID int64  `sql:"foreign key:parent (id),ON DELETE CASCADE"`
    FullName string `sql:"GENERATED:Name || ' ' || LastName,STORED"`
}

Available tag options include:

  • primary key - Makes the column a primary key
  • autoincrement - Adds auto-increment (only for INTEGER PRIMARY KEY)
  • NOT NULL - Adds NOT NULL constraint
  • UNIQUE - Adds UNIQUE constraint
  • DEFAULT:value - Sets default value
  • foreign key:table (column),action - Creates foreign key reference
  • GENERATED:expression,STORED/VIRTUAL - Creates computed column

Project Status

This is a learning project and not intended for production use. It's a simple implementation to explore Go's capabilities for working with struct tags and database schemas.

License

MIT

Contributing

This is a personal learning project, but feel free to use it as inspiration for your own exploration of Go programming.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	OnDelete = func(r RowAction) string {
		return fmt.Sprintf("ON DELETE %s", r.String())
	}
	OnUpdate = func(r RowAction) string {
		return fmt.Sprintf("ON UPDATE %s", r.String())
	}
	None = func(r RowAction) string {
		return ""
	}
)

Functions

This section is empty.

Types

type Action

type Action func(RowAction) string

type ForeignKey

type ForeignKey struct {
	Column     string
	References string
	Action     string
}

func (*ForeignKey) String

func (f *ForeignKey) String() string

type GeneratedOption

type GeneratedOption struct {
	Stored bool
	// contains filtered or unexported fields
}

func (*GeneratedOption) String

func (g *GeneratedOption) String() string

type IndexOptions

type IndexOptions struct {
	Name   string // Name of the index
	Unique bool   // Whether the index is unique
	Where  string // Conditional index (partial index)
	Column string
}

func (*IndexOptions) String

func (i *IndexOptions) String(table string) string

type RowAction

type RowAction int
const (
	Cascade RowAction = iota
	SetNul
	SetDefault
	Restrict
)

func (RowAction) String

func (r RowAction) String() string

type SQLSchema

type SQLSchema struct {
	Tables []*SqlTable
}

func CreateSchema

func CreateSchema(models ...interface{}) (*SQLSchema, error)

GenerateSchema generates SQL schema from structs

func (*SQLSchema) SetUpDB

func (s *SQLSchema) SetUpDB(db *sql.DB)

type SqlColumn

type SqlColumn struct {
	Name string
	Tags *TagOptions
}

func (*SqlColumn) String

func (c *SqlColumn) String() string

String generates the SQL column definition

type SqlTable

type SqlTable struct {
	Name        string
	TableConfig *TableOptions
	Columns     []*SqlColumn
	ForeignKeys []*ForeignKey
	Indexes     []*IndexOptions
}

func (*SqlTable) String

func (t *SqlTable) String() string

String generates the complete SQL CREATE TABLE statement

type TableOptions

type TableOptions struct {
	IfNotExist bool
}

type TagOptions

type TagOptions struct {
	Type string
	// Basic Constraints
	PrimaryKey    bool        // PRIMARY KEY constraint
	ForeignKey    *ForeignKey // FOREIGN KEY constraint with reference
	Unique        bool        // UNIQUE constraint
	NotNull       bool        // NOT NULL constraint
	AutoIncrement bool        // AUTOINCREMENT (only for INTEGER PRIMARY KEY)

	// Value Constraints
	Default string // DEFAULT value
	Check   string // CHECK constraint

	// Text-specific Attributes
	Collate string // COLLATION type (BINARY, NOCASE, RTRIM)

	// Generated Column
	Generated *GeneratedOption // GENERATED ALWAYS AS expression

	// Conflict Clause
	OnConflict string // ON CONFLICT clause (ROLLBACK, ABORT, FAIL, IGNORE, REPLACE)

	// Deferrable Constraints
	Deferrable        bool // DEFERRABLE
	InitiallyDeferred bool // INITIALLY DEFERRED

	// Index
	Index *IndexOptions // Creates an index on this column
}

TagOptions represents all possible SQLite column constraints and attributes

func (*TagOptions) String

func (t *TagOptions) String() string

func (*TagOptions) Validate

func (t *TagOptions) Validate() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL