crud

command module
v0.0.0-...-6689b15 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2023 License: MIT Imports: 4 Imported by: 0

README

🤖 crud Go Go Report Card Sourcegraph

Demo

  1. There is a table posts in the database, whose structure is as follows:
CREATE SEQUENCE IF NOT EXISTS post_id_seq;

-- Table Definition
CREATE TABLE "public"."posts" (
    "id"         int4 NOT NULL DEFAULT nextval('post_id_seq'::regclass),
    "uid"        bpchar(1),
    "title"      bpchar(1),
    "content"    bpchar(1),
    "created_at" time,
    "updated_at" time,
    "deleted_at" time,
    PRIMARY KEY ( "id" )
);
  1. Run the following command to auto generate code based on the table structure:
crud gen --dsn=postgres://postgres:postgres@localhost:5432/crud?sslmode=disable
  1. Here is what you get, amazing!
package db

import (
	"context"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

var _ PostsStore = (*posts)(nil)

// Posts is the default instance of the PostsStore.
var Posts PostsStore

// PostsStore is the persistent interface for posts.
type PostsStore interface {
	// GetByID returns a post with the given id.
	// The zero value in the options will be ignored.
	GetByID(ctx context.Context, id int64) (*Post, error)
}

// NewPostsStore returns a PostsStore instance with the given database connection.
func NewPostsStore(db *gorm.DB) PostsStore {
	return &posts{db}
}

// Post represents the posts.
type Post struct {
	gorm.Model

	UID     string
	Title   string
	Content string
}

type posts struct {
	*gorm.DB
}

var (
	ErrPostNotExists = errors.New("post dose not exist")
)

func (db *posts) GetByID(ctx context.Context, id int64) (*Post, error) {
	var post Post
	if err := db.WithContext(ctx).Model(&Post{}).Where("id = ?", id).First(&post).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrPostNotExists
		}
	}
	return &post, nil
}

License

MIT License

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
internal
cmd
db

Jump to

Keyboard shortcuts

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