#!/bin/bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

Select() {
#Select table [col1 [col2 [..]]] <	WHERE_key WHERE_operator WHERE_value
#					[WHERE_key WHERE_operator WHERE_value
#					[…]]
	local			\
		table="$1"	\
		col		\
		columns		\
		operator	\
		results		\
		where_statement
	shift
	# Build column list
	for col
	do
		(( ${#columns} )) && columns+=','
		columns+="$col"
	done
	# Build WHERE clause from stdin triplets
	while read key operator value
	do
		(( ${#where_statement} )) && where_statement+=( "AND" )
		# Restore encoded newlines before embedding in SQL
		value=${value//::AtOM:NewLine:SQL:Inline::/$'\n'}
		where_statement+=( "$key $operator "'"'"${value//\"/\"\"}"'"' )
	done
	# Use IFNULL so SQLite always produces output.
	echo	"SELECT IFNULL("				\
			"(SELECT $columns FROM $table"		\
				"WHERE ${where_statement[@]})"	\
			",'SQL::Select:not found'"		\
		");" >&3
	read -u 4 -r -d $'\0' results
	# Return exit code 1 if the sentinel value indicates no row was found
	if ! [[ $results == "SQL::Select:not found" ]]
	then
		echo "$results"
	else
		return 1
	fi
}
