Bash based Busy Handler for Sqlite

Sqlite is a serverless database and hence doesn’t allow multiple synchronous write requests. Sqlite API for most programming languages have a busy handler functionality which lets you define a busy handler function or a timeout value, thus enabling your program to wait for a certain amount of time and then access the database again.

However no such functionality exists when you want to use sqlite through a bash script. Hence I implemented a pseudo busy handler for bash scripts.

function sqlite_query {
  local QUERY=$1
  local OUTPUT=""
  local RUN=1
  while [ "$RUN" = "1" ]; do
    OUTPUT=$(sqlite3 /PATH_TO_DB/SqliteDB "$QUERY" 2>>/dev/null)
    RETURNVAL="$?"
    if [ "$RETURNVAL" = "5" ]; then
      sleep 1;
    else
      RUN=O;
    fi
  done
  echo ${OUTPUT[@]}
}
export DB_COMMAND="sqlite_query"

This script allows you to use the $DB_COMMAND variable just like you would use the sqlite3 utility, no changes in syntax. When the DB is found busy, it will sleep for 1 second and try again till it can successfully access the DB.

About Pratik Sinha

Linux Nerd, Socialist, Atheist, Adventuristic, Nature Lover, Geeky.

Leave a Reply