All Projects → azer → Crud

azer / Crud

Licence: wtfpl
Relational database library for SQL databases & Go.

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Crud

Warehouse Inventory System
Open source inventory management system with php and mysql
Stars: ✭ 235 (-20.61%)
Mutual labels:  database, mysql
Php Crud Api
Single file PHP script that adds a REST API to a SQL database
Stars: ✭ 2,904 (+881.08%)
Mutual labels:  database, mysql
Granite
ORM Model with Adapters for mysql, pg, sqlite in the Crystal Language.
Stars: ✭ 238 (-19.59%)
Mutual labels:  database, mysql
Scany
Library for scanning data from a database into Go structs and more
Stars: ✭ 228 (-22.97%)
Mutual labels:  database, mysql
Sequelizer
A GUI Desktop App for export sequelize models from database automatically.
Stars: ✭ 273 (-7.77%)
Mutual labels:  database, mysql
Db Sync
PHP library with command line tool for efficiently syncing tables between remote MySQL databases
Stars: ✭ 230 (-22.3%)
Mutual labels:  database, mysql
Sqlfiddle3
New version based on vert.x and docker
Stars: ✭ 242 (-18.24%)
Mutual labels:  database, mysql
Endb
Key-value storage for multiple databases. Supports MongoDB, MySQL, Postgres, Redis, and SQLite.
Stars: ✭ 208 (-29.73%)
Mutual labels:  database, mysql
Wetland
A Node.js ORM, mapping-based. Works with MySQL, PostgreSQL, SQLite and more.
Stars: ✭ 261 (-11.82%)
Mutual labels:  database, mysql
Mikro Orm
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.
Stars: ✭ 3,874 (+1208.78%)
Mutual labels:  database, mysql
Liquibase
Main Liquibase Source
Stars: ✭ 2,910 (+883.11%)
Mutual labels:  database, mysql
Dbq
Zero boilerplate database operations for Go
Stars: ✭ 273 (-7.77%)
Mutual labels:  database, mysql
Db
Data access layer for PostgreSQL, CockroachDB, MySQL, SQLite and MongoDB with ORM-like features.
Stars: ✭ 2,832 (+856.76%)
Mutual labels:  database, mysql
Django Migration Linter
🚀 Detect backward incompatible migrations for your django project
Stars: ✭ 231 (-21.96%)
Mutual labels:  database, mysql
Fluentmigrator
Fluent migrations framework for .NET
Stars: ✭ 2,636 (+790.54%)
Mutual labels:  database, mysql
Gorm Bulk Insert
implement BulkInsert using gorm, just pass a Slice of Struct. Simple and compatible.
Stars: ✭ 241 (-18.58%)
Mutual labels:  database, mysql
Migrate
Database migrations. CLI and Golang library.
Stars: ✭ 2,315 (+682.09%)
Mutual labels:  database, mysql
Shardingsphere
Build criterion and ecosystem above multi-model databases
Stars: ✭ 14,989 (+4963.85%)
Mutual labels:  database, mysql
Bitnami Docker Mariadb
Bitnami MariaDB Docker Image
Stars: ✭ 251 (-15.2%)
Mutual labels:  database, mysql
Pg chameleon
MySQL to PostgreSQL replica system
Stars: ✭ 274 (-7.43%)
Mutual labels:  database, mysql

CRUD

A minimalistic relational database library for Go.

Features:

Manual:

Table of Contents

Install

$ go get github.com/azer/crud

Initialize

import (
  "github.com/azer/crud"
  _ "github.com/go-sql-driver/mysql"
)

var DB *crud.DB

func init () {
  var err error
  DB, err = crud.Connect("mysql", os.Getenv("DATABASE_URL"))
  err = DB.Ping()
}

Define

type User struct {
  Id int `sql:"auto-increment primary-key"`
  FirstName string
  LastName string
  ProfileId int
}

type Profile struct {
  Id int `sql:"auto-increment primary-key"`
  Bio string `sql:"text"`
}

CRUD will automatically convert column names from "FirstName" (CamelCase) to "first_name" (snake_case) for you. You can still choose custom names though;

type Post struct {
  Slug string `sql:"name=slug_id varchar(255) primary-key required"`
}

If no primary key is specified, CRUD will look for a field named "Id" with int type, and set it as auto-incrementing primary-key field.

Create & Drop Tables

