add tests for sqlite migration

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

Reviewed By: alexsn

Differential Revision: D15875669

fbshipit-source-id: 5ddebe396b9683f364e91f2f9e6296e3659ff618
This commit is contained in:
Ariel Mashraki
2019-06-18 10:52:17 -07:00
committed by Facebook Github Bot
parent 5f0268e02c
commit 970a410b31
4 changed files with 176 additions and 17 deletions

View File

@@ -19,30 +19,36 @@ func (d *SQLite) Create(ctx context.Context, tables ...*Table) error {
if err != nil {
return err
}
if err := d.create(ctx, tx, tables...); err != nil {
return rollback(tx, fmt.Errorf("dialect/sqlite: %v", err))
}
return tx.Commit()
}
func (d *SQLite) create(ctx context.Context, tx dialect.Tx, tables ...*Table) error {
on, err := d.fkEnabled(ctx, tx)
if err != nil {
return fmt.Errorf("sql/sqlite: check foreign_keys pragma: %v", err)
return fmt.Errorf("check foreign_keys pragma: %v", err)
}
if !on {
// foreign_keys pragma is off, either enable it by execute "PRAGMA foreign_keys=ON"
// or add the following parameter in the connection string "_fk=1".
return fmt.Errorf("sql/sqlite: foreign_keys pragma is off: missing %q is the connection string", "_fk=1")
return fmt.Errorf("foreign_keys pragma is off: missing %q is the connection string", "_fk=1")
}
for _, t := range tables {
exist, err := d.tableExist(ctx, tx, t.Name)
if err != nil {
return rollback(tx, err)
return err
}
if exist {
continue
}
query, args := t.SQLite().Query()
if err := tx.Exec(ctx, query, args, new(sql.Result)); err != nil {
err = fmt.Errorf("sql/sqlite: create table %q: %v", t.Name, err)
return rollback(tx, err)
return fmt.Errorf("create table %q: %v", t.Name, err)
}
}
return tx.Commit()
return nil
}
func (d *SQLite) tableExist(ctx context.Context, tx dialect.Tx, name string) (bool, error) {
@@ -60,15 +66,15 @@ func (d *SQLite) fkEnabled(ctx context.Context, tx dialect.Tx) (bool, error) {
func (d *SQLite) exist(ctx context.Context, tx dialect.Tx, query string, args ...interface{}) (bool, error) {
rows := &sql.Rows{}
if err := tx.Query(ctx, query, args, rows); err != nil {
return false, fmt.Errorf("dialect/sqlite: reading schema information %v", err)
return false, fmt.Errorf("reading schema information %v", err)
}
defer rows.Close()
if !rows.Next() {
return false, fmt.Errorf("dialect/sqlite: no rows returned")
return false, fmt.Errorf("no rows returned")
}
var n int
if err := rows.Scan(&n); err != nil {
return false, fmt.Errorf("dialect/sqlite: scanning count")
return false, fmt.Errorf("scanning count")
}
return n > 0, nil
}