#!/usr/bin/env bash
openDatabase() {
	local			\
		populate_db

	[[ -f "$database" ]] || populate_db=1
	rm -f "$tempdir"/sqlite.{in,out}
	mkfifo "$tempdir"/sqlite.{in,out}
	stdbuf -o0 sqlite3 -bail 				\
		-newline $'::AtOM:SQL:EOL::\n'			\
		"$database"					\
		< "$tempdir/sqlite.in"				\
		| stdbuf -o0					\
		sed 's/::AtOM:SQL:EOL::/\x0/g;s/\(\x0\)\xA/\1/g'	\
		> "$tempdir/sqlite.out"	&
	db_pid=$!
	exec 3> "$tempdir"/sqlite.in
	exec 4< "$tempdir"/sqlite.out
	rm "$tempdir"/sqlite.{in,out}
	if (( debug > 2 ))
	then
		exec 5>&3
		exec 3> >(tee -a "$tempdir/debug.log" >&5)
	fi
	(( populate_db )) && cat $schema >&3
	echo '.separator ::AtOM:SQL:Sep::' >&3
	echo 'PRAGMA foreign_keys = ON;' >&3
	echo 'PRAGMA recursive_triggers = ON;' >&3
	echo 'PRAGMA temp_store = 2;' >&3
	echo 'PRAGMA locking_mode = EXCLUSIVE;' >&3
	read -u4 -r -d $'\0'
	unset REPLY
	checkDatabaseVersion
}
