Replacing GORM's Default SQLite Driver for Static Compilation
Recently, while developing a program using GORM to interact with an SQLite database, I encountered issues with GORM's default driver, gorm.io/driver/sqlite, which is implemented using CGO. After facing several problems, I decided to switch to a third-party SQLite driver to resolve them.

The Problem
Since the official GORM SQLite driver relies on CGO, I encountered the following error during development:
[error] failed to initialize database, got error Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub panic: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub
The error indicates that the GORM SQLite driver requires a CGO-enabled environment to function.
The solution seems straightforward: simply enable CGO support by modifying the CGO_ENABLED environment variable:
go env -w CGO_ENABLED=1
However, enabling CGO results in compiling a binary file that dynamically links libraries. If you attempt to run this binary on a different platform, such as Windows, it may fail due to missing dynamic libraries (e.g., SQLite). To ensure the compiled binary runs without dynamic dependencies, static compilation is necessary. This requirement conflicts with the official GORM SQLite driver.
Solution: Replace GORM's Default SQLite Driver
While investigating GORM's official Issues, I found similar reports. Following the thread, I discovered the github.com/glebarez/sqlite library. This library is implemented entirely in Go and does not depend on CGO. You can find it here: https://github.com/glebarez/sqlite.
To implement this solution, replace the official driver import:
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
With the third-party driver:
import (
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
This change allows you to compile static binary files without CGO dependencies, effectively solving the cross-platform dynamic library issue.
Trade-offs
- Performance: The
glebarez/sqlitedriver does not perform as well as the official driver. However, sacrificing a small amount of performance for the convenience of static compilation is worth it. If you do not have cross-platform requirements, the default official driver remains a viable option. - File Size: The static binary files produced after packaging are significantly larger in size.