Reputation: 194
I have a .sql file that has all the create statements for the tables in my database (ie CREATE TABLE X, CREATE INDEX Y, CREATE UNIQUE INDEX Z). Is it possible to write a makefile that can easily run this code and generate the tables?
Additionally, would it be possible to connect this to Xcode so that when I run my app the database is created?
Upvotes: 0
Views: 2334
Reputation: 318794
Use sqlite3_exec
to run your sql
file at runtime in your app. Of course you only want to do it once. You need to use sqlite2_open_v2
to open a new database file first, then execute the sql
file.
If you want to generate the database file in Xcode during a build, you can do this after some setup. I do this in one of my projects.
Start by selecting your target in Xcode and going to the "Build Phases" tab. Then click on the "Add Build Phase" button and select "Add Run Script". Double-click on the "Run Script" title and rename it to something useful such as "Generate db file".
Change the "shell" value to "/bin/bash".
Use the following for the script:
cd database
if [ create.sql -nt data.db ]; then
rm -rf empty.db
fi
if [ ! -e data.db ]; then
sqlite3 data.db < create.sql
fi
cd -
You probably need to change a few details of this script. Given that the script will be run from the root directory of your project, change the first line (cd database
) to reflect where your sql
file is within your own project. Then change any references to create.sql
to match the name of your own sql
file. And last, change any references to data.db
to match what you want your database file to be named.
The last step is to move this build phase to before the "Copy Bundle Resources" phase. Also make sure the db
file ends up in your resources.
The script will update the db
file any time the sql
file is updated.
Upvotes: 3