Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support "drop tables if exists" #27

Open
sqs opened this issue Oct 19, 2014 · 0 comments
Open

Support "drop tables if exists" #27

sqs opened this issue Oct 19, 2014 · 0 comments

Comments

@sqs
Copy link
Contributor

sqs commented Oct 19, 2014

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:

  1. Exporting the tables []*TableMap field on DbMap.
  2. Adding a DropTablesIfExists method to DbMap.

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,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant