百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
K

korm

> 数据库
开源

KORM 是一个优雅且极其快速的 ORM,可满足您所有的并发和异步需求。受到广受欢迎的 Django 框架的启发,KORM 提供了类似的功能。

184 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

KORM 是一个优雅且极其快速的 ORM,可满足您所有的并发和异步需求。受到广受欢迎的 Django 框架的启发,KORM 提供了类似的功能。


Introducing Korm - the elegant, lightning-fast ORM/Framework for all your needs, see benchmarks. Inspired by the highly popular Django Framework, Korm offers similar functionality with the added bonus of performance

It is also composable, allowing for integration with a network websocket PubSub using WithBus when you want to synchronise your data between multiple Korm or WithDashboard to have a complete setup of server bus and Admin Dashboard.

Why settle for less when you can have the best ?

  • Django become very hard to work with when you need concurrency and async, you will need django channels and a server like daphne or uvicorn, Go have the perfect implementation
  • Django can handle at most 300 request per second, Go handle 44,000 requests per second (benchmarks done on my machine)
  • The API is also more user-friendly and less verbose than Django's
  • Deploying an executable binary file using Korm , with automatic TLS Let's encrypt, a built-in Admin Dashboard, Interactive Shell, Eventbus to communicate between multiple Korm applications is pretty neat
  • Additionally, its caching system uses goroutines and channels to efficiently to clean the cache when rows or tables are created, updated, deleted, or dropped

