Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
reform: путь к лучшему ORM
Search
Alexey Palazhchenko
May 14, 2016
Programming
660
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
reform: путь к лучшему ORM
Alexey Palazhchenko
May 14, 2016
More Decks by Alexey Palazhchenko
See All by Alexey Palazhchenko
Using PostgreSQL's Background Worker Processes For Fun and Profit
aleksi
0
210
Песнь Хорьков и Гоферов
aleksi
0
400
Fuzzy generics
aleksi
0
200
On Ferrets and Gophers
aleksi
0
300
How to Go Wrong with Concurrency
aleksi
2
830
Adding context to existing code
aleksi
1
190
Зачем и как написать свой database/sql драйвер
aleksi
1
220
Cooking gRPC
aleksi
1
940
Profiling and Optimizing Go Programs
aleksi
1
1.8k
Other Decks in Programming
See All in Programming
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
370
Vibes Containers 〜AIで変わるコンテナ設計と運用〜
tkikuc
3
550
技術的負債を組織課題として解く-増えすぎたマイクロサービスとの戦い-
reimaru
1
1.8k
技術的負債の返済は、AI時代の複利で効く投資 — 経営としての意思決定とその遂行
curekoshimizu
0
1.3k
Jetpack Compose メカニズム
skydoves
0
420
「新人AI禁止のその先へ ― 参加と協働のステップアップ」Vibe TOKYO, AI & CRAFT / 2026年8月21日
kentarowada
0
100
【高い買い物LT会】初任給で話題の国産フィジカルAIを買った話
akagami
PRO
0
160
更なる可用性を求めて、5年間運用したKotlinのアプリケーションをGoでリプレイスする話
ken_tunc
0
230
20260914 AIエージェント時代のPlatform Engineering LLM基盤とプロダクトの責務境界線
kanfab1
6
1.9k
スマート反転とウェブアクセシビリティ
camiha
0
210
XHTMLが残したもの
yosuke_furukawa
PRO
2
800
From 6 People Classroom Meetup to 100 People Regional Conference / FOSS4G Hiroshima 2026
furukawayasuto
0
200
Featured
See All Featured
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.6k
The untapped power of vector embeddings
frankvandijk
2
1.9k
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
2
2.9k
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
330
The Language of Interfaces
destraynor
162
27k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
700
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.6k
The World Runs on Bad Software
bkeepers
PRO
72
12k
KATA
mclloyd
PRO
35
15k
Building the Perfect Custom Keyboard
takai
2
870
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
67
58k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
17k
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