Skip to content

Commit a563cc4

Browse files
committed
scripts: use trap to make sure old files always restored
In this commit, we fix an issue I observed on my machine after updating many command line/dev utilities. I observed that if the script failed for w/e reason, then the old files weren't properly restored. The repro on my machine is something like: 1. Shutdown docker, make sure the daemon isn't accessible. 2. Run `mac sqlc`. The script should fail. 3. Observe that the files in your local working tree are still altered. We fix this by using the `trap` command, [which is basically like Go's `defer`, but for bash scripts](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html)!
1 parent d81bd74 commit a563cc4

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

scripts/gen_sqlc_docker.sh

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,23 @@
22

33
set -e
44

5+
# restore_files is a function to restore original schema files.
6+
restore_files() {
7+
echo "Restoring SQLite bigint patch..."
8+
for file in tapdb/sqlc/migrations/*.up.sql.bak; do
9+
mv "$file" "${file%.bak}"
10+
done
11+
}
12+
13+
# Set trap to call restore_files on script exit. This makes sure the old files
14+
# are always restored.
15+
trap restore_files EXIT
16+
517
# Directory of the script file, independent of where it's called from.
6-
DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
18+
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
719
# Use the user's cache directories
8-
GOCACHE=`go env GOCACHE`
9-
GOMODCACHE=`go env GOMODCACHE`
20+
GOCACHE=$(go env GOCACHE)
21+
GOMODCACHE=$(go env GOMODCACHE)
1022

1123
# SQLite doesn't support "BIGINT PRIMARY KEY" for auto-incrementing primary
1224
# keys, only "INTEGER PRIMARY KEY". Internally it uses 64-bit integers for
@@ -19,23 +31,18 @@ GOMODCACHE=`go env GOMODCACHE`
1931
# PRIMARY KEY".
2032
echo "Applying SQLite bigint patch..."
2133
for file in tapdb/sqlc/migrations/*.up.sql; do
22-
echo "Patching $file"
23-
sed -i.bak -E 's/INTEGER PRIMARY KEY/BIGINT PRIMARY KEY/g' "$file"
34+
echo "Patching $file"
35+
sed -i.bak -E 's/INTEGER PRIMARY KEY/BIGINT PRIMARY KEY/g' "$file"
2436
done
2537

26-
2738
echo "Generating sql models and queries in go..."
2839

40+
# Run the script to generate the new generated code. Once the script exits, we
41+
# use `trap` to make sure all files are restored.
2942
docker run \
30-
--rm \
31-
--user "$UID:$(id -g)" \
32-
-e UID=$UID \
33-
-v "$DIR/../:/build" \
34-
-w /build \
35-
sqlc/sqlc:1.25.0 generate
36-
37-
# Restore the original schema files.
38-
echo "Restoring SQLite bigint patch..."
39-
for file in tapdb/sqlc/migrations/*.up.sql.bak; do
40-
mv "$file" "${file%.bak}"
41-
done
43+
--rm \
44+
--user "$UID:$(id -g)" \
45+
-e UID=$UID \
46+
-v "$DIR/../:/build" \
47+
-w /build \
48+
sqlc/sqlc:1.25.0 generate

0 commit comments

Comments
 (0)