cat << EOF > setup.sql
create user weather;
create database weather_journal;
grant all privileges on weather_journal.* to weather@localhost identified by 'pwd';
use weather_journal;
create table if not exists temperature_history (zip varchar(10), temp int, curr_date date, curr_time time);
create table if not exists climate_avg (zip varchar(10) primary key, average_temp int, count int);
EOF
Copied!
cat << EOF > weather.golf
%% /weather/insert public
get-param zip_code
get-param temperature
begin-transaction
run-query @weather_db = "insert into temperature_history (zip, temp, curr_date, curr_time) \
values ('%s', '%s', CURRENT_DATE(), CURRENT_TIME())" \
input zip_code, temperature no-loop error-text et
if-true et not-equal ""
@Error in inserting temperature history [<<print-out et>>]
rollback-transaction @weather_db
exit-handler
else-if
run-query @weather_db = "insert into climate_avg (zip, average_temp, count) values ('%s', '%s', 1) \
on duplicate key update count=count+1, average_temp=(average_temp*(count-1)+'%s')/count" \
input zip_code, temperature, temperature no-loop error-text et
if-true et not-equal ""
@Error in updating temperature average [<<print-out et>>]
rollback-transaction @weather_db
exit-handler
end-if
end-if
commit-transaction @weather_db
@Data stored and average updated.
%%
%% /weather/get-avg public
get-param zip_code
run-query @weather_db = "select temp, curr_date, curr_time from temperature_history \
where zip='%s' order by curr_date, curr_time asc" input zip_code output temp, date, time
print-format "Temp [%4ld] Date [%s %s]\n", #temp, date, time
end-query
run-query @weather_db = "select average_temp, count from climate_avg where zip='%s'" input zip_code output avg, count
@Average is [<<print-out avg>>] from the total of [<<print-out count>>] samples
end-query
%%
EOF
Copied!