CreateTables takes list of structs and makes sure they exist in the database.

err := DB.CreateTables(User{}, Profile{})

err := DB.DropTables(User{}, Profile{})
Reset Tables

Shortcut for dropping and creating tables.

err := DB.ResetTables(User{}, Profile{})
SQL Options

CRUD tries to be smart about figuring out the best SQL options for your structs, and lets you choose manually, too. For example;

type Tweet struct {
 Text string `sql:"varchar(140) required name=tweet"`
}

Above example sets the type of the Text column as varchar(140), makes it required (NOT NULL) and changes the column name as tweet.

Here is the list of the options that you can pass;

  • Types: int, bigint, varchar, text, date, time, timestamp
  • auto-increment / autoincrement / auto_increment
  • primary-key / primarykey / primary_key
  • required
  • default='?'
  • name=?
  • table-name=?

If you'd like a struct field to be ignored by CRUD, choose - as options:

type Foo struct {
 IgnoreMe string `sql:"-"`
}

Create

Simply pass a struct. It can be pointer or not.

user := &User{1, "Foo", "Bar", 1}
err := DB.Create(user)

CreateAndRead

Create a row, and read it back from the DB. The values of the struct you passed get resetted to whatever the corresponding DB row has. In the other words, CreateAndRead creates, and reads. So you got fields generated by the DB scanned to your struct, like ID.

Make sure passing a pointer.

user := User{
  FirstName:"Foo"
}

err := DB.CreateAndRead(&user)

user.Id
// => 123

Read

You can read single/multiple rows, or custom values, with the Read method.

Reading a single row:

Pass your struct's pointer, and a query;

user := &User{}
err := DB.Read(user, "SELECT * FROM users WHERE id = ?", 1)
// => SELECT * FROM users WHERE id = 1

fmt.Println(user.Name)
// => Foo
Reading multiple rows:
users := []*User{}

err := DB.Read(&users)
// => SELECT * FROM users

fmt.Println(len(users))
// => 10
Scanning to custom values:
names := []string{}
err := DB.Read(&names, "SELECT name FROM users")
name := ""
err := DB.Read(&name, "SELECT name FROM users WHERE id=1")
totalUsers := 0
err := DB.Read(&totalUsers, "SELECT COUNT(id) FROM users"

Update

Updates matching row in database, returns sql.ErrNoRows nothing matched.

user := &User{}
err := DB.Read(user, "SELECT * FROM users WHERE id = ?", 1)

user.Name = "Yolo"
err := DB.Update(user)

Delete

Deletes matching row in database, returns sql.ErrNoRows nothing matched.

err := DB.Delete(&User{
  Id: 1
})

Transactions

Use Begin method of a crud.DB instance to create a new transaction. Each transaction will provide you following methods;

  • Commit
  • Rollback
  • Exec
  • Query
  • Create
  • Read
  • Update
  • Delete
tx, err := DB.Begin()

err := tx.Create(&User{
  Name: "yolo"
})

err := tx.Delete(&User{
  Id: 123
})

err := tx.Commit()

Logs

If you want to see crud's internal logs, specify crud in the LOG environment variable when you run your app. For example;

$ LOG=crud go run myapp.go

(More info about how crud's logging work)

Custom Queries

result, err := DB.Query("DROP DATABASE yolo") // or .Exec

Running Tests

DATABASE_URL="?" go test ./...

Why another ORMish library for Go?

  • Simplicity, taking more advantage of reflect library to keep the API simple.
  • Building less things with more complete abstractions
  • Handling errors in an idiomatic way
  • Good test coverage
  • Modular & reusable code
  • Making less unsafe assumptions. e.g: not mapping structs to SQL rows by column index.
  • Complete & tested SQL Options

Apps Using CRUD

What's Missing?

  • Migration: We need a sophisticated solution for adding / removing columns when user changes the structs.
  • Relationships: This was intentionally avoided. Can be considered if there is a clean way to implement it.
  • Testing Transactions: Transactions work as expected but there is a sync bug in the test causing failure. It needs to be fixed.
  • Comments: I rarely comment my code.
  • Hooks: I'm not sure if this is needed, but worths to consider.
  • Foreign Keys: *
  • Query Builder: Building SQL queries programmatically is useful.
  • Make UTF-8 Default: Looks like the default charset is not UTF8.

LICENSE

WTFPL

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].