mysql

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2022 License: MIT Imports: 7 Imported by: 0

README

mysql

Support MySQL or MariaDB for github.com/gopsql/psql.

You can make MySQL SELECT, INSERT, UPDATE, DELETE statements with this package.

NOTE: Please don't use those features that are only available in PostgreSQL but not MySQL at the moment.

Example

package main

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/gopsql/logger"
	"github.com/gopsql/mysql"
	"github.com/gopsql/psql"
)

type (
	User struct {
		// using a different table name other than "users"
		__TABLE_NAME__ string "user"

		Id        int
		Name      string
		Avatar    string
		Phone     *string   // can be null
		CreatedAt timestamp // use integer to store time
		UpdatedAt timestamp
	}
)

var (
	Users = newModel(User{})
)

func main() {
	conn := mysql.MustOpen("root@tcp(127.0.0.1:33333)/yourdb")
	for _, m := range models {
		m.SetConnection(conn)
		m.SetLogger(logger.StandardLogger)
	}

	var users []User
	Users.Find().Where("id > $1", 1).Limit(10).MustQuery(&users)
	fmt.Println(users)
}

var (
	models []*psql.Model
)

func newModel(o interface{}) *psql.Model {
	m := psql.NewModel(o)
	models = append(models, m)
	return m
}

type timestamp time.Time

func (t timestamp) String() string {
	return time.Time(t).Format(time.RFC3339)
}

func (t *timestamp) Scan(value interface{}) error {
	if v, ok := value.([]byte); ok {
		ts, err := strconv.ParseInt(string(v), 10, 64)
		if err != nil {
			return err
		}
		*t = timestamp(time.Unix(ts, 0))
	}
	return nil
}

func (t timestamp) Value() (driver.Value, error) {
	return strconv.FormatInt(time.Time(t).Unix(), 10), nil
}

func (t timestamp) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Time(t))
}

func (t *timestamp) UnmarshalJSON(b []byte) error {
	var m time.Time
	if err := json.Unmarshal(b, &m); err != nil {
		return err
	}
	*t = timestamp(m)
	return nil
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustOpen

func MustOpen(conn string) *mysqlDB

MustOpen is like Open but panics if connect operation fails.

func Open

func Open(conn string) (*mysqlDB, error)

Open creates and establishes one connection to database.

Types

This section is empty.

Jump to

Keyboard shortcuts

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