bob

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2021 License: MIT Imports: 4 Imported by: 0

README

Bob - SQL Query Builder

Go Reference Go Report Card GitHub CodeFactor codecov Codacy Badge Test and coverage

Bob is an SQL builder library initially made as an extension for Squirrel with functionality like Knex (from the Node.js world). Squirrel itself doesn't provide other types of queries for creating a table, upsert, and some other things. Bob is meant to fill those gaps.

The different between Bob and Squirrel is that Bob is solely a query builder. The users have to execute and manage the SQL connection themself. Meaning there are no ExecWith() function implemented on Bob, as you can find it on Squirrel.

The purpose of an SQL query builder is to prevent any typo or mistypes on the SQL queries. Although also with that reason, Bob might not always have the right query for you, depending on what you are doing with the SQL query. It might sometimes be better for you to write the SQL query yourself, if your problem is specific and needs some micro-tweaks.

With that being said, I hope you enjoy using Bob and consider starring or reporting any issues regarding the usage of Bob in your projects.

Oh, and of course, heavily inspired by Bob the Builder.

Usage

import "github.com/aldy505/bob"

Like any other Go projects when you're using Go modules, just put that text right there on the top of your projects, do go mod tidy and you are good to go.

Either way, I'm not 100% confident enough to say that this thing is production ready. But, the way I see it, it's good enough to be used on a production-level applications. In fact, I'm using it on one of my current projects that's getting around 100-200 hits per day.

If you have any feature request or improvement ideas for the project, please kindly open an issue

Create a table
import "github.com/aldy505/bob"

func main() {
  // Note that CREATE TABLE doesn't returns args params.
  sql, _, err := bob.
    CreateTable("tableName").
    // The first parameter is the column's name.
    // The second parameters and so on forth are extras.
    StringColumn("id", "NOT NULL", "PRIMARY KEY", "AUTOINCREMENT").
    StringColumn("email", "NOT NULL", "UNIQUE").
    // See the list of available column definition types through pkg.go.dev or scroll down below.
    TextColumn("password").
    // Or add your custom type.
    AddColumn(bob.ColumnDef{Name: "tableName", Type: "customType", Extras: []string{"NOT NULL"}}).
    ToSql()
  if err != nil {
    // handle your error
  }
}

Available column definition types (please be aware that some only works on certain database):

  • StringColumn() - Default to VARCHAR(255)
  • TextColumn() - Default to TEXT
  • UUIDColumn() - Defaults to UUID
  • BooleanColumn() - Defaults to BOOLEAN
  • IntegerColumn() - Defaults to INTEGER. Postgres and SQLite only.
  • IntColumn() - Defaults to INT. MySQL and MSSQL only.
  • RealColumn() - Defaults to REAL. Postgres, MSSQL, and SQLite only.
  • FloatColumn() - Defaults to FLOAT. Postgres and SQLite only.
  • DateTimeColumn() - Defaults to DATETIME.
  • TimeStampColumn() - Defaults to TIMESTAMP.
  • TimeColumn() - Defaults to TIME.
  • DateColumn() - Defaults to DATE.
  • JSONColumn() - Dafults to JSON. MySQL and Postgres only.
  • JSONBColumn() - Defaults to JSONB. Postgres only.
  • BlobColumn() - Defaults to BLOB. MySQL and SQLite only.

For any other types, please use AddColumn().

Another builder of bob.CreateTableIfNotExists() is also available.

Create index
func main() {
  sql, _, err := bob.
    CreateIndex("idx_email").
    On("users").
    // To create a CREATE UNIQUE INDEX ...
    Unique().
    // Method "Spatial()" and "FullText()" are also available.
    // You can specify as many columns as you like.
    Columns(bob.IndexColumn{Name: "email", Collate: "DEFAULT", Extras: []string{"ASC"}}).
    ToSql()
  if err != nil {
    log.Fatal(err)
  }
}

Another builder of bob.CreateIndexIfNotExists() is also available.

