1010import stat
1111from collections import namedtuple
1212
13+ from pygments .lexer import combined
14+
1315try :
1416 from pwd import getpwuid
1517except ImportError :
@@ -1262,9 +1264,13 @@ def cli(
12621264
12631265 dsn_uri = None
12641266
1265- # Treat the database argument as a DSN alias if we're missing
1266- # other connection information.
1267- if mycli .config ["alias_dsn" ] and database and "://" not in database and not any ([user , password , host , port , login_path ]):
1267+ # Treat the database argument as a DSN alias only if it matches a configured alias
1268+ if (
1269+ database
1270+ and "://" not in database
1271+ and not any ([user , password , host , port , login_path ])
1272+ and database in mycli .config .get ("alias_dsn" , {})
1273+ ):
12681274 dsn , database = database , ""
12691275
12701276 if database and "://" in database :
@@ -1306,6 +1312,29 @@ def cli(
13061312 ssh_key_filename = ssh_key_filename if ssh_key_filename else ssh_config .get ("identityfile" , [None ])[0 ]
13071313
13081314 ssh_key_filename = ssh_key_filename and os .path .expanduser (ssh_key_filename )
1315+ # Merge init-commands: global, DSN-specific, then CLI
1316+ init_cmds = []
1317+ # 1) Global init-commands
1318+ global_section = mycli .config .get ("init-commands" , {})
1319+ for _ , val in global_section .items ():
1320+ if isinstance (val , (list , tuple )):
1321+ init_cmds .extend (val )
1322+ elif val :
1323+ init_cmds .append (val )
1324+ # 2) DSN-specific init-commands
1325+ if dsn :
1326+ alias_section = mycli .config .get ("alias_dsn.init-commands" , {})
1327+ if dsn in alias_section :
1328+ val = alias_section .get (dsn )
1329+ if isinstance (val , (list , tuple )):
1330+ init_cmds .extend (val )
1331+ elif val :
1332+ init_cmds .append (val )
1333+ # 3) CLI-provided init_command
1334+ if init_command :
1335+ init_cmds .append (init_command )
1336+
1337+ combined_init_cmd = "; " .join (cmd .strip () for cmd in init_cmds if cmd )
13091338
13101339 mycli .connect (
13111340 database = database ,
@@ -1321,11 +1350,14 @@ def cli(
13211350 ssh_port = ssh_port ,
13221351 ssh_password = ssh_password ,
13231352 ssh_key_filename = ssh_key_filename ,
1324- init_command = init_command ,
1353+ init_command = combined_init_cmd ,
13251354 charset = charset ,
13261355 password_file = password_file ,
13271356 )
13281357
1358+ if combined_init_cmd :
1359+ click .echo ("Executing init-command: %s" % combined_init_cmd , err = True )
1360+
13291361 mycli .logger .debug ("Launch Params: \n " "\t database: %r" "\t user: %r" "\t host: %r" "\t port: %r" , database , user , host , port )
13301362
13311363 # --execute argument
0 commit comments