It Has :

  • New: When using korm.WithDashboard, now you have access to all logs in realtime (websockets) from admin dashboard when you log using lg pkg. By default only 10 last logs are keeped in memory, you can increase it using lg.SaveLogs(50) for keeping last 50 logs

  • New: Handle Nested or Embeded structs and slice of structs through joins, like sqlx, but sqlx doesn't handle slice of structs

  • New: korm.QueryNamed, QueryNamedS, korm.ExecNamed, korm.ExecContextNamed and WhereNamed(query string, args map[string]any) like :Where("email = :email",map[string]any{"email":"[email protected]"})

  • New: korm.LogsQueries() that log statements and time tooked by sql queries

  • Auto Docs with Model API and video tutoriel

  • Swagger Documentation and tutorial

  • PPROF Go profiling tool and Metrics Prometheus

  • Logs Middleware

  • Admin dashboard with ready offline and installable PWA (using /static/sw.js and /static/manifest.webmanifest). All statics mentionned in sw.js will be cached and served by the service worker, you can inspect the Network Tab in the browser to check it

  • Shared Network Bus allowing you to send and recv data in realtime using pubsub websockets between your ORMs, so you can decide how you data will be distributed between different databases, see Example

  • Built-in Authentication using korm.Auth , korm.Admin or korm.BasicAuth middlewares, whenever Auth and Admin middlewares are used, you get access to the .User model and variable .IsAuthenticated from any template html like this example admin_nav.html

  • Interactive Shell, to CRUD in your databases from command line, use korm.WithShell() , ⚠️ if dashboard used, korm.WithShell should be after WithDashboard

  • AutoMigrate directly from struct

  • Compatible with official database/sql, so you can do your queries yourself using sql.DB `korm.GetConnection()``, and overall a painless integration of your existing codebases using database/sql

  • Router/Mux accessible from the serverBus after calling korm.WithBus(...opts) or korm.WithDashboard(addr, ...opts)

  • Hooks : OnInsert OnSet OnDelete and OnDrop

  • many to many relationships

  • GENERATED ALWAYS AS tag added (all dialects)

  • Concatination and Length support for Where and for tags: check and generated (all dialects)

  • Support for foreign keys, indexes , checks,... See all

  • Kenv load env vars to struct

  • Python Bus Client pip install ksbus

All drivers concurrent safe read and write

Supported databases:

  • Sqlite
  • Mysql
  • Maria
  • Postgres
  • Cockroach

Installation

bash
go get -u github.com/kamalshkeir/korm@latest

Drivers moved outside this package to not get them all in your go.mod file

bash
go get -u github.com/kamalshkeir/sqlitedriver@latest
go get -u github.com/kamalshkeir/pgdriver@latest
go get -u github.com/kamalshkeir/mysqldriver@latest

Global Vars

go
// Debug when true show extra useful logs for queries executed for migrations and queries statements
Debug = false
// FlushCacheEvery execute korm.FlushCache() every 10 min by default, you should not worry about it, but useful that you can change it
FlushCacheEvery = 10 * time.Minute
// SetCacheMaxMemory set max size of each cache cacheAllS AllM ...
korm.SetCacheMaxMemory(megaByte int) // default maximum of 50 Mb , cannot be lower
// Connection pool
MaxOpenConns = 20
MaxIdleConns = 20
MaxLifetime = 30 * time.Minute
MaxIdleTime = 15 * time.Minute

Connect to a database

go
// sqlite
// go get github.com/kamalshkeir/sqlitedriver
err := korm.New(korm.SQLITE, "dbName", sqlitedriver.Use()) // Connect
// postgres, cockroach
// go get github.com/kamalshkeir/pgdriver
err := korm.New(korm.POSTGRES,"dbName", pgdriver.Use(), "user:password@localhost:5432") // Connect
// mysql, maria
// go get github.com/kamalshkeir/mysqldriver
err := korm.New(korm.MYSQL,"dbName", mysqldriver.Use(), "user:password@localhost:3306") // Connect

korm.Shutdown(databasesName ...string) error

Hello world example

…

AutoMigrate

Available Tags (SQL)

SQL:

…

Builder map[string]any:

…

Dashboard defaults you can set

go
korm.PaginationPer      = 10
korm.DocsUrl           = "docs"
korm.EmbededDashboard   = false
korm.MediaDir           = "media"
korm.AssetsDir          = "assets"
korm.StaticDir          = path.Join(AssetsDir, "/", "static")
korm.TemplatesDir       = path.Join(AssetsDir, "/", "templates")
korm.RepoUser           = "kamalshkeir"
korm.RepoName           = "korm-dash"
korm.adminPathNameGroup = "/admin" // korm.SetAdminPath("/another")
// so you can create a custom dashboard, upload it to your repos and change like like above korm.RepoUser and korm.RepoName

Example With Dashboard (you don't need korm.WithBus with it, because WithDashboard already call it and return the server bus for you)

…

Then create admin user to connect to the dashboard

bash
go run main.go shell

createsuperuser

Then you can visit /admin

Auth middleware example

…

Example Admin Auth User and IsAuthenticated

xml
{{define "admin_nav"}}

  
    
      
KORM

     
    
    

        

          Home
        

        

          Admin
        

        {{if .IsAuthenticated}}
            

              Logout
            

            
            {{if .User.Email}}
              

                Hello {{.User.Email}}
              

            {{end}}
        {{end}}
    

  

{{end}}

Admin middlewares

…

Example With Bus between 2 KORM

KORM 1:

…

KORM 2:

…

Example generated tag

…

Example concat and len from korm_test.go

go
// Where example
func TestConcatANDLen(t *testing.T) {
	groupes, err := Model[Group]().Where("name = concat(?,'min') AND len(name) = ?", "ad", 5).Debug().All()
	// translated to select * from groups WHERE name = 'ad' || 'min'  AND  length(name) = 5 (sqlite)
	// translated to select * from groups WHERE name = concat('ad','min')  AND  char_length(name) = 5 (postgres, mysql)
	if err != nil {
		t.Error(err)
	}
	if len(groupes) != 1 || groupes[0].Name != "admin" {
		t.Error("len(groupes) != 1 , got: ", groupes)
	}
}

Router/Mux

Learn more about Ksmux

go
func main() {
	err := korm.New(korm.SQLITE, "db", sqlitedriver.Use())
	if err != nil {
		log.Fatal(err)
	}

	serverBus := korm.WithDashboard("localhost:9313")
	korm.WithShell() // ⚠️ if dashboard used, korm.WithShell should be after WithDashboard
	mux := serverBus.App
	// add global middlewares
	mux.Use((midws ...func(http.Handler) http.Handler))
	...
}

Pprof

go

serverBus := korm.WithDashboard("localhost:9313")
// or srv := korm.WithBus()
serverBus.WithPprof(path ...string) // path is 'debug' by default

will enable:
	- /debug/pprof
	- /debug/profile
	- /debug/heap
	- /debug/trace

To execute profile cpu: go tool pprof -http=":8000" pprofbin http://localhost:9313/debug/profile?seconds=18 To execute profile memory: go tool pprof -http=":8000" pprofbin http://localhost:9313/debug/heap?seconds=18 To execute generate trace: go to endpoint http://localhost:9313/debug/trace?seconds=18 from browser , this will download the trace of 18 seconds Then to see the trace : go tool trace path/to/trace

Metrics Prometheus

go
// or srv := korm.WithBus()
//srv.WithMetrics(httpHandler http.Handler, path ...string) path default to 'metrics'
srv.WithMetrics(promhttp.Handler())

will enable:
	- /metrics

Logs middleware

go
// or srv := korm.WithBus()
//srv.WithMetrics(httpHandler http.Handler, path ...string) path default to 'metrics'
srv.App.Use(ksmux.Logs()) // it take an optional callback executed on each request if you want to add log to a file or send
srv.App.Use(ksmux.Logs(func(method, path, remote string, status int, took time.Duration) {
	// save somewhere
}))

will enable:
	- /metrics

Hooks

go
korm.OnInsert(func(database, table string, data map[string]any) error {
	fmt.Println("inserting into", database, table, data)
	// if error returned, it will not insert
	return nil
})

korm.OnSet(func(database, table string, data map[string]any) error {
	fmt.Println("set into", database, table, data)
	return nil
})

korm.OnDelete(func(database, table, query string, args ...any) error {})

korm.OnDrop(func(database, table string) error {})

Python bus client example

bash
pip install ksbus==1.1.0
# if it doesn't work , execute it again 
…

ManyToMany Relationships Example

…

Swagger documentation

go
korm.DocsUrl = "docs" // default endpoint '/docs' 
korm.BASIC_AUTH_USER = "test"
korm.BASIC_AUTH_PASS = "pass"
korm.WithDocs(generate, dirPath, korm.BasicAuth)
korm.WithDocs(true, "", korm.BasicAuth) // dirPath default to 'assets/static/docs'
korm.WithEmbededDocs(embeded embed.FS, dirPath, korm.BasicAuth)
// dirPath default to 'assets/static/docs' if empty

Interactive shell

…

Example, not required, Load config from env directly to struct using Kenv

…

Example nested or embeded structs

…

Benchmark vs Tarantool, Pgx, Gorm

https://github.com/kamalshkeir/korm-vs-gorm-vs-tarantool-vs-pgx

Benchmarks vs Gorm

bash
goos: windows
goarch: amd64
pkg: github.com/kamalshkeir/korm/benchmarks
cpu: Intel(R) Core(TM) i5-7300HQ CPU @ 2.50GHz

To execute these benchmarks on your machine, very easy :

  • git clone https://github.com/kamalshkeir/korm.git
  • cd korm
  • uncomment commented code at benchmarks/bench-test.go and Save
  • go mod tidy
  • go test -bench ^ .\benchmarks\ -benchmem
…

Available Tags by struct field type:

String Field:

Without parameter          &n

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Goadminadmin-dashboardblazingly-fastbuilder

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库