Check if a table exists
func main() {
  sql, args, err := bob.HasTable("users").ToSql()
  if err != nil {
    log.Fatal(err)
  }
}
Check if a column exists
func main() {
  sql, args, err := bob.HasColumn("email").ToSql()
  if err != nil {
    log.Fatal(err)
  }
}
Drop table
func main() {
  sql, _, err := bob.DropTable("users").ToSql()
  if err != nil {
    log.Fatal(err)
  }
  // sql = "DROP TABLE users;"

  sql, _, err = bob.DropTableIfExists("users").ToSql()
  if err != nil {
    log.Fatal(err)
  }
  // sql = "DROP TABLE IF EXISTS users;"

  sql, _, err = bob.DropTable("users").Cascade().ToSql()
  if err != nil {
    log.Fatal(err)
  }
  // sql = "DROP TABLE users CASCADE;"

  sql, _, err = bob.DropTable("users").Restrict().ToSql()
  if err != nil {
    log.Fatal(err)
  }
  // sql = "DROP TABLE users RESTRICT;"
}
Truncate table
func main() {
  sql, _, err := bob.Truncate("users").ToSql()
  if err != nil {
    log.Fatal(err)
  }
}
Rename table
func main() {
  sql, _, err := bob.RenameTable("users", "people").ToSql()
  if err != nil {
    log.Fatal(err)
  }
}
Upsert
func main() {
  sql, args, err := bob.
    // Notice that you should give database dialect on the second params.
    // Available database dialect are MySQL, PostgreSQL, SQLite, and MSSQL.
    Upsert("users", bob.MySQL).
    Columns("name", "email", "age").
    // You could do multiple Values() call, but I'd suggest to not do it.
    // Because this is an upsert function, not an insert one.
    Values("Thomas Mueler", "tmueler@something.com", 25).
    Replace("age", 25).
    ToSql()

  // Another example for PostgreSQL
  sql, args, err = bob.
    Upsert("users", bob.PostgreSQL).
    Columns("name", "email", "age").
    Values("Billy Urtha", "billu@something.com", 30).
    Key("email").
    Replace("age", 40).
    ToSql()

  // One more time, for MSSQL / SQL Server.
  sql, args, err = bob.
    Upsert("users", bob.MSSQL).
    Columns("name", "email", "age").
    Values("George Rust", "georgee@something.com", 19).
    Key("email", "georgee@something.com").
    Replace("age", 18).
    ToSql()
}
Placeholder format / Dialect

Default placeholder is a question mark (MySQL-like). If you want to change it, simply use something like this:

func main() {
  // Option 1
  sql, args, err := bob.HasTable("users").PlaceholderFormat(bob.Dollar).ToSql()
  if err != nil {
    log.Fatal(err)
  }

  // Option 2
  sql, args, err = bob.HasTable("users").ToSql()
  if err != nil {
    log.Fatal(err)
  }
  correctPlaceholder := bob.ReplacePlaceholder(sql, bob.Dollar)
}

Available placeholder formats:

  • bob.Question - INSERT INTO "users" (name) VALUES (?)
  • bob.Dollar - INSERT INTO "users" (name) VALUES ($1)
  • bob.Colon - INSERT INTO "users" (name) VALUES (:1)
  • bob.AtP - INSERT INTO "users" (name) VALUES (@p1)
With pgx (PostgreSQL)
import (
  "context"
  "log"
  "strings"

  "github.com/aldy505/bob"
  "github.com/jackc/pgx/v4"
)

