Skip to content

Commit

Permalink
Merge pull request #44 from gobuffalo/task-postgres-delete
Browse files Browse the repository at this point in the history
Task postgres delete
  • Loading branch information
paganotoni authored May 6, 2021
2 parents 6efb867 + fd74b04 commit 5c761b3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
go-version: [1.13.x, 1.14.x]
go-version: [1.15.x, 1.16.x]
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout Code
Expand Down
37 changes: 36 additions & 1 deletion model.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Model struct {
func (m *Model) SetupTest() {
m.Assertions = require.New(m.T())
if m.DB != nil {
err := m.DB.TruncateAll()
err := m.CleanDB()
m.NoError(err)
}
}
Expand Down Expand Up @@ -96,3 +96,38 @@ func (m *Model) Run(name string, subtest func()) bool {
subtest()
})
}

// CleanDB clears records from the database, this function is
// useful to run before tests to ensure other tests are not
// affecting the one running.
func (m *Model) CleanDB() error {
if m.DB == nil {
return nil
}

switch m.DB.Dialect.Name() {
case "postgres":
deleteAllQuery := `DO
$func$
DECLARE
_tbl text;
_sch text;
BEGIN
FOR _sch, _tbl IN
SELECT schemaname, tablename
FROM pg_tables
WHERE tablename <> '%s' AND schemaname NOT IN ('pg_catalog', 'information_schema') AND tableowner = current_user
LOOP
--RAISE ERROR '%%',
EXECUTE -- dangerous, test before you execute!
format('DELETE FROM %%I.%%I CASCADE', _sch, _tbl);
END LOOP;
END
$func$;`

q := m.DB.RawQuery(fmt.Sprintf(deleteAllQuery, m.DB.MigrationTableName()))
return q.Exec()
default:
return m.DB.TruncateAll()
}
}

0 comments on commit 5c761b3

Please sign in to comment.