Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add gorm #1

Merged
merged 31 commits into from
Aug 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = false
max_line_length = 100
tab_width = 4
ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = false
ij_smart_tabs = false
ij_visual_guides = 80,100
ij_wrap_on_typing = false

[{*.go,*.go2}]
indent_style = tab
ij_continuation_indent_size = 4
ij_visual_guides = none
ij_go_GROUP_CURRENT_PROJECT_IMPORTS = true
ij_go_add_leading_space_to_comments = false
ij_go_add_parentheses_for_single_import = false
ij_go_call_parameters_new_line_after_left_paren = true
ij_go_call_parameters_right_paren_on_new_line = true
ij_go_call_parameters_wrap = off
ij_go_fill_paragraph_width = 80
ij_go_group_stdlib_imports = true
ij_go_import_sorting = goimports
ij_go_keep_indents_on_empty_lines = false
ij_go_local_group_mode = project
ij_go_move_all_imports_in_one_declaration = true
ij_go_move_all_stdlib_imports_in_one_group = true
ij_go_remove_redundant_import_aliases = false
ij_go_run_go_fmt_on_reformat = true
ij_go_use_back_quotes_for_imports = false
ij_go_wrap_comp_lit = off
ij_go_wrap_comp_lit_newline_after_lbrace = true
ij_go_wrap_comp_lit_newline_before_rbrace = true
ij_go_wrap_func_params = off
ij_go_wrap_func_params_newline_after_lparen = true
ij_go_wrap_func_params_newline_before_rparen = true
ij_go_wrap_func_result = off
ij_go_wrap_func_result_newline_after_lparen = true
ij_go_wrap_func_result_newline_before_rparen = true
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@

# Dependency directories (remove the comment below to include it)
# vendor/

.DS_Store
.idea
81 changes: 81 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package cmd

import (
"os"

"github.com/spf13/cobra"

"github.com/anqiansong/sqlgen/internal/gen/flags"
)

var arg flags.RunArg

var rootCmd = &cobra.Command{
Use: "sqlgen",
Short: "A cli for mysql generator",
}
var sqlCmd = &cobra.Command{
Use: "sql",
Short: "Generate SQL model",
Run: func(cmd *cobra.Command, args []string) {
arg.Mode = flags.SQL
flags.Run(arg)
},
}

var gormCmd = &cobra.Command{
Use: "gorm",
Short: "Generate gorm model",
Run: func(cmd *cobra.Command, args []string) {
arg.Mode = flags.GORM
flags.Run(arg)
},
}

var xormCmd = &cobra.Command{
Use: "xorm",
Short: "Generate xorm model",
Run: func(cmd *cobra.Command, args []string) {
arg.Mode = flags.XORM
flags.Run(arg)
},
}

var sqlxCmd = &cobra.Command{
Use: "sqlx",
Short: "Generate sqlx model",
Run: func(cmd *cobra.Command, args []string) {
arg.Mode = flags.SQLX
flags.Run(arg)
},
}

var bunCmd = &cobra.Command{
Use: "bun",
Short: "Generate bun model",
Run: func(cmd *cobra.Command, args []string) {
arg.Mode = flags.BUN
flags.Run(arg)
},
}

func init() {
// flags init
var persistentFlags = rootCmd.PersistentFlags()
persistentFlags.StringVarP(&arg.DSN, "dsn", "d", "", "Mysql address")
persistentFlags.StringSliceVarP(&arg.Table, "table", "t", []string{"*"}, "Patterns of table name")
persistentFlags.StringSliceVarP(&arg.Filename, "filename", "f", []string{"*.sql"}, "Patterns of SQL filename")
persistentFlags.StringVarP(&arg.Output, "output", "o", ".", "The output directory")

// sub commands init
rootCmd.AddCommand(sqlCmd)
rootCmd.AddCommand(gormCmd)
rootCmd.AddCommand(xormCmd)
rootCmd.AddCommand(sqlxCmd)
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
10 changes: 10 additions & 0 deletions example/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/anqiansong/sqlgen/example

go 1.18

require gorm.io/gorm v1.23.8

require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
)
6 changes: 6 additions & 0 deletions example/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas=
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
gorm.io/gorm v1.23.8 h1:h8sGJ+biDgBA1AD1Ha9gFCx7h8npU7AsLdlkX0n2TpE=
gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
16 changes: 16 additions & 0 deletions example/gorm/create/example.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- 用户表 --
CREATE TABLE `user`
(
`id` bigint(10) unsigned NOT NULL AUTO_INCREMENT primary key,
`name` varchar(255) COLLATE utf8mb4_general_ci NULL COMMENT '用户\t名称',
`password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户\n密码',
`mobile` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号',
`gender` char(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '男|女|未公\r开',
`nickname` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '用户昵称',
`type` tinyint(1) COLLATE utf8mb4_general_ci DEFAULT 0 COMMENT '用户类型',
`create_time` timestamp NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `name_index` (`name`),
UNIQUE KEY `type_index` (`type`),
UNIQUE KEY `mobile_index` (`mobile`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '用户表' COLLATE=utf8mb4_general_ci;
44 changes: 44 additions & 0 deletions example/gorm/create/user_model.gen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// generated by sqlgen, do not edit.

package model

import (
"context"
"fmt"
"time"

"gorm.io/gorm"
)

// UserModel represents a user model.
type UserModel struct {
db gorm.DB
}

// User represents a user struct data.
type User struct {
Id uint64 `gorm:"primaryKey;autoIncrement;column:id" json:"id"`
Name string `gorm:"column:name" json:"name"`
Password string `gorm:"column:password" json:"password"`
Mobile string `gorm:"column:mobile" json:"mobile"`
Gender string `gorm:"column:gender" json:"gender"`
Nickname string `gorm:"column:nickname" json:"nickname"`
Type int8 `gorm:"column:type" json:"type"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
UpdateTime time.Time `gorm:"column:update_time" json:"updateTime"`
}