func main() {
  db := pgx.Connect()

  // Check if a table is exists
  sql, args, err = bob.HasTable("users").PlaceholderFormat(bob.Dollar).ToSql()
  if err != nil {
    log.Fatal(err)
  }

  var hasTableUsers bool
  err = db.QueryRow(context.Background(), sql, args...).Scan(&hasTableUsers)
  if err != nil {
    if err == bob.ErrEmptyTablePg {
      hasTableUsers = false
    } else {
      log.Fatal(err)
    }
  }

  if !hasTableUsers {
    // Create "users" table
    sql, _, err := bob.
      CreateTable("users").
      IntegerColumn("id", "PRIMARY KEY", "SERIAL").
      StringColumn("name", "NOT NULL").
      TextColumn("password", "NOT NULL").
      DateColumn("created_at").
      ToSql()
    if err != nil {
      log.Fatal(err)
    }

    _, err = db.Query(context.Background(), splitQuery[i])
    if err != nil {
      log.Fatal(err)
    }

    // Create another table, this time with CREATE TABLE IF NOT EXISTS
    sql, _, err := bob.
      CreateTableIfNotExists("inventory").
      UUIDColumn("id", "PRIMARY KEY").
      IntegerColumn("userID", "FOREIGN KEY REFERENCES users(id)").
      JSONColumn("items").
      IntegerColumn("quantity").
      ToSql()
    if err != nil {
      log.Fatal(err)
    }

    _, err = db.Query(context.Background(), inventoryQuery[i])
    if err != nil {
      log.Fatal(err)
    }
  }
}

Features

  • bob.CreateTable(tableName) - Basic SQL create table
  • bob.CreateTableIfNotExists(tableName) - Create table if not exists
  • bob.CreateIndex(indexName) - Basic SQL create index
  • bob.CreateIndexIfNotExists(tableName) - Create index if not exists
  • bob.HasTable(tableName) - Checks if column exists (return error if false, check example above for error handling)
  • bob.HasColumn(columnName) - Check if a column exists on current table
  • bob.DropTable(tableName) - Drop a table (drop table "users")
  • bob.DropTableIfExists(tableName) - Drop a table if exists (drop table if exists "users")
  • bob.RenameTable(currentTable, desiredName) - Rename a table (rename table "users" to "people")
  • bob.Truncate(tableName) - Truncate a table (truncate "users")
  • bob.Upsert(tableName, dialect) - UPSERT function (insert into "users" ("name", "email") values (?, ?) on duplicate key update email = ?)

Contributing

Contributions are always welcome! As long as you add a test for your changes.

License

Bob is licensed under MIT license

Documentation

Overview

Bob is an SQL builder library initially made as an extension for Squirrel with functionality like Knex (from the Node.js world). Squirrel itself doesn't provide other types of queries for creating a table, upsert, and some other things. Bob is meant to fill those gaps.

The different between Bob and Squirrel is that Bob is solely a query builder. The users have to execute and manage the SQL connection themself. Meaning there are no ExecWith() function implemented on Bob, as you can find it on Squirrel.

The purpose of an SQL query builder is to prevent any typo or mistypes on the SQL queries. Although also with that reason, Bob might not always have the right query for you, depending on what you are doing with the SQL query. It might sometimes be better for you to write the SQL query yourself, if your problem is specific and needs some micro-tweaks.

With that being said, I hope you enjoy using Bob and consider starring or reporting any issues regarding the usage of Bob in your projects.

MIT License

Copyright (c) 2021-present Reinaldy Rafli and Bob collaborators

Index

Examples

Constants

View Source
const (
	MySQL int = iota
	PostgreSQL
	SQLite
	MSSQL
)
View Source
const (
	// Question is the format used in MySQL
	Question = "?"
	// Dollar is the format used in PostgreSQL
	Dollar = "$"
	// Colon is the format used in Oracle Database, but here I implemented it wrong.
	// I will either fix it or remove it in the future.
	Colon = ":"
	// AtP comes in the documentation of Squirrel but I don't know what database uses it.
	AtP = "@p"
)

Variables

BobStmtBuilder is the parent builder for BobBuilderType

View Source
var ErrDialectNotSupported = errors.New("provided database dialect is not supported")

ErrDialectNotSupported tells you whether the dialect is supported or not.

View Source
var ErrEmptyTable = errors.New("sql: no rows in result set")

ErrEmptyTable is a common database/sql error if a table is empty or no rows is returned by the query.

View Source
var ErrEmptyTablePgx = errors.New("no rows in result set")

