#!/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.

Insert() {
#Insert table [no_id] <	key value
#			[key value
#			[…]]
#
# If no_id is set to a non-zero value, the function will not return the
# auto-assigned row ID of the inserted row. 
	local			\
		table="$1"	\
		no_id="${2:-0}"	\
		insert_keys	\
		insert_values	\
		results
	# Build column list and value list from stdin key-value pairs
	while read key value
	do
		(( ${#insert_keys} )) && insert_keys+=","
		insert_keys+='`'"$key"'`'
		(( ${#insert_values} )) && insert_values+=","
		case $value in
			'::AtOM:FT::'*)
				# Force-text prefix: strip the marker and quote
				# as string (prevents numeric-looking values
				# from being stored as int / float)
				value="${value//::AtOM:FT::/}"
				insert_values+='"'"${value//\"/\"\"}"'"'
			;;
			'NULL')
				# Insert SQL NULL (not the string "NULL")
				insert_values+="NULL"
			;;
			+([0-9])?(.+([0-9])))
				# Pure integer or decimal: insert unquoted for
				# numeric storage
				insert_values+=$value
			;;
			*)
				# General string: restore encoded newlines,
				# then quote
				value=${value//::AtOM:NewLine:SQL:Inline::/$'\n'}
				insert_values+='"'"${value//\"/\"\"}"'"'
			;;
		esac
	done
	echo	"INSERT INTO $table"				\
				"( $insert_keys )"		\
			"VALUES"				\
				"( $insert_values );" >&3
	# Unless no_id is set, return the auto-assigned row ID
	(( no_id )) || {
		echo 'SELECT LAST_INSERT_ROWID();' >&3
		read -u4 -r -d $'\0' results
		echo "$results"
	}
}
