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
610
reform: путь к лучшему ORM
Alexey Palazhchenko
May 14, 2016
Tweet
Share
More Decks by Alexey Palazhchenko
See All by Alexey Palazhchenko
Песнь Хорьков и Гоферов
aleksi
0
310
Fuzzy generics
aleksi
0
110
On Ferrets and Gophers
aleksi
0
220
How to Go Wrong with Concurrency
aleksi
2
730
Adding context to existing code
aleksi
1
110
Зачем и как написать свой database/sql драйвер
aleksi
1
140
Cooking gRPC
aleksi
1
790
Profiling and Optimizing Go Programs
aleksi
1
1.7k
Go: начало
aleksi
0
92
Other Decks in Programming
See All in Programming
快速入門可觀測性
blueswen
0
400
[JAWS-UG横浜 #76] イケてるアップデートを宇宙いち早く紹介するよ!
maroon1st
0
500
Monixと常駐プログラムの勘どころ / Scalaわいわい勉強会 #4
stoneream
0
280
htmxって知っていますか?次世代のHTML
hiro_ghap1
0
350
モバイルアプリにおける自動テストの導入戦略
ostk0069
0
110
見えないメモリを観測する: PHP 8.4 `pg_result_memory_size()` とSQL結果のメモリ管理
kentaroutakeda
0
450
Exploring: Partial and Independent Composables
blackbracken
0
100
103 Early Hints
sugi_0000
1
250
開発者とQAの越境で自動テストが増える開発プロセスを実現する
92thunder
1
200
Fibonacci Function Gallery - Part 1
philipschwarz
PRO
0
220
17年周年のWebアプリケーションにTanStack Queryを導入する / Implementing TanStack Query in a 17th Anniversary Web Application
saitolume
0
250
【re:Growth 2024】 Aurora DSQL をちゃんと話します!
maroon1st
0
790
Featured
See All Featured
Navigating Team Friction
lara
183
15k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
28
2.1k
Docker and Python
trallard
42
3.1k
The Art of Programming - Codeland 2020
erikaheidi
53
13k
Stop Working from a Prison Cell
hatefulcrawdad
267
20k
Building Your Own Lightsaber
phodgson
103
6.1k
Side Projects
sachag
452
42k
Into the Great Unknown - MozCon
thekraken
33
1.5k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
665
120k
Code Reviewing Like a Champion
maltzj
521
39k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
59k
BBQ
matthewcrist
85
9.4k
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