10.3.2 데이터베이스 초기화
웹 애플리케이션이 구동될 때 데이터베이스를 초기화해야 한다. app/controller 디렉터리에 init.go 파일을 생성하고 다음과 같이 코드를 작성하자.
▼ app/controllers/init.go
package controllers import ( "github.com/revel/modules/db/app" "github.com/revel/revel" ) func InitDB() { db.Init() schema := ` CREATE TABLE IF NOT EXISTS posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ` db.Db.Exec(schema) } func init() { revel.OnAppStart(InitDB) }
컨트롤러 모듈의 초기화 함수인 init() 함수에서 revel.OnAppStart(InitDB)를 호출하여 Revel 웹 애플리케이션이 구동될 때 InitDB() 함수를 실행한다. InitDB() 함수에서는 Revel의 기본 db 모듈을 초기화한 다음 posts 테이블을 생성한다.