ErrEmptyTable is a common pgx error if a table is empty or no rows is returned by the query.

Functions

func ReplacePlaceholder

func ReplacePlaceholder(sql string, format string) string

ReplacePlaceholder converts default placeholder format to a specific format.

Types

type AlterBuilder added in v0.0.5

type AlterBuilder builder.Builder

func DropColumn added in v0.0.5

func DropColumn(table, column string) AlterBuilder

func DropConstraint added in v0.0.5

func DropConstraint(table, constraint string) AlterBuilder

func RenameColumn added in v0.0.5

func RenameColumn(table, from, to string) AlterBuilder

func RenameConstraint added in v0.0.5

func RenameConstraint(table, from, to string) AlterBuilder

func (AlterBuilder) Suffix added in v0.0.5

func (b AlterBuilder) Suffix(any string) AlterBuilder

func (AlterBuilder) ToSql added in v0.0.5

func (b AlterBuilder) ToSql() (string, []interface{}, error)

type BobBuilder

type BobBuilder interface {
	ToSql() (string, []interface{}, error)
}

BobBuilder interface wraps the ToSql method

type BobBuilderType

type BobBuilderType builder.Builder

BobBuilderType is the type for BobBuilder

func (BobBuilderType) CreateIndex added in v0.0.5

func (b BobBuilderType) CreateIndex(name string) IndexBuilder

CreateIndex creates an index with CreateIndexBuilder interface.

func (BobBuilderType) CreateIndexIfNotExists added in v0.0.5

func (b BobBuilderType) CreateIndexIfNotExists(name string) IndexBuilder

CreateIndexIfNotExists creates an index with CreateIndexBuilder interface, if the index doesn't exists.

func (BobBuilderType) CreateTable

func (b BobBuilderType) CreateTable(table string) CreateBuilder

CreateTable creates a table with CreateBuilder interface

func (BobBuilderType) CreateTableIfNotExists

func (b BobBuilderType) CreateTableIfNotExists(table string) CreateBuilder

CreateTableIfNotExists creates a table with CreateBuilder interface, if the table doesn't exists.

func (BobBuilderType) DropColumn added in v0.0.5

func (b BobBuilderType) DropColumn(table, column string) AlterBuilder

func (BobBuilderType) DropConstraint added in v0.0.5

func (b BobBuilderType) DropConstraint(table, constraint string) AlterBuilder

func (BobBuilderType) DropTable added in v0.0.3

func (b BobBuilderType) DropTable(table string) DropBuilder

DropTable drops (delete contents & remove) a table from the database.

func (BobBuilderType) DropTableIfExists added in v0.0.3

func (b BobBuilderType) DropTableIfExists(table string) DropBuilder

DropTable drops (delete contents & remove) a table from the database if the table exists.

func (BobBuilderType) HasColumn

func (b BobBuilderType) HasColumn(column string) HasBuilder

HasColumn checks if a column exists with HasBuilder interface

func (BobBuilderType) HasTable

func (b BobBuilderType) HasTable(table string) HasBuilder

HasTable checks if a table exists with HasBuilder interface

func (BobBuilderType) RenameColumn added in v0.0.5

func (b BobBuilderType) RenameColumn(table, from, to string) AlterBuilder

func (BobBuilderType) RenameConstraint added in v0.0.5

func (b BobBuilderType) RenameConstraint(table, from, to string) AlterBuilder

func (BobBuilderType) RenameTable added in v0.0.3

func (b BobBuilderType) RenameTable(from, to string) RenameBuilder

RenameTable simply renames an exisisting table.

func (BobBuilderType) Truncate added in v0.0.3

func (b BobBuilderType) Truncate(table string) TruncateBuilder

Truncate performs TRUNCATE function. It deletes all contents from a table but not deleting the table.

func (BobBuilderType) Upsert added in v0.0.3

func (b BobBuilderType) Upsert(table string, dialect int) UpsertBuilder

type ColumnDef added in v0.0.2

type ColumnDef struct {
	Name   string
	Type   string
	Extras []string
}

