@@ -1499,6 +1499,12 @@ def echo_via_pager(self, text, color=None):
1499
1499
default = None ,
1500
1500
help = "Write all queries & output into a file, in addition to the normal output destination." ,
1501
1501
)
1502
+ @click .option (
1503
+ "--init-command" ,
1504
+ "init_command" ,
1505
+ type = str ,
1506
+ help = "SQL statement to execute after connecting." ,
1507
+ )
1502
1508
@click .argument ("dbname" , default = lambda : None , envvar = "PGDATABASE" , nargs = 1 )
1503
1509
@click .argument ("username" , default = lambda : None , envvar = "PGUSER" , nargs = 1 )
1504
1510
def cli (
@@ -1525,6 +1531,7 @@ def cli(
1525
1531
list_dsn ,
1526
1532
warn ,
1527
1533
ssh_tunnel : str ,
1534
+ init_command : str ,
1528
1535
log_file : str ,
1529
1536
):
1530
1537
if version :
@@ -1682,6 +1689,33 @@ def echo_error(msg: str):
1682
1689
# of conflicting sources
1683
1690
echo_error (e .args [0 ])
1684
1691
1692
+ # Merge init-commands: global, DSN-specific, then CLI-provided
1693
+ init_cmds = []
1694
+ # 1) Global init-commands
1695
+ global_section = pgcli .config .get ("init-commands" , {})
1696
+ for _ , val in global_section .items ():
1697
+ if isinstance (val , (list , tuple )):
1698
+ init_cmds .extend (val )
1699
+ elif val :
1700
+ init_cmds .append (val )
1701
+ # 2) DSN-specific init-commands
1702
+ if dsn :
1703
+ alias_section = pgcli .config .get ("alias_dsn.init-commands" , {})
1704
+ if dsn in alias_section :
1705
+ val = alias_section .get (dsn )
1706
+ if isinstance (val , (list , tuple )):
1707
+ init_cmds .extend (val )
1708
+ elif val :
1709
+ init_cmds .append (val )
1710
+ # 3) CLI-provided init-command
1711
+ if init_command :
1712
+ init_cmds .append (init_command )
1713
+ if init_cmds :
1714
+ click .echo ("Running init commands: %s" % "; " .join (init_cmds ))
1715
+ for cmd in init_cmds :
1716
+ # Execute each init command
1717
+ list (pgcli .pgexecute .run (cmd ))
1718
+
1685
1719
if list_databases :
1686
1720
cur , headers , status = pgcli .pgexecute .full_databases ()
1687
1721
0 commit comments