4646
4747echo " Restoring TeslaMate database backup: $backup_file "
4848
49+ prepare_database_for_restore () {
50+ psql -v ON_ERROR_STOP=1 --username " $POSTGRES_USER " --dbname " $POSTGRES_DB " << 'SQL '
51+ DROP SCHEMA IF EXISTS public CASCADE;
52+ DROP SCHEMA IF EXISTS private CASCADE;
53+ CREATE SCHEMA public;
54+ CREATE EXTENSION IF NOT EXISTS cube WITH SCHEMA public;
55+ CREATE EXTENSION IF NOT EXISTS earthdistance WITH SCHEMA public;
56+ SQL
57+ }
58+
4959restore_dump_or_sql () {
5060 candidate=" $1 "
5161
@@ -56,6 +66,41 @@ restore_dump_or_sql() {
5666 fi
5767}
5868
69+ clear_restored_teslamate_tokens () {
70+ echo " Clearing restored TeslaMate API tokens so this instance can be authorized fresh."
71+
72+ psql -v ON_ERROR_STOP=1 --username " $POSTGRES_USER " --dbname " $POSTGRES_DB " << 'SQL '
73+ DO $$
74+ DECLARE
75+ token_table record;
76+ cleared_count integer := 0;
77+ BEGIN
78+ FOR token_table IN
79+ SELECT table_schema, table_name
80+ FROM information_schema.tables
81+ WHERE table_name = 'tokens'
82+ AND table_schema IN ('private', 'public')
83+ AND table_type = 'BASE TABLE'
84+ LOOP
85+ EXECUTE format(
86+ 'TRUNCATE TABLE %I.%I RESTART IDENTITY CASCADE',
87+ token_table.table_schema,
88+ token_table.table_name
89+ );
90+ cleared_count := cleared_count + 1;
91+ RAISE NOTICE 'Cleared restored TeslaMate tokens from %.%', token_table.table_schema, token_table.table_name;
92+ END LOOP;
93+
94+ IF cleared_count = 0 THEN
95+ RAISE NOTICE 'No TeslaMate tokens table found to clear.';
96+ END IF;
97+ END
98+ $$;
99+ SQL
100+ }
101+
102+ prepare_database_for_restore
103+
59104case " $backup_file " in
60105 * .sql|* .bck)
61106 restore_dump_or_sql " $backup_file "
@@ -81,4 +126,6 @@ case "$backup_file" in
81126 ;;
82127esac
83128
129+ clear_restored_teslamate_tokens
130+
84131echo " TeslaMate database backup restore completed."
0 commit comments