type CreateBuilder

type CreateBuilder builder.Builder

func CreateTable

func CreateTable(table string) CreateBuilder

CreateTable creates a table with CreateBuilder interface. Refer to README for available column definition types.

// Note that CREATE TABLE doesn't returns args params.
sql, _, err := bob.
  CreateTable("tableName").
  // The first parameter is the column's name.
  // The second parameters and so on forth are extras.
  StringColumn("id", "NOT NULL", "PRIMARY KEY", "AUTOINCREMENT").
  StringColumn("email", "NOT NULL", "UNIQUE").
  // See the list of available column definition types through pkg.go.dev or README.
  TextColumn("password").
  // Or add your custom type.
  AddColumn(bob.ColumnDef{Name: "tableName", Type: "customType", Extras: []string{"NOT NULL"}}).
  ToSql()
if err != nil {
// handle your error
}

func CreateTableIfNotExists

func CreateTableIfNotExists(table string) CreateBuilder

CreateTableIfNotExists creates a table with CreateBuilder interface, if the table doesn't exists.

func (CreateBuilder) AddColumn added in v0.0.2

func (b CreateBuilder) AddColumn(column ColumnDef) CreateBuilder

AddColumn sets custom columns

func (CreateBuilder) BlobColumn added in v0.0.2

func (b CreateBuilder) BlobColumn(name string, extras ...string) CreateBuilder

BlobColumn only available for MySQL and SQLite. For PostgreSQL and MSSQL, please use AddColumn(bob.ColumnDef{Name: "name", Type: "BYTEA"}).

func (CreateBuilder) BooleanColumn added in v0.0.2

func (b CreateBuilder) BooleanColumn(name string, extras ...string) CreateBuilder

BooleanColumn only available for PostgreSQL

func (CreateBuilder) DateColumn added in v0.0.2

func (b CreateBuilder) DateColumn(name string, extras ...string) CreateBuilder

func (CreateBuilder) DateTimeColumn added in v0.0.2

func (b CreateBuilder) DateTimeColumn(name string, extras ...string) CreateBuilder

func (CreateBuilder) FloatColumn added in v0.0.2

func (b CreateBuilder) FloatColumn(name string, extras ...string) CreateBuilder

FloatColumn only available for MySQL and MSSQL. For PostgreSQL and SQLite, please refer to RealColumn.

func (CreateBuilder) IntColumn added in v0.0.2

func (b CreateBuilder) IntColumn(name string, extras ...string) CreateBuilder

IntColumn only available for MySQL and MSSQL. For PostgreSQL and SQLite please refer to IntegerColumn.

func (CreateBuilder) IntegerColumn added in v0.0.2

func (b CreateBuilder) IntegerColumn(name string, extras ...string) CreateBuilder

IntegerColumn only available for PostgreSQL and SQLite. For MySQL and MSSQL, please refer to IntColumn,

func (CreateBuilder) JSONBColumn added in v0.0.2

func (b CreateBuilder) JSONBColumn(name string, extras ...string) CreateBuilder

JSONBColumn only available for PostgreSQL. For MySQL please refer to JSONColumn.

func (CreateBuilder) JSONColumn added in v0.0.2

func (b CreateBuilder) JSONColumn(name string, extras ...string) CreateBuilder

JSONColumn only available for MySQL and PostgreSQL. For MSSQL please use AddColumn(bob.ColumnDef{Name: "name", Type: "NVARCHAR(1000)"}). Not supported for SQLite.

func (CreateBuilder) RealColumn added in v0.0.2

func (b CreateBuilder) RealColumn(name string, extras ...string) CreateBuilder

RealColumn only available for MSSQL, PostgreSQL, and SQLite. For MySQL, please refer to FloatColumn, or create your own with AddColumn() with Type: "DOUBLE".

func (CreateBuilder) StringColumn added in v0.0.2

func (b CreateBuilder) StringColumn(name string, extras ...string) CreateBuilder

