-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgreSQL_Review_Full_Check_Script.sql
More file actions
14103 lines (12649 loc) · 932 KB
/
Copy pathPostgreSQL_Review_Full_Check_Script.sql
File metadata and controls
14103 lines (12649 loc) · 932 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
====================================================================================
PostgreSQL Review - Template Header
Purpose: Collect PostgreSQL system introduction information.
This header collects:
- PostgreSQL server and cluster identity
- PostgreSQL version and build information
- PostgreSQL distribution/flavor best-effort detection
- Execution context
- Basic host information visible from PostgreSQL
- Important PostgreSQL configuration values
- Databases list
- Tablespaces list
- Installed extensions
- Current database statistics snapshot
- Current activity summary
- Replication / recovery high-level state
- PostgreSQL licensing note
- Header collection errors, if any
Important:
This file should be included at the beginning of the generated script: PostgreSQL_Review_Full_Check_Script.sql
Expected flow:
Template_Header.sql
SQLChecks\*.sql
Template_Footer.sql
Output:
This header does not return the final Review output.
Final JSON output is generated by Template_Footer.sql.
Important PostgreSQL limitation:
PostgreSQL does not expose full operating system and hardware inventory through standard SQL.
The following information is usually not available from SQL alone:
- Number of sockets
- Cores per socket
- Total physical memory
- NUMA layout
- Virtualization type
- Detailed operating system version
These values should be collected from the OS, cloud provider, VM platform,
monitoring platform, or customer documentation when required.
PostgreSQL documentation:
https://www.postgresql.org/docs/current/
System information functions:
https://www.postgresql.org/docs/current/functions-info.html
Monitoring statistics:
https://www.postgresql.org/docs/current/monitoring-stats.html
Server configuration:
https://www.postgresql.org/docs/current/runtime-config.html
System catalogs:
https://www.postgresql.org/docs/current/catalogs.html
====================================================================================
*/
/*
====================================================================================
Header section 1 - Cleanup previous temporary objects
Purpose: Drop temporary tables from a previous execution in the same session.
Allows this script to be re-run in the same session, for example from pgAdmin.
====================================================================================
*/
DROP TABLE IF EXISTS pg_review_header_server_identity;
DROP TABLE IF EXISTS pg_review_header_host_visibility;
DROP TABLE IF EXISTS pg_review_header_execution_context;
DROP TABLE IF EXISTS pg_review_header_distribution_detection;
DROP TABLE IF EXISTS pg_review_header_important_settings;
DROP TABLE IF EXISTS pg_review_header_licensing;
DROP TABLE IF EXISTS pg_review_header_databases;
DROP TABLE IF EXISTS pg_review_header_current_database_session;
DROP TABLE IF EXISTS pg_review_header_tablespaces;
DROP TABLE IF EXISTS pg_review_header_extensions;
DROP TABLE IF EXISTS pg_review_header_database_statistics;
DROP TABLE IF EXISTS pg_review_header_activity_summary;
DROP TABLE IF EXISTS pg_review_header_replication_state;
DROP TABLE IF EXISTS pg_review_header_capabilities;
DROP TABLE IF EXISTS pg_review_header_errors;
DROP TABLE IF EXISTS pg_review_results;
DROP TABLE IF EXISTS pg_review_errors;
/*
====================================================================================
Header section 2 - Create output tables
Purpose: Create all output tables before collecting data.
Why: If a specific collection section fails, the relevant table still exists and the final SELECT statements will not fail.
====================================================================================
*/
-- Temp table for Header collection errors
CREATE TEMP TABLE pg_review_header_errors
(
SectionName text,
ErrorMessage text,
ErrorTime timestamptz DEFAULT now()
);
-- Temp table for PostgreSQL server and cluster identity information
CREATE TEMP TABLE pg_review_header_server_identity
(
PostgreSQLClusterName text,
CurrentDatabaseName text,
PostgreSQLVersion text,
PostgreSQLVersionNum text,
PostgreSQLFullVersionString text,
ServerIPAddress text,
ServerPort integer,
PostgreSQLStartTime timestamptz,
PostgreSQLUptime interval,
IsInRecovery boolean,
TransactionReadOnly text,
DataDirectory text,
ConfigFile text,
HbaFile text,
IdentFile text
);
-- Temp table for host and operating system information visible from PostgreSQL
CREATE TEMP TABLE pg_review_header_host_visibility
(
ServerIPAddress text,
ServerPort integer,
ClientIPAddress text,
ClientPort integer,
PostgreSQLBuildAndHostString text,
OperatingSystemName text,
OperatingSystemRelease text,
OperatingSystemArchitecture text,
VirtualizationType text,
NumOfSockets integer,
CoresPerSocket integer,
HostNumOfCores integer,
NumOfNUMAs integer,
PhysicalMemory_GB numeric,
HostResourceCollectionNote text
);
-- Temp table for the Review execution context and current user permissions
CREATE TEMP TABLE pg_review_header_execution_context
(
CurrentUser text,
SessionUser text,
CurrentDatabaseName text,
CanLogin boolean,
IsSuperuser boolean,
CanCreateDatabase boolean,
CanCreateRole boolean,
HasReplicationPrivilege boolean,
CanBypassRowLevelSecurity boolean,
HasPgMonitor boolean,
HasPgReadAllStats boolean,
HasPgReadAllSettings boolean,
HasPgStatScanTables boolean
);
-- Temp table for PostgreSQL distribution and managed-service detection
CREATE TEMP TABLE pg_review_header_distribution_detection
(
PostgreSQLDistributionFlavor text,
DetectionConfidence text,
PostgreSQLVersion text,
PostgreSQLVersionNum text,
HasRdsAdminRole boolean,
HasRdsAdminDatabase boolean,
RdsExtensionsSettingExists boolean,
HasRdsToolsExtension boolean,
HasAwsCommonsExtension boolean,
HasAwsS3Extension boolean,
HasAzurePgAdminRole boolean,
AzureExtensionsSettingExists boolean,
HasAzureStorageExtension boolean,
HasCloudSqlSuperuserRole boolean,
CloudSqlPglogicalSettingExists boolean,
HasGoogleMlIntegrationExtension boolean,
EdbRedwoodDateSettingExists boolean,
HasPgStatStatementsExtension boolean,
DetectionNote text
);
-- Temp table for important PostgreSQL configuration settings
CREATE TEMP TABLE pg_review_header_important_settings
(
SettingName text,
SettingValue text,
Unit text,
Category text,
Description text,
Context text,
ValueType text,
BootValue text,
ResetValue text,
Source text,
PendingRestart boolean
);
-- Temp table for PostgreSQL licensing information
CREATE TEMP TABLE pg_review_header_licensing
(
LicensingCategory text,
LicensingInformation text,
LicensingNote text
);
-- Temp table for the PostgreSQL databases list
CREATE TEMP TABLE pg_review_header_databases
(
DatabaseName text,
OwnerName text,
AllowConnections boolean,
IsTemplate boolean,
ConnectionLimit integer,
DatabaseEncoding text,
DatabaseCollation text,
DatabaseCType text,
DatabaseSize text,
DatabaseSizeBytes bigint
);
-- Temp table for current database session settings
CREATE TEMP TABLE pg_review_header_current_database_session
(
DatabaseName text,
ClientEncoding text,
ServerEncoding text,
DateStyle text,
TimeZone text,
IntervalStyle text,
StandardConformingStrings text,
DefaultTransactionIsolation text,
CurrentTransactionIsolation text,
TransactionReadOnly text,
StatementTimeout text,
LockTimeout text,
IdleInTransactionSessionTimeout text,
SearchPath text
);
-- Temp table for PostgreSQL tablespaces information
CREATE TEMP TABLE pg_review_header_tablespaces
(
TablespaceName text,
OwnerName text,
TablespaceLocation text,
TablespaceOptions text[]
);
-- Temp table for installed extensions in the current database
CREATE TEMP TABLE pg_review_header_extensions
(
ExtensionName text,
ExtensionVersion text,
SchemaName text,
IsRelocatable boolean
);
-- Temp table for current database statistics snapshot
CREATE TEMP TABLE pg_review_header_database_statistics
(
DatabaseName text,
CurrentBackends integer,
TransactionsCommitted bigint,
TransactionsRolledBack bigint,
BlocksReadFromDisk bigint,
BlocksHitInCache bigint,
CacheHitPercent numeric,
TuplesReturned bigint,
TuplesFetched bigint,
TuplesInserted bigint,
TuplesUpdated bigint,
TuplesDeleted bigint,
Conflicts bigint,
TempFiles bigint,
TempBytes text,
TempBytesRaw bigint,
Deadlocks bigint,
BlockReadTimeMs double precision,
BlockWriteTimeMs double precision,
StatisticsResetTime timestamptz
);
-- Temp table for current PostgreSQL activity summary
CREATE TEMP TABLE pg_review_header_activity_summary
(
TotalConnections bigint,
ActiveConnections bigint,
IdleConnections bigint,
IdleInTransactionConnections bigint,
SessionsWaitingOnLocks bigint,
DistinctUsers bigint,
DistinctApplications bigint,
DistinctClientAddresses bigint,
OldestBackendStart timestamptz,
OldestTransactionStart timestamptz,
OldestQueryStart timestamptz
);
-- Temp table for replication and recovery state summary
CREATE TEMP TABLE pg_review_header_replication_state
(
IsInRecovery boolean,
WalLevel text,
ArchiveMode text,
MaxWalSenders text,
MaxReplicationSlots text,
WalKeepSize text,
ConnectedStandbyCount bigint,
ReplicationSlotCount bigint,
ActiveReplicationSlotCount bigint
);
-- Temp table for optional PostgreSQL capabilities and feature availability
CREATE TEMP TABLE pg_review_header_capabilities
(
CapabilityName text,
IsAvailable boolean
);
-- Temp table for PostgreSQL Review check results
CREATE TEMP TABLE pg_review_results
(
CheckId integer PRIMARY KEY,
Title text NOT NULL,
Category text NOT NULL,
Scope text NOT NULL,
RequiresAttention boolean NOT NULL,
WorstCaseImpact integer NOT NULL,
CurrentStateImpact integer NOT NULL,
RecommendationEffort integer NOT NULL,
RecommendationRisk integer NOT NULL,
Recommendation text NOT NULL,
AdditionalInfo jsonb NOT NULL DEFAULT '{}'::jsonb,
ResponsibleDbaTeam text NOT NULL DEFAULT 'Production/Development'
);
-- Temp table for PostgreSQL Review check execution errors.
CREATE TEMP TABLE pg_review_errors
(
CheckId integer,
Title text,
ErrorSqlState text,
ErrorMessage text,
ErrorDetail text,
ErrorHint text,
ErrorContext text,
IsDeadlockRetry boolean DEFAULT false,
ErrorTime timestamptz DEFAULT now()
);
/*
====================================================================================
Header section 3 - PostgreSQL Server / Cluster Identity
Purpose: Basic PostgreSQL identity information.
Notes: PostgreSQL cluster can contain multiple databases.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_server_identity
SELECT
COALESCE(NULLIF(current_setting('cluster_name', true), ''), 'Not provided') AS PostgreSQLClusterName,
current_database() AS CurrentDatabaseName,
current_setting('server_version', true) AS PostgreSQLVersion,
current_setting('server_version_num', true) AS PostgreSQLVersionNum,
version() AS PostgreSQLFullVersionString,
inet_server_addr()::text AS ServerIPAddress,
inet_server_port() AS ServerPort,
pg_postmaster_start_time() AS PostgreSQLStartTime,
now() - pg_postmaster_start_time() AS PostgreSQLUptime,
pg_is_in_recovery() AS IsInRecovery,
current_setting('transaction_read_only', true) AS TransactionReadOnly,
current_setting('data_directory', true) AS DataDirectory,
current_setting('config_file', true) AS ConfigFile,
current_setting('hba_file', true) AS HbaFile,
current_setting('ident_file', true) AS IdentFile;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('PostgreSQL Server / Cluster Identity', SQLERRM);
END $$;
/*
====================================================================================
Header section 4 - Host / Operating System Visibility from PostgreSQL
Purpose: Provide host-related information that is visible from PostgreSQL.
Important: PostgreSQL does not expose full OS/hardware inventory through standard SQL.
CPU count, sockets, cores per socket, NUMA, physical memory, and virtualization
type should be collected from OS/cloud/monitoring tools when needed.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_host_visibility
SELECT
inet_server_addr()::text AS ServerIPAddress,
inet_server_port() AS ServerPort,
inet_client_addr()::text AS ClientIPAddress,
inet_client_port() AS ClientPort,
version() AS PostgreSQLBuildAndHostString,
'Not available from standard PostgreSQL SQL'::text AS OperatingSystemName,
'Not available from standard PostgreSQL SQL'::text AS OperatingSystemRelease,
'Not available from standard PostgreSQL SQL'::text AS OperatingSystemArchitecture,
'Not available from standard PostgreSQL SQL'::text AS VirtualizationType,
NULL::integer AS NumOfSockets,
NULL::integer AS CoresPerSocket,
NULL::integer AS HostNumOfCores,
NULL::integer AS NumOfNUMAs,
NULL::numeric AS PhysicalMemory_GB,
'Collect OS and hardware details from operating system, cloud provider, VM platform, container platform, or monitoring tool.'::text AS HostResourceCollectionNote;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Host / Operating System Visibility from PostgreSQL', SQLERRM);
END $$;
/*
====================================================================================
Header section 5 - Execution Context
Purpose: Identify who executed the Review and what privileges are visible.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_execution_context
SELECT
current_user AS CurrentUser,
session_user AS SessionUser,
current_database() AS CurrentDatabaseName,
r.rolcanlogin AS CanLogin,
r.rolsuper AS IsSuperuser,
r.rolcreatedb AS CanCreateDatabase,
r.rolcreaterole AS CanCreateRole,
r.rolreplication AS HasReplicationPrivilege,
r.rolbypassrls AS CanBypassRowLevelSecurity,
pg_has_role(current_user, 'pg_monitor', 'member') AS HasPgMonitor,
pg_has_role(current_user, 'pg_read_all_stats', 'member') AS HasPgReadAllStats,
pg_has_role(current_user, 'pg_read_all_settings', 'member') AS HasPgReadAllSettings,
pg_has_role(current_user, 'pg_stat_scan_tables', 'member') AS HasPgStatScanTables
FROM pg_roles r
WHERE r.rolname = current_user;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Execution Context', SQLERRM);
END $$;
/*
====================================================================================
Header section 6 - PostgreSQL Distribution / Flavor Detection
Purpose: Best-effort detection of PostgreSQL distribution/flavor.
Detects signals for:
- Community PostgreSQL or unknown
- Amazon RDS for PostgreSQL / Amazon Aurora PostgreSQL
- Azure Database for PostgreSQL
- Google Cloud SQL for PostgreSQL
- EDB Postgres Advanced Server
Important:
This is best-effort detection from SQL only.
Managed services may hide internal details.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_distribution_detection
WITH settings AS
(
SELECT
current_setting('server_version', true) AS server_version,
current_setting('server_version_num', true) AS server_version_num,
current_setting('rds.extensions', true) AS rds_extensions,
current_setting('azure.extensions', true) AS azure_extensions,
current_setting('cloudsql.enable_pglogical', true) AS cloudsql_enable_pglogical,
current_setting('edb_redwood_date', true) AS edb_redwood_date
),
extensions AS
(
SELECT
bool_or(extname = 'rds_tools') AS has_rds_tools,
bool_or(extname = 'aws_commons') AS has_aws_commons,
bool_or(extname = 'aws_s3') AS has_aws_s3,
bool_or(extname = 'azure_storage') AS has_azure_storage,
bool_or(extname = 'google_ml_integration') AS has_google_ml_integration,
bool_or(extname = 'pg_stat_statements') AS has_pg_stat_statements
FROM pg_extension
),
roles AS
(
SELECT
bool_or(rolname = 'rdsadmin') AS has_rdsadmin_role,
bool_or(rolname = 'azure_pg_admin') AS has_azure_pg_admin_role,
bool_or(rolname = 'cloudsqlsuperuser') AS has_cloudsqlsuperuser_role
FROM pg_roles
),
databases AS
(
SELECT
bool_or(datname = 'rdsadmin') AS has_rdsadmin_database
FROM pg_database
)
SELECT
CASE
WHEN settings.server_version ILIKE '%EnterpriseDB%'
OR settings.server_version ILIKE '%EDB%'
OR settings.edb_redwood_date IS NOT NULL
THEN 'EDB Postgres Advanced Server'
WHEN roles.has_rdsadmin_role
OR databases.has_rdsadmin_database
OR settings.rds_extensions IS NOT NULL
OR extensions.has_rds_tools
OR extensions.has_aws_commons
OR extensions.has_aws_s3
THEN
CASE
WHEN settings.server_version ILIKE '%aurora%'
THEN 'Amazon Aurora PostgreSQL'
ELSE 'Amazon RDS for PostgreSQL or Amazon Aurora PostgreSQL'
END
WHEN roles.has_azure_pg_admin_role
OR settings.azure_extensions IS NOT NULL
OR extensions.has_azure_storage
THEN 'Azure Database for PostgreSQL'
WHEN roles.has_cloudsqlsuperuser_role
OR settings.cloudsql_enable_pglogical IS NOT NULL
OR extensions.has_google_ml_integration
THEN 'Google Cloud SQL for PostgreSQL'
ELSE 'PostgreSQL Community or unknown distribution'
END AS PostgreSQLDistributionFlavor,
CASE
WHEN settings.server_version ILIKE '%EnterpriseDB%'
OR settings.server_version ILIKE '%EDB%'
OR settings.edb_redwood_date IS NOT NULL
OR roles.has_rdsadmin_role
OR databases.has_rdsadmin_database
OR roles.has_azure_pg_admin_role
OR roles.has_cloudsqlsuperuser_role
THEN 'High'
WHEN settings.rds_extensions IS NOT NULL
OR settings.azure_extensions IS NOT NULL
OR settings.cloudsql_enable_pglogical IS NOT NULL
OR extensions.has_rds_tools
OR extensions.has_aws_commons
OR extensions.has_aws_s3
OR extensions.has_azure_storage
OR extensions.has_google_ml_integration
THEN 'Medium'
ELSE 'Best-effort detection'
END AS DetectionConfidence,
settings.server_version AS PostgreSQLVersion,
settings.server_version_num AS PostgreSQLVersionNum,
COALESCE(roles.has_rdsadmin_role, false) AS HasRdsAdminRole,
COALESCE(databases.has_rdsadmin_database, false) AS HasRdsAdminDatabase,
settings.rds_extensions IS NOT NULL AS RdsExtensionsSettingExists,
COALESCE(extensions.has_rds_tools, false) AS HasRdsToolsExtension,
COALESCE(extensions.has_aws_commons, false) AS HasAwsCommonsExtension,
COALESCE(extensions.has_aws_s3, false) AS HasAwsS3Extension,
COALESCE(roles.has_azure_pg_admin_role, false) AS HasAzurePgAdminRole,
settings.azure_extensions IS NOT NULL AS AzureExtensionsSettingExists,
COALESCE(extensions.has_azure_storage, false) AS HasAzureStorageExtension,
COALESCE(roles.has_cloudsqlsuperuser_role, false) AS HasCloudSqlSuperuserRole,
settings.cloudsql_enable_pglogical IS NOT NULL AS CloudSqlPglogicalSettingExists,
COALESCE(extensions.has_google_ml_integration, false) AS HasGoogleMlIntegrationExtension,
settings.edb_redwood_date IS NOT NULL AS EdbRedwoodDateSettingExists,
COALESCE(extensions.has_pg_stat_statements, false) AS HasPgStatStatementsExtension,
'Best-effort detection from SQL only. Validate with customer/provider documentation when required.'::text AS DetectionNote
FROM settings
CROSS JOIN extensions
CROSS JOIN roles
CROSS JOIN databases;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('PostgreSQL Distribution / Flavor Detection', SQLERRM);
END $$;
/*
====================================================================================
Header section 7 - Important PostgreSQL Configuration Values
Purpose: Collect important PostgreSQL settings for system introduction.
Values are shown for context only.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_important_settings
SELECT
name AS SettingName,
setting AS SettingValue,
unit AS Unit,
category AS Category,
short_desc AS Description,
context AS Context,
vartype AS ValueType,
boot_val AS BootValue,
reset_val AS ResetValue,
source AS Source,
pending_restart AS PendingRestart
FROM pg_settings
WHERE name IN
(
'max_connections',
'superuser_reserved_connections',
'reserved_connections',
'shared_buffers',
'effective_cache_size',
'work_mem',
'maintenance_work_mem',
'autovacuum_work_mem',
'autovacuum',
'autovacuum_max_workers',
'autovacuum_naptime',
'autovacuum_vacuum_threshold',
'autovacuum_vacuum_scale_factor',
'autovacuum_analyze_threshold',
'autovacuum_analyze_scale_factor',
'autovacuum_freeze_max_age',
'checkpoint_timeout',
'checkpoint_completion_target',
'max_wal_size',
'min_wal_size',
'wal_level',
'wal_compression',
'archive_mode',
'archive_command',
'archive_library',
'max_wal_senders',
'max_replication_slots',
'wal_keep_size',
'shared_preload_libraries',
'track_activities',
'track_counts',
'track_io_timing',
'track_wal_io_timing',
'log_min_duration_statement',
'log_temp_files',
'log_autovacuum_min_duration',
'log_checkpoints',
'log_lock_waits',
'deadlock_timeout',
'max_worker_processes',
'max_parallel_workers',
'max_parallel_workers_per_gather',
'statement_timeout',
'lock_timeout',
'idle_in_transaction_session_timeout',
'temp_file_limit',
'default_statistics_target',
'random_page_cost',
'seq_page_cost',
'effective_io_concurrency'
)
ORDER BY category, name;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Important PostgreSQL Configuration Values', SQLERRM);
END $$;
/*
====================================================================================
Header section 8 - PostgreSQL Licensing Information
Purpose: Provide licensing context.
Notes: PostgreSQL Community Edition is open-source and does not have per-core licensing limits.
Managed services and commercial distributions may have provider-specific pricing or subscription models.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_licensing
SELECT
'PostgreSQL License'::text AS LicensingCategory,
'PostgreSQL is released under the PostgreSQL License, a liberal open-source license.'::text AS LicensingInformation,
'PostgreSQL Community does not use socket/core licensing. Managed services and commercial distributions may have provider-specific pricing or subscriptions.'::text AS LicensingNote;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('PostgreSQL Licensing Information', SQLERRM);
END $$;
/*
====================================================================================
Header section 9 - Databases List
Purpose: List databases in the PostgreSQL cluster.
Notes: PostgreSQL has multiple databases inside a cluster.
Object-level checks usually apply only to the database where the script runs.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_databases
SELECT
d.datname::text AS DatabaseName,
pg_get_userbyid(d.datdba)::text AS OwnerName,
d.datallowconn AS AllowConnections,
d.datistemplate AS IsTemplate,
d.datconnlimit AS ConnectionLimit,
pg_encoding_to_char(d.encoding)::text AS DatabaseEncoding,
d.datcollate::text AS DatabaseCollation,
d.datctype::text AS DatabaseCType,
CASE
WHEN d.datallowconn THEN pg_size_pretty(pg_database_size(d.datname))
ELSE NULL
END AS DatabaseSize,
CASE
WHEN d.datallowconn THEN pg_database_size(d.datname)
ELSE NULL
END AS DatabaseSizeBytes
FROM pg_database d
ORDER BY d.datistemplate, d.datname;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Databases List', SQLERRM);
END $$;
/*
====================================================================================
Header section 10 - Current Database Session Defaults
Purpose: Show session/default values relevant to the current database connection.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_current_database_session
SELECT
current_database() AS DatabaseName,
current_setting('client_encoding', true) AS ClientEncoding,
current_setting('server_encoding', true) AS ServerEncoding,
current_setting('DateStyle', true) AS DateStyle,
current_setting('TimeZone', true) AS TimeZone,
current_setting('IntervalStyle', true) AS IntervalStyle,
current_setting('standard_conforming_strings', true) AS StandardConformingStrings,
current_setting('default_transaction_isolation', true) AS DefaultTransactionIsolation,
current_setting('transaction_isolation', true) AS CurrentTransactionIsolation,
current_setting('transaction_read_only', true) AS TransactionReadOnly,
current_setting('statement_timeout', true) AS StatementTimeout,
current_setting('lock_timeout', true) AS LockTimeout,
current_setting('idle_in_transaction_session_timeout', true) AS IdleInTransactionSessionTimeout,
current_setting('search_path', true) AS SearchPath;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Current Database Session Defaults', SQLERRM);
END $$;
/*
====================================================================================
Header section 11 - Tablespaces
Purpose: List PostgreSQL tablespaces.
Notes: PostgreSQL tablespaces represent locations in the filesystem.
Filesystem free space is not available through standard SQL.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_tablespaces
SELECT
t.spcname::text AS TablespaceName,
pg_get_userbyid(t.spcowner)::text AS OwnerName,
pg_tablespace_location(t.oid)::text AS TablespaceLocation,
t.spcoptions AS TablespaceOptions
FROM pg_tablespace t
ORDER BY t.spcname;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Tablespaces', SQLERRM);
END $$;
/*
====================================================================================
Header section 12 - Installed Extensions in Current Database
Purpose: List extensions installed in the current database.
Notes: Extensions are database-level in PostgreSQL.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_extensions
SELECT
e.extname::text AS ExtensionName,
e.extversion::text AS ExtensionVersion,
n.nspname::text AS SchemaName,
e.extrelocatable AS IsRelocatable
FROM pg_extension e
JOIN pg_namespace n
ON n.oid = e.extnamespace
ORDER BY e.extname;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Installed Extensions in Current Database', SQLERRM);
END $$;
/*
====================================================================================
Header section 13 - Current Database Statistics Snapshot
Purpose: Show high-level statistics for the current database.
Notes: These counters are cumulative since statistics reset.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_database_statistics
SELECT
datname::text AS DatabaseName,
numbackends AS CurrentBackends,
xact_commit AS TransactionsCommitted,
xact_rollback AS TransactionsRolledBack,
blks_read AS BlocksReadFromDisk,
blks_hit AS BlocksHitInCache,
CASE
WHEN blks_hit + blks_read > 0
THEN round((blks_hit::numeric / (blks_hit + blks_read)) * 100, 2)
ELSE NULL
END AS CacheHitPercent,
tup_returned AS TuplesReturned,
tup_fetched AS TuplesFetched,
tup_inserted AS TuplesInserted,
tup_updated AS TuplesUpdated,
tup_deleted AS TuplesDeleted,
conflicts AS Conflicts,
temp_files AS TempFiles,
pg_size_pretty(temp_bytes) AS TempBytes,
temp_bytes AS TempBytesRaw,
deadlocks AS Deadlocks,
blk_read_time AS BlockReadTimeMs,
blk_write_time AS BlockWriteTimeMs,
stats_reset AS StatisticsResetTime
FROM pg_stat_database
WHERE datname = current_database();
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Current Database Statistics Snapshot', SQLERRM);
END $$;
/*
====================================================================================
Header section 14 - Activity Summary
Purpose: Provide high-level current connection/session summary.
Notes: This is a runtime snapshot.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_activity_summary
SELECT
count(*) AS TotalConnections,
count(*) FILTER (WHERE state = 'active') AS ActiveConnections,
count(*) FILTER (WHERE state = 'idle') AS IdleConnections,
count(*) FILTER (WHERE state = 'idle in transaction') AS IdleInTransactionConnections,
count(*) FILTER (WHERE wait_event_type = 'Lock') AS SessionsWaitingOnLocks,
count(DISTINCT usename) AS DistinctUsers,
count(DISTINCT application_name) AS DistinctApplications,
count(DISTINCT client_addr) AS DistinctClientAddresses,
min(backend_start) AS OldestBackendStart,
min(xact_start) FILTER (WHERE xact_start IS NOT NULL) AS OldestTransactionStart,
min(query_start) FILTER (WHERE query_start IS NOT NULL) AS OldestQueryStart
FROM pg_stat_activity;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Activity Summary', SQLERRM);
END $$;
/*
====================================================================================
Header section 15 - Replication and Recovery State
Purpose: Provide high-level replication/recovery information.
Notes: This is not a replication health check.
It is only system introduction information.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_replication_state
SELECT
pg_is_in_recovery() AS IsInRecovery,
current_setting('wal_level', true) AS WalLevel,
current_setting('archive_mode', true) AS ArchiveMode,
current_setting('max_wal_senders', true) AS MaxWalSenders,
current_setting('max_replication_slots', true) AS MaxReplicationSlots,
current_setting('wal_keep_size', true) AS WalKeepSize,
(
SELECT count(*)
FROM pg_stat_replication
) AS ConnectedStandbyCount,
(
SELECT count(*)
FROM pg_replication_slots
) AS ReplicationSlotCount,
(
SELECT count(*)
FROM pg_replication_slots
WHERE active
) AS ActiveReplicationSlotCount;
EXCEPTION WHEN OTHERS THEN
INSERT INTO pg_review_header_errors(SectionName, ErrorMessage)
VALUES ('Replication and Recovery State', SQLERRM);
END $$;
/*
====================================================================================
Header section 16 - Capability Summary
Purpose: Show which optional PostgreSQL capabilities/views/extensions are available.
This is useful for understanding what later checks can use.
====================================================================================
*/
DO $$
BEGIN
INSERT INTO pg_review_header_capabilities
SELECT
'pg_stat_statements extension installed in current database' AS CapabilityName,
EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements') AS IsAvailable
UNION ALL
SELECT
'pg_stat_statements view visible',
to_regclass('public.pg_stat_statements') IS NOT NULL
OR to_regclass('pg_catalog.pg_stat_statements') IS NOT NULL
UNION ALL
SELECT
'pg_stat_checkpointer view available',
to_regclass('pg_catalog.pg_stat_checkpointer') IS NOT NULL
UNION ALL
SELECT
'pg_stat_io view available',
to_regclass('pg_catalog.pg_stat_io') IS NOT NULL
UNION ALL
SELECT
'pg_stat_wal view available',
to_regclass('pg_catalog.pg_stat_wal') IS NOT NULL
UNION ALL
SELECT
'Current user has pg_monitor',
pg_has_role(current_user, 'pg_monitor', 'member')
UNION ALL
SELECT
'Current user has pg_read_all_stats',
pg_has_role(current_user, 'pg_read_all_stats', 'member')
UNION ALL
SELECT