GuidesProtectionsSQL Operation

SQL Operation

To prevent SQL injection, use the drivers and hooks provided by Waffle.

When using database/sql

To prevent SQL injection, use the waffle-go/contrib/database/sql package.
The context must pass through the Waffle HTTP server middleware.

import (
    ...
    waffleSQL "github.com/sitebatch/waffle-go/contrib/database/sql"
    _ "github.com/mattn/go-sqlite3" // or any other database driver
    ...
)
 
db, err := waffleSQL.Open("sqlite3", "file::memory:?cache=shared")
if err != nil {
    panic(err)
}
 
// ctx MUST be a context propagated from Waffle HTTP server middleware such as WafMiddleware
db.QueryContext(ctx, query)

More information can be found in the contrib/databse/sql.

When using GORM

GORM v2 is supported by Waffle.

import (
	waffleSql "github.com/sitebatch/waffle-go/contrib/database/sql"
	"gorm.io/driver/sqlite"
)
 
_, err := waffleSql.Register(sqlite.DriverName)
sqlDB, err := waffleSql.Open(sqlite.DriverName, dsn)
db, err := gorm.Open(sqlite.New(sqlite.Config{Conn: sqlDB}), &gorm.Config{})
 
result := db.WithContext(ctx).Where(fmt.Sprintf("code = '%s'", "D42') OR 1=1--")).First(&product)

More information can be found in the contrib/gorm.io/gorm.