Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Commit

Permalink
lot of good stuff, AutoMigrate handle all, LinkModel no longer needed
Browse files Browse the repository at this point in the history
  • Loading branch information
kamalshkeir committed Jul 29, 2022
1 parent ca953f6 commit bc8a0f9
Show file tree
Hide file tree
Showing 17 changed files with 614 additions and 364 deletions.
15 changes: 7 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -609,19 +609,21 @@ orm.CreateUser(email,password string,isAdmin int, dbName ...string) error // pas
##### using the shell, you can migrate a .sql file 'go run main.go shell'
##### OR
##### you can migrate from a struct
##### on compilation time all models registered using AutoMigrate will be synchronized with the database so if you add a field to you struct or add a column to your table, you will have a prompt proposing solutions
##### execute AutoMigrate and don't think about it, it will handle all synchronisations between your project structs types like 'Bookmark' below
## For the BONUS part: notice that if you add a struct field with tags, tags are handled too, so you can add foreign keys, remove foreign keys, all from your struct, the result will be mirrored in the database after your confirmation
###### if you need to change a tag, remove the field and put new one with the new tag ;)
```go
// execute AutoMigrate to migrate only, not if the table already exist in db, in this case you need only to link your model to the table using : orm.LinkModel
orm.AutoMigrate[T comparable](dbName, tableName string, debug ...bool) error // debug will print the query statement

// if table already exist you can use LinkModel[T comparable](to_table_name string, dbNames ...string)
orm.LinkModel[models.User]("users") // if dbName empty , use default .env db
orm.AutoMigrate[T comparable](dbName, tableName string, debug ...bool) error // debug (optional) will print the query statement

//Example:
type Bookmark struct {
Id uint `orm:"autoinc"`
UserId int `orm:"fk:users.id:cascade"` // options on delete: cascade, donothing, noaction
IsUsed bool
ToCheck string `orm:"size:50; notnull; unique; check:len(to_check) > 10"` // column type will be VARCHAR(50)
ToCheck string `orm:"size:50; notnull; check:len(to_check) > 10"` // column type will be VARCHAR(50)
Content string `orm:"text"` // column type will be TEXT
CreatedAt time.Time `orm:"now"` // now is default to current timestamp
}
Expand Down Expand Up @@ -676,9 +678,6 @@ orm.One() (T, error) // finisher
```
#### Examples
```go
// if a model struct exist already in the database but not linked, you can't migrate it again, so you can link it using:
orm.LinkModel[models.User]("users")

// then you can query your data as models.User data
// you have 2 finisher : All and One

Expand Down
2 changes: 1 addition & 1 deletion core/admin/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import "time"
type User struct {
Id int `json:"id,omitempty" orm:"autoinc"`
Uuid string `json:"uuid,omitempty" orm:"size:50"`
Email string `json:"email,omitempty" orm:"size:50"`
Email string `json:"email,omitempty" orm:"size:50;unique"`
Password string `json:"password,omitempty" orm:"size:150"`
IsAdmin bool `json:"is_admin,omitempty" orm:"default:false"`
Image string `json:"image,omitempty" orm:"size:100;default:''"`
Expand Down
11 changes: 8 additions & 3 deletions core/admin/views.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ var DeleteRowPost = func(c *kamux.Context) {
_ = c.DeleteFile(vv)
}
} else {
c.Status(http.StatusBadRequest).Json(map[string]any{
"error":"missing 'image' in request body",
c.Status(200).Json(map[string]any{
"message":"missing 'image' in request body",
})
return
}
Expand Down Expand Up @@ -343,7 +343,12 @@ var UpdateRowPost = func(c *kamux.Context) {
default:
if modelDB[key] != val[0] {
_,err := orm.Table(data["table"][0]).Where("id = ?",id).Set(key+" = ?",val[0])
logger.CheckError(err)
if err != nil {
c.Json(map[string]any{
"error":err.Error(),
})
return
}
}
c.Json(map[string]any{
"success": key + " Updated successfully !",
Expand Down
3 changes: 3 additions & 0 deletions core/kamux/kamux.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/kamalshkeir/kago/core/orm"
"github.com/kamalshkeir/kago/core/settings"
"github.com/kamalshkeir/kago/core/shell"
"github.com/kamalshkeir/kago/core/utils"
"github.com/kamalshkeir/kago/core/utils/logger"
"golang.org/x/net/websocket"
Expand Down Expand Up @@ -128,6 +129,8 @@ func New(envFiles ...string) *Router {
wg.Done()
}()
wg.Wait()
// init orm shell
if shell.InitShell() {os.Exit(0)}
utils.PrintServerStart()
return app
}
Expand Down
5 changes: 0 additions & 5 deletions core/kamux/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (

"github.com/kamalshkeir/kago/core/orm"
"github.com/kamalshkeir/kago/core/settings"
"github.com/kamalshkeir/kago/core/shell"
"github.com/kamalshkeir/kago/core/utils"
"github.com/kamalshkeir/kago/core/utils/logger"
"golang.org/x/net/websocket"
Expand Down Expand Up @@ -59,8 +58,6 @@ func (router *Router) UseMiddlewares(midws ...func(http.Handler) http.Handler) {

// Run start the server
func (router *Router) Run() {
// init orm shell
if shell.InitShell() {os.Exit(0)}
// init templates and assets
initTemplatesAndAssets(router)
// init server
Expand All @@ -78,8 +75,6 @@ func (router *Router) Run() {

// RunTLS start the server TLS
func (router *Router) RunTLS(certFile string,keyFile string) {
// init orm shell
if shell.InitShell() {os.Exit(0)}
// init templates and assets
initTemplatesAndAssets(router)
// init server
Expand Down
1 change: 1 addition & 0 deletions core/orm/benchmarks/benchmarks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ func init() {
r := kamux.Router{}
r.LoadEnv("../../../.env")
_ = orm.InitDB()
orm.UseCache=false
//migrate
err := orm.Migrate()
if logger.CheckError(err) {return}
Expand Down
3 changes: 1 addition & 2 deletions core/orm/builderM.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,6 @@ func (b *BuilderM) Insert(fields_comma_separated string, fields_values []any) (i
if con, ok := mDbNameConnection[b.database]; ok {
b.conn = con
} else {

b.conn = databases[0].Conn
}
}
Expand Down Expand Up @@ -399,7 +398,7 @@ func (b *BuilderM) Set(query string, args ...any) (int, error) {

func (b *BuilderM) Delete() (int, error) {
if b.tableName == "" {
return 0, errors.New("unable to find model, try orm.LinkModel before")
return 0, errors.New("unable to find model, try orm.AutoMigrate before")
}
if b.database == "" {
b.database=settings.GlobalConfig.DbName
Expand Down
Loading

0 comments on commit bc8a0f9

Please sign in to comment.