StringColumn creates a column with VARCHAR(255) data type. For SQLite please refer to TextColumn.

func (CreateBuilder) TextColumn added in v0.0.2

func (b CreateBuilder) TextColumn(name string, extras ...string) CreateBuilder

TextColumn creates a column with TEXT data type

func (CreateBuilder) TimeColumn added in v0.0.2

func (b CreateBuilder) TimeColumn(name string, extras ...string) CreateBuilder

func (CreateBuilder) TimeStampColumn added in v0.0.2

func (b CreateBuilder) TimeStampColumn(name string, extras ...string) CreateBuilder

func (CreateBuilder) ToSql

func (b CreateBuilder) ToSql() (string, []interface{}, error)

ToSql returns 3 variables filled out with the correct values based on bindings, etc.

func (CreateBuilder) UUIDColumn added in v0.0.2

func (b CreateBuilder) UUIDColumn(name string, extras ...string) CreateBuilder

UUIDColumn only available for PostgreSQL

func (CreateBuilder) WithSchema

func (b CreateBuilder) WithSchema(name string) CreateBuilder

WithSchema specifies the schema to be used when using the schema-building commands.

type DropBuilder added in v0.0.3

type DropBuilder builder.Builder

func DropTable added in v0.0.3

func DropTable(table string) DropBuilder

DropTable drops (delete contents & remove) a table from the database.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, _, err := bob.DropTable("users").Cascade().ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Println(sql)
}
Output:

DROP TABLE "users" CASCADE;

func DropTableIfExists added in v0.0.3

func DropTableIfExists(table string) DropBuilder

DropTable drops (delete contents & remove) a table from the database if the table exists.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, _, err := bob.DropTableIfExists("users").ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Println(sql)
}
Output:

DROP TABLE IF EXISTS "users";

func (DropBuilder) Cascade added in v0.0.4

func (b DropBuilder) Cascade() DropBuilder

func (DropBuilder) Restrict added in v0.0.4

func (b DropBuilder) Restrict() DropBuilder

func (DropBuilder) ToSql added in v0.0.3

func (b DropBuilder) ToSql() (string, []interface{}, error)

ToSql returns 3 variables filled out with the correct values based on bindings, etc.

type HasBuilder

type HasBuilder builder.Builder

func HasColumn

func HasColumn(col string) HasBuilder

HasColumn checks if a column exists with HasBuilder interface.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, args, err := bob.HasColumn("email").HasTable("users").ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Printf("sql: %s, args: %v", sql, args)
}
Output:

sql: SELECT * FROM information_schema.columns WHERE table_name = ? AND column_name = ? AND table_schema = current_schema();, args: [users email]

func HasTable

func HasTable(table string) HasBuilder

HasTable checks if a table exists with HasBuilder interface.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, args, err := bob.HasTable("users").ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Printf("sql: %s, args: %v", sql, args)
}
Output:

sql: SELECT * FROM information_schema.tables WHERE table_name = ? AND table_schema = current_schema();, args: [users]

func (HasBuilder) HasColumn

func (h HasBuilder) HasColumn(column string) HasBuilder

HasColumn checks if a column exists in the current table, resolves the promise with a boolean, true if the column exists, false otherwise.

func (HasBuilder) HasTable

func (h HasBuilder) HasTable(table string) HasBuilder

HasTable checks for a table's existence by tableName, resolving with a boolean to signal if the table exists.

func (HasBuilder) PlaceholderFormat

func (h HasBuilder) PlaceholderFormat(f string) HasBuilder

PlaceholderFormat changes the default placeholder (?) to desired placeholder.

func (HasBuilder) ToSql

func (h HasBuilder) ToSql() (string, []interface{}, error)

ToSql returns 3 variables filled out with the correct values based on bindings, etc.

func (HasBuilder) WithSchema

func (h HasBuilder) WithSchema(schema string) HasBuilder

WithSchema specifies the schema to be used when using the schema-building commands.

type IndexBuilder added in v0.0.5

type IndexBuilder builder.Builder

func CreateIndex added in v0.0.5

