Commit b5fa7103 authored by Jason Moiron's avatar Jason Moiron

add upstream 2f8eadc19c53fece3b19247d937cd75ebc400e5f support for TruncateTables on all 3 dialects

parent 45cfa23e
......@@ -370,6 +370,19 @@ func (m *DbMap) TableForType(t reflect.Type) *TableMap {
return nil
}
// Truncate all tables in the DbMap
func (m *DbMap) TruncateTables() error {
var err error
for i := range m.tables {
table := m.tables[i]
_, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuoteField(table.TableName)))
if e != nil {
err = e
}
}
return err
}
func (m *DbMap) queryRow(query string, args ...interface{}) *sql.Row {
m.trace(query, args)
return m.Db.QueryRow(query, args...)
......
......@@ -42,6 +42,9 @@ type Dialect interface {
// SQL parsing exceptions by using a reserved word as a field name.
QuoteField(field string) string
// string used to truncate tables
TruncateClause() string
// Get the driver name from a dialect
DriverName() string
}
......@@ -126,6 +129,13 @@ func (d SqliteDialect) QuoteField(f string) string {
return `"` + f + `"`
}
// With sqlite, there technically isn't a TRUNCATE statement,
// but a DELETE FROM uses a truncate optimization:
// http://www.sqlite.org/lang_delete.html
func (d SqliteDialect) TruncateClause() string {
return "delete from"
}
///////////////////////////////////////////////////////
// PostgreSQL //
////////////////
......@@ -222,6 +232,10 @@ func (d PostgresDialect) QuoteField(f string) string {
return `"` + strings.ToLower(f) + `"`
}
func (d PostgresDialect) TruncateClause() string {
return "truncate"
}
///////////////////////////////////////////////////////
// MySQL //
///////////
......@@ -319,3 +333,7 @@ func ReBind(query string, dialect Dialect) string {
}
return query
}
func (m MySQLDialect) TruncateClause() string {
return "truncate"
}
......@@ -711,6 +711,38 @@ func initDbMap() *DbMap {
return dbmap
}
func TestTruncateTables(t *testing.T) {
dbmap := initDbMap()
defer dbmap.DropTables()
err := dbmap.CreateTablesIfNotExists()
if err != nil {
t.Error(err)
}
// Insert some data
p1 := &Person{0, 0, 0, "Bob", "Smith", 0}
dbmap.Insert(p1)
inv := &Invoice{0, 0, 1, "my invoice", 0, true}
dbmap.Insert(inv)
err = dbmap.TruncateTables()
if err != nil {
t.Error(err)
}
// Make sure all rows are deleted
people := []Person{}
invoices := []Invoice{}
dbmap.Select(&people, "SELECT * FROM person_test")
if len(people) != 0 {
t.Errorf("Expected 0 person rows, got %d", len(people))
}
dbmap.Select(&invoices, "SELECT * FROM invoice_test")
if len(invoices) != 0 {
t.Errorf("Expected 0 invoice rows, got %d", len(invoices))
}
}
func TestQuoteTableNames(t *testing.T) {
dbmap := initDbMap()
defer dbmap.DropTables()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment