mirror of
https://github.com/ent/ent.git
synced 2026-05-28 09:49:08 +03:00
entc/gen: generate sql builders with dialect option
Summary: Pull Request resolved: https://github.com/facebookincubator/ent/pull/130 Reviewed By: alexsn Differential Revision: D18164397 fbshipit-source-id: 2858d69d3ff85c06b51382c01c3d4369ee2c3bdb
This commit is contained in:
committed by
Facebook Github Bot
parent
ea479ea527
commit
c259aee24b
40
entc/gen/template/dialect/sql/globals.tmpl
Normal file
40
entc/gen/template/dialect/sql/globals.tmpl
Normal file
@@ -0,0 +1,40 @@
|
||||
{{/*
|
||||
Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
This source code is licensed under the Apache 2.0 license found
|
||||
in the LICENSE file in the root directory of this source tree.
|
||||
*/}}
|
||||
|
||||
{{/* custom globals and helpers for sql dialects */}}
|
||||
{{ define "dialect/sql/globals" }}
|
||||
// insertLastID invokes the insert query on the transaction and returns the LastInsertID.
|
||||
func insertLastID(ctx context.Context, tx dialect.Tx, insert *sql.InsertBuilder) (int64, error) {
|
||||
query, args := insert.Query()
|
||||
// PostgreSQL does not support the LastInsertId() method of sql.Result
|
||||
// on Exec, and should be extracted manually using the `RETURNING` clause.
|
||||
if insert.Dialect() == dialect.Postgres {
|
||||
rows := &sql.Rows{}
|
||||
if err := tx.Query(ctx, query, args, rows); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
if !rows.Next() {
|
||||
return 0, fmt.Errorf("no rows found for query: %v", query)
|
||||
}
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
// MySQL, SQLite, etc.
|
||||
var res sql.Result
|
||||
if err := tx.Exec(ctx, query, args, &res); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
{{ end }}
|
||||
Reference in New Issue
Block a user