func CreateIndex(name string) IndexBuilder

CreateIndex creates an index with CreateIndexBuilder interface.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, _, err := bob.
		CreateIndex("idx_email").
		On("users").
		Unique().
		Columns(bob.IndexColumn{Name: "email", Collate: "DEFAULT", Extras: []string{"ASC"}}).
		ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Print(sql)
}
Output:

CREATE UNIQUE INDEX idx_email ON users (email COLLATE DEFAULT ASC);

func CreateIndexIfNotExists added in v0.0.5

func CreateIndexIfNotExists(name string) IndexBuilder

CreateIndexIfNotExists creates an index with CreateIndexBuilder interface, if the index doesn't exists.

func (IndexBuilder) Columns added in v0.0.5

func (i IndexBuilder) Columns(column IndexColumn) IndexBuilder

func (IndexBuilder) Fulltext added in v0.0.5

func (i IndexBuilder) Fulltext() IndexBuilder

func (IndexBuilder) On added in v0.0.5

func (i IndexBuilder) On(table string) IndexBuilder

func (IndexBuilder) Spatial added in v0.0.5

func (i IndexBuilder) Spatial() IndexBuilder

func (IndexBuilder) ToSql added in v0.0.5

func (i IndexBuilder) ToSql() (string, []interface{}, error)

func (IndexBuilder) Unique added in v0.0.5

func (i IndexBuilder) Unique() IndexBuilder

type IndexColumn added in v0.0.5

type IndexColumn struct {
	Name    string
	Extras  []string
	Collate string
}

type PlaceholderFormat

type PlaceholderFormat interface {
	ReplacePlaceholders(sql string) (string, error)
}

PlaceholderFormat is an interface for placeholder formattings.

type RenameBuilder added in v0.0.3

type RenameBuilder builder.Builder

func RenameTable added in v0.0.3

func RenameTable(from, to string) RenameBuilder

RenameTable simply renames an exisisting table.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, _, err := bob.RenameTable("users", "people").ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Println(sql)
}
Output:

RENAME TABLE "users" TO "people";

func (RenameBuilder) ToSql added in v0.0.3

func (b RenameBuilder) ToSql() (string, []interface{}, error)

ToSql returns 3 variables filled out with the correct values based on bindings, etc.

type TruncateBuilder added in v0.0.3

type TruncateBuilder builder.Builder

func Truncate added in v0.0.3

func Truncate(table string) TruncateBuilder

Truncate performs TRUNCATE function. It deletes all contents from a table but not deleting the table.

Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	sql, _, err := bob.Truncate("users").ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Println(sql)
}
Output:

TRUNCATE "users";

func (TruncateBuilder) ToSql added in v0.0.3

func (b TruncateBuilder) ToSql() (string, []interface{}, error)

ToSql returns 3 variables filled out with the correct values based on bindings, etc.

type UpsertBuilder added in v0.0.3

type UpsertBuilder builder.Builder

func Upsert added in v0.0.3

func Upsert(table string, dialect int) UpsertBuilder

Upsert performs a UPSERT query with specified database dialect. Supported database includes MySQL, PostgreSQL, SQLite and MSSQL.

// MySQL example:
sql, args, err := bob.
  // Notice that you should give database dialect on the second params.
  // Available database dialect are MySQL, PostgreSQL, SQLite, and MSSQL.
  Upsert("users", bob.MySQL).
  Columns("name", "email", "age").
  // You could do multiple Values() call, but I'd suggest to not do it.
  // Because this is an upsert function, not an insert one.
  Values("Thomas Mueler", "tmueler@something.com", 25).
  Replace("age", 25).
  PlaceholderFormat(bob.Question).
  ToSql()

// Another example for PostgreSQL:
sql, args, err = bob.
  Upsert("users", bob.PostgreSQL).
  Columns("name", "email", "age").
  Values("Billy Urtha", "billu@something.com", 30).
  Key("email").
  Replace("age", 40).
  PlaceholderFormat(bob.Dollar).
  ToSql()

