Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
reform: путь к лучшему ORM
Search
Alexey Palazhchenko
May 14, 2016
Programming
2
640
reform: путь к лучшему ORM
Alexey Palazhchenko
May 14, 2016
Tweet
Share
More Decks by Alexey Palazhchenko
See All by Alexey Palazhchenko
Using PostgreSQL's Background Worker Processes For Fun and Profit
aleksi
0
100
Песнь Хорьков и Гоферов
aleksi
0
350
Fuzzy generics
aleksi
0
150
On Ferrets and Gophers
aleksi
0
240
How to Go Wrong with Concurrency
aleksi
2
760
Adding context to existing code
aleksi
1
130
Зачем и как написать свой database/sql драйвер
aleksi
1
170
Cooking gRPC
aleksi
1
860
Profiling and Optimizing Go Programs
aleksi
1
1.7k
Other Decks in Programming
See All in Programming
実践!App Intents対応
yuukiw00w
1
350
Terraform やるなら公式スタイルガイドを読もう 〜重要項目 10選〜
hiyanger
13
3.2k
Scale out your Claude Code ~自社専用Agentで10xする開発プロセス~
yukukotani
9
2.6k
AIコーディングAgentとの向き合い方
eycjur
0
230
フロントエンドのmonorepo化と責務分離のリアーキテクト
kajitack
2
140
Honoアップデート 2025年夏
yusukebe
1
860
CSC305 Summer Lecture 06
javiergs
PRO
0
100
RDoc meets YARD
okuramasafumi
2
120
Google I/O recap web編 大分Web祭り2025
kponda
0
2.9k
管你要 trace 什麼、bpftrace 用下去就對了 — COSCUP 2025
shunghsiyu
0
470
Langfuseと歩む生成AI活用推進
licux
3
300
tool ディレクティブを導入してみた感想
sgash708
1
150
Featured
See All Featured
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
8
480
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
50
5.5k
The MySQL Ecosystem @ GitHub 2015
samlambert
251
13k
GitHub's CSS Performance
jonrohan
1031
460k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
9
780
Six Lessons from altMBA
skipperchong
28
4k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
26
3k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
358
30k
Imperfection Machines: The Place of Print at Facebook
scottboms
268
13k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Java REST API Framework Comparison - PWX 2021
mraible
33
8.8k
Transcript
reform путь к лучшему ORM Алексей Палажченко mc² software
None
Цели database/sql src/database/sql/doc.txt • generic database API for SQL/SQL-like, feel
like Go • common cases, portable, no quirks • consistent but flexible type conversions • concurrency, thread safety, built-in pool • push complexity to drivers via optional interfaces
Интерфейс database/sql • DB: Open, Close, Begin, Prepare, Driver •
DB, Stmt, Tx: Query, QueryRow, Exec • Rows: Next, Scan, Err, Close • Result: LastInsertId, RowsAffected • NullBool, NullInt64, NullFloat64, NullString • Scanner: Scan(src interface{}) error
INSERT result, err := db.Exec( "INSERT INTO users (name) "+
"VALUES ($1)", "gopher" )
SELECT defer rows.Close() for rows.Next() { var name string if
e := rows.Scan(&name); e != nil { log.Fatal(e) } fmt.Println(name) } if e := rows.Err(); e != nil { log.Fatal(e) }
Интерфейс database/sql/driver • Value: пустой интерфейс • ValueConverter: ConvertValue(v interface{})
(Value, error) • Valuer: Value() (Value, error)
database/sql/driver.Value • nil • int64 • float64 • bool •
[]byte (non-nil) • string everywhere except from Rows.Next. #6497 • time.Time (боль с часовыми зонами)
Свои типы func (j JSONText) Value() (driver.Value, error) { if
j == nil { return nil, nil } var m json.RawMessage err := json.Unmarshal(j, &m) if err != nil { return []byte{}, err } return []byte(j), nil }
Свои типы func (j *JSONText) Scan(value interface{}) error { if
value == nil { *j = nil return nil } v, ok := value.([]byte) if !ok { return fmt.Errorf("error") } *j = JSONText(append((*j)[0:0], v...)) return nil }
Драйвера • github.com/golang/go/wiki/SQLDrivers • github.com/bradfitz/go-sql-test
Зачем ORM?
INSERT result, err := db.Exec( "INSERT INTO users (name) "+
"VALUES ($1)", "gopher" )
SELECT defer rows.Close() for rows.Next() { var name string if
e := rows.Scan(&name); e != nil { log.Fatal(e) } fmt.Println(name) } if e := rows.Err(); e != nil { log.Fatal(e) }
ORM • Не-ORM / малые ORM (например, отображение Scan строк
в структуры) • Большие ORM
ORM func Save(m interface{}) error
ORM Save(User{Name: "gopher"}) Save(&User{Name: "gopher"}) Save(nil) Save(42) Save("Batman!!")
Идея: struct для данных type Person struct { ID int64
`sql:"id,omitempty"` Name string `sql:"name,omitempty"` }
Идея: непустые интерфейсы type Record interface { Values() []interface{} Pointers()
[]interface{} PrimaryKeyPointer() interface{} SetPrimaryKey(id interface{}) Table() Table } funс Save(record Record) error
Идея: генерация кода • struct и код из XML •
XML из information_schema • struct пишется, код генерируется из него
Проблемы: Go vs SQL • SQL: значения по-умолчанию • SQL:
отсутствие в запросе • Go: zero value
person := &Person{ Name: "gopher", } if err := DB.Save(person);
err != nil { log.Fatal(err) }
Что почитать • Документацию database/sql/… • Код database/sql/… • github.com/mc2soft/pq-types
• github.com/AlekSi/reform
• https://groups.google.com/forum/#!forum/golang-ru • http://www.meetup.com/Golang-Moscow/ • http://4gophers.ru • http://4gophers.ru/slack • https://golangshow.com