entc/gen: add open func for creating client

Summary: Pull Request resolved: https://github.com/facebookincubator/ent/pull/44

Reviewed By: alexsn

Differential Revision: D17657719

fbshipit-source-id: 9bbe18dc0e9c553f8a2df81018d7db06f38f5e0e
This commit is contained in:
Ariel Mashraki
2019-10-02 01:39:14 -07:00
committed by Facebook Github Bot
parent 86a6fbe48e
commit cb1f78f233
35 changed files with 525 additions and 70 deletions

View File

@@ -39,6 +39,23 @@ func NewClient(opts ...Option) *Client {
}
}
// Open opens a connection to the database specified by the driver name and a
// driver-specific data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// Tx returns a new transactional client.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
@@ -74,6 +91,11 @@ func (c *Client) Debug() *Client {
}
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// UserClient is a client for the User schema.
type UserClient struct {
config

View File

@@ -8,7 +8,6 @@ import (
"context"
"testing"
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/entc/integration/idtype/ent"
"github.com/facebookincubator/ent/entc/integration/idtype/ent/migrate"
"github.com/facebookincubator/ent/entc/integration/idtype/ent/user"
@@ -17,11 +16,10 @@ import (
)
func TestIDType(t *testing.T) {
drv, err := sql.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
require.NoError(t, err)
defer drv.Close()
defer client.Close()
ctx := context.Background()
client := ent.NewClient(ent.Driver(drv))
require.NoError(t, client.Schema.Create(ctx, migrate.WithGlobalUniqueID(true)))
a8m := client.User.Create().SetName("a8m").SaveX(ctx)