Solution 1 is more flexible but solution 2 is more in keeping with the current scheme of adding a bunch of helper methods on DbMap. @jmoiron, do you have a preference or any other ideas?
Here is a patch for solution 2 that we use at @sourcegraph.
commit d1ea3bbd873a92d1df083f97f2e129d681f1c0a4
Author: Quinn Slack <qslack@qslack.com>
Date: Tue Apr 22 02:27:43 2014 -0700
DropTablesIfExists
diff --git a/dbmap.go b/dbmap.go
index 9580a10..17506ec 100644
--- a/dbmap.go
+++ b/dbmap.go
@@ -263,6 +263,20 @@ func (m *DbMap) DropTables() error {
return err
}
+// DropTablesIfExists iterates through TableMaps registered to this DbMap and
+// executes "drop table if exists" statements against the database for each.
+func (m *DbMap) DropTablesIfExists() error {
+ var err error
+ for i := range m.tables {
+ table := m.tables[i]
+ _, e := m.Exec(fmt.Sprintf("drop table if exists %s;", m.Dialect.QuoteField(table.TableName)))
+ if e != nil {
+ err = e
+ }
+ }
+ return err
+}
+
// Insert runs a SQL INSERT statement for each element in list. List
// items must be pointers, because any interface whose TableMap has an
// auto-increment PK will have its insert Id bound to the PK struct field,
Right now as best I can tell it's not possible to drop all tables registered to a DBMap if they exist.
There are 2 possible solutions:
tables []*TableMap
field onDbMap
.DropTablesIfExists
method toDbMap
.Solution 1 is more flexible but solution 2 is more in keeping with the current scheme of adding a bunch of helper methods on
DbMap
. @jmoiron, do you have a preference or any other ideas?Here is a patch for solution 2 that we use at @sourcegraph.