// TableName returns the table name. it implemented by gorm.Tabler.
func (User) TableName() string {
return "user"
}

// Create creates user data.
func (m *UserModel) Create(ctx context.Context, data ...*User) error {
if len(data) == 0 {
return fmt.Errorf("data is empty")
}

db := m.db.WithContext(ctx)
return db.Create(&data).Error
}
8 changes: 8 additions & 0 deletions example/gorm/create/user_model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package model

import "context"

// TODO(sqlgen): Add your own customize code here.
func (m *UserModel) Customize(ctx context.Context, args ...any) {

}
28 changes: 28 additions & 0 deletions example/gorm/delete/example.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-- 用户表 --
CREATE TABLE `user`
(
`id` bigint(10) unsigned NOT NULL AUTO_INCREMENT primary key,
`name` varchar(255) COLLATE utf8mb4_general_ci NULL COMMENT '用户\t名称',
`password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户\n密码',
`mobile` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号',
`gender` char(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '男|女|未公\r开',
`nickname` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '用户昵称',
`type` tinyint(1) COLLATE utf8mb4_general_ci DEFAULT 0 COMMENT '用户类型',
`create_time` timestamp NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `name_index` (`name`),
UNIQUE KEY `type_index` (`type`),
UNIQUE KEY `mobile_index` (`mobile`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '用户表' COLLATE=utf8mb4_general_ci;

-- example1: delete by primary key
-- fn: Delete
delete from user where id = ?;

-- example2: delete by unique key
-- fn: DeleteByName
delete from user where name = ?;

-- example3: delete by unique keys
-- fn: DeleteByNameAndMobile
delete from user where name = ? and mobile = ?;
87 changes: 87 additions & 0 deletions example/gorm/delete/user_model.gen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// generated by sqlgen, do not edit.

package model

import (
"context"
"fmt"
"time"

"gorm.io/gorm"
)

// UserModel represents a user model.
type UserModel struct {
db gorm.DB
}

// User represents a user struct data.
type User struct {
Id uint64 `gorm:"primaryKey;autoIncrement;column:id" json:"id"`
Name string `gorm:"column:name" json:"name"`
Password string `gorm:"column:password" json:"password"`
Mobile string `gorm:"column:mobile" json:"mobile"`
Gender string `gorm:"column:gender" json:"gender"`
Nickname string `gorm:"column:nickname" json:"nickname"`
Type int8 `gorm:"column:type" json:"type"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
UpdateTime time.Time `gorm:"column:update_time" json:"updateTime"`
}

// DeleteWhereParameter is a where parameter structure.
type DeleteWhereParameter struct {
Id uint64
}

// DeleteByNameWhereParameter is a where parameter structure.
type DeleteByNameWhereParameter struct {
Name string
}

// DeleteByNameAndMobileWhereParameter is a where parameter structure.
type DeleteByNameAndMobileWhereParameter struct {
Name string
Mobile string
}

// TableName returns the table name. it implemented by gorm.Tabler.
func (User) TableName() string {
return "user"
}

// Create creates user data.
func (m *UserModel) Create(ctx context.Context, data ...*User) error {
if len(data) == 0 {
return fmt.Errorf("data is empty")
}

db := m.db.WithContext(ctx)
return db.Create(&data).Error
}

// Delete is generated from sql:
// delete from user where id = ?;
func (m *UserModel) Delete(ctx context.Context, where DeleteWhereParameter) error {
var db = m.db.WithContext(ctx)
db.Where(`id = ?`, where.Id)
db.Delete(&User{})
return db.Error
}

// DeleteByName is generated from sql:
// delete from user where name = ?;
func (m *UserModel) DeleteByName(ctx context.Context, where DeleteByNameWhereParameter) error {
var db = m.db.WithContext(ctx)
db.Where(`name = ?`, where.Name)
db.Delete(&User{})
return db.Error
}

// DeleteByNameAndMobile is generated from sql:
// delete from user where name = ? and mobile = ?;
func (m *UserModel) DeleteByNameAndMobile(ctx context.Context, where DeleteByNameAndMobileWhereParameter) error {
var db = m.db.WithContext(ctx)
db.Where(`name = ? AND mobile = ?`, where.Name, where.Mobile)
db.Delete(&User{})
return db.Error
}
8 changes: 8 additions & 0 deletions example/gorm/delete/user_model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package model

import "context"

// TODO(sqlgen): Add your own customize code here.
func (m *UserModel) Customize(ctx context.Context, args ...any) {

}
Loading