microsoft / go-sqlcmd

The new sqlcmd, CLI for SQL Server and Azure SQL (winget install sqlcmd / sqlcmd create mssql / sqlcmd open ads)
https://learn.microsoft.com/sql/tools/sqlcmd/go-sqlcmd-utility
MIT License
334 stars 58 forks source link

User's database default is not master or tempdb #284

Closed airtank20 closed 1 year ago

airtank20 commented 1 year ago

When using sqlcmd to start a container with a given database backup, the user's default database is changed to reflect the name of the database is restored in the create process. If the database is later renamed that breaks sqlcmd because the original database is no longer present. You either have to nuke/pave the container or know how to fix that from within sql.

--1. run this sqlcmd create mssql --using https://github.com/Microsoft/sql-server-samples/releases/download/wide-world-importers-v1.0/WideWorldImporters-Full.bak --accept-eula --2. connect to the container via ADS --3. run this Alter database [WideWorldImporters-Full] set single_user with rollback IMMEDIATE; Alter database [WideWorldImporters-Full] modify name = WideWorldImporters Alter database [WideWorldImporters] set multi_user with rollback IMMEDIATE; --4. Back to sqlcmd, you cannot connect with the user_name/password

Suggested Fix: alter login john with default_database = master or leave the user defaulted to master

stuartpa commented 1 year ago

We've added an Example to the sqlcmd query --help to help any user that runs into this to resolve it:

C:\src>sqlcmd query --help
Run a query against the current context

Usage:
  sqlcmd query [TEXT] [flags]

Examples:
...
# Set new default database
  sqlcmd query "ALTER LOGIN [stuartpa] WITH DEFAULT_DATABASE = [tempdb]" --database master

Also, #290 will have a full fix, in that the user will be able to specify the DB name in the --using flag, so don't need to rename later.

stuartpa commented 1 year ago

Fixed in 0.15.4 (--using now takes a ,tsql-db-name option), so rename not needed for this scenario.