// One more time, for MSSQL / SQL Server:
sql, args, err = bob.
  Upsert("users", bob.MSSQL).
  Columns("name", "email", "age").
  Values("George Rust", "georgee@something.com", 19).
  Key("email", "georgee@something.com").
  Replace("age", 18).
  PlaceholderFormat(bob.AtP).
  ToSql()
Example
package main

import (
	"fmt"

	"github.com/aldy505/bob"
)

func main() {
	// Example for MYSQL
	mysql, myArgs, err := bob.
		// Notice that you should give database dialect on the second params.
		// Available database dialect are MySQL, PostgreSQL, SQLite, and MSSQL.
		Upsert("users", bob.MySQL).
		Columns("name", "email", "age").
		// You could do multiple Values() call, but I'd suggest to not do it.
		// Because this is an upsert function, not an insert one.
		Values("Thomas Mueler", "tmueler@something.com", 25).
		Replace("age", 25).
		ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	// Another example for PostgreSQL
	pgsql, pgArgs, err := bob.
		Upsert("users", bob.PostgreSQL).
		Columns("name", "email", "age").
		Values("Billy Urtha", "billu@something.com", 30).
		Key("email").
		Replace("age", 40).
		ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	// One more time, for MSSQL / SQL Server.
	mssql, msArgs, err := bob.
		Upsert("users", bob.MSSQL).
		Columns("name", "email", "age").
		Values("George Rust", "georgee@something.com", 19).
		Key("email", "georgee@something.com").
		Replace("age", 18).
		ToSql()
	if err != nil {
		fmt.Printf("Handle this error: %v", err)
	}

	fmt.Printf("MySQL: %s, %v\n", mysql, myArgs)
	fmt.Printf("PostgreSQL: %s, %v\n", pgsql, pgArgs)
	fmt.Printf("MSSQL: %s, %v\n", mssql, msArgs)
}
Output:

MySQL: INSERT INTO "users" ("name", "email", "age") VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE "age" = ?;, [Thomas Mueler tmueler@something.com 25 25]
PostgreSQL: INSERT INTO "users" ("name", "email", "age") VALUES ($1, $2, $3) ON CONFLICT ("email") DO UPDATE SET "age" = $4;, [Billy Urtha billu@something.com 30 40]
MSSQL: IF NOT EXISTS (SELECT * FROM "users" WHERE "email" = @p1) INSERT INTO "users" ("name", "email", "age") VALUES (@p2, @p3, @p4) ELSE UPDATE "users" SET "age" = @p5 WHERE "email" = @p6;, [georgee@something.com George Rust georgee@something.com 19 18 georgee@something.com]

func (UpsertBuilder) Columns added in v0.0.3

func (u UpsertBuilder) Columns(columns ...string) UpsertBuilder

Columns sets the columns for the data to be inserted.

func (UpsertBuilder) Key added in v0.0.3

func (u UpsertBuilder) Key(key ...interface{}) UpsertBuilder

Key specifies which key to be checked on conflict. Must be used on PostgreSQL and SQLite.

func (UpsertBuilder) PlaceholderFormat added in v0.0.3

func (u UpsertBuilder) PlaceholderFormat(f string) UpsertBuilder

PlaceholderFormat changes the default placeholder (?) to desired placeholder.

func (UpsertBuilder) Replace added in v0.0.3

func (u UpsertBuilder) Replace(column interface{}, value interface{}) UpsertBuilder

Replace sets the column and value respectively for the data to be changed on a specific row.

func (UpsertBuilder) ToSql added in v0.0.3

func (u UpsertBuilder) ToSql() (string, []interface{}, error)

ToSql returns 3 variables filled out with the correct values based on bindings, etc.

func (UpsertBuilder) Values added in v0.0.3

func (u UpsertBuilder) Values(values ...interface{}) UpsertBuilder

Values sets the values in relation with the columns. Please not that only string, int, and bool type are supported. Inputting other types other than those might result in your SQL not working properly.

Jump to

Keyboard shortcuts

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