Search code examples
mysqlscalasqueryl

How can I delete all records from a table with squeryl?


I've looked at ways to use squeryl to delete all records from a table. The only thing I could come up with is

myTable.deleteWhere(r => r.id.isNotNull)  //id is the primary key

This seems strange and possibly inefficient.

What is the cleanest way to delete all records from a table when using squeryl?


Solution

  • The deleteWhere clause takes any logical boolean, so you could simply say:

    myTable.deleteWhere(r => 1 === 1) 
    

    Which should output the statement:

    DELETE FROM mytable WHERE 1 = 1
    

    If you want to eliminate the where clause automatically, you could try:

    myTable.deleteWhere(r => 1 === 1.inhibitWhen(true))
    

    Which should suppress the where clause altogether.

    If you are looking for an even more efficient method and your database supports TRUNCATE or another equivalent function, you can get a java.sql.Connection from org.squeryl.Session and issue the query directly through JDBC. Unfortunately, this would lose some of the type safety Squeryl offers.