{
    "metadata": {
        "kernelspec": {
            "name": "python3",
            "display_name": "Python 3"
        },
        "language_info": {
            "name": "python",
            "version": "3.7.3",
            "mimetype": "text/x-python",
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "pygments_lexer": "ipython3",
            "nbconvert_exporter": "python",
            "file_extension": ".py"
        }
    },
    "nbformat_minor": 2,
    "nbformat": 4,
    "cells": [
        {
            "cell_type": "markdown",
            "source": [
                "![Microsoft](https://raw.githubusercontent.com/microsoft/azuredatastudio/master/src/sql/media/microsoft-small-logo.png)\n",
                "## Run SQL Server 2019 container image with Docker\n",
                "This notebook will use Docker to pull and run the SQL Server 2019 container image and connect to it in Azure Data Studio\n",
                "\n",
                "### Dependencies\n",
                "- Docker Engine. For more information, see [Install Docker](https://docs.docker.com/engine/installation/).\n",
                "\n",
                "<span style=\"color:red\"><font size=\"3\">Please press the \"Run Cells\" button to run the notebook</font></span>"
            ],
            "metadata": {}
        },
        {
            "cell_type": "markdown",
            "source": "### Check dependencies",
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "import pandas,sys,os,getpass,json,html,time\n",
                "pandas_version = pandas.__version__.split('.')\n",
                "pandas_major = int(pandas_version[0])\n",
                "pandas_minor = int(pandas_version[1])\n",
                "pandas_patch = int(pandas_version[2])\n",
                "if not (pandas_major > 0 or (pandas_major == 0 and pandas_minor > 24) or (pandas_major == 0 and pandas_minor == 24 and pandas_patch >= 2)):\n",
                "    sys.exit('Please upgrade the Notebook dependency before you can proceed, you can do it by running the \"Reinstall Notebook dependencies\" command in command palette (View menu -> Command Palette…).')\n",
                "\n",
                "def run_command():\n",
                "    print(\"Executing: \" + cmd)\n",
                "    !{cmd}\n",
                "    if _exit_code != 0:\n",
                "        sys.exit(f'Command execution failed with exit code: {str(_exit_code)}.\\n\\t{cmd}\\n')\n",
                "    print(f'Successfully executed: {cmd}')\n",
                "\n",
                "cmd = 'docker version'\n",
                "run_command()"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 1
        },
        {
            "cell_type": "markdown",
            "source": [
                "### List existing containers\n",
                "You can view the ports that have been used by existing containers"
            ],
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "cmd = f'docker ps -a'\n",
                "run_command()"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 2
        },
        {
            "cell_type": "markdown",
            "source": "### Required information",
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "env_var_flag = \"AZDATA_NB_VAR_DOCKER_PASSWORD\" in os.environ\n",
                "password_name = 'SQL Server sa account password'\n",
                "if env_var_flag:\n",
                "    sql_password = os.environ[\"AZDATA_NB_VAR_DOCKER_PASSWORD\"]\n",
                "    sql_port = os.environ[\"AZDATA_NB_VAR_DOCKER_PORT\"]\n",
                "else:\n",
                "    sql_password = getpass.getpass(prompt = password_name)\n",
                "    password_confirm = getpass.getpass(prompt = f'Confirm {password_name}')\n",
                "    if sql_password != password_confirm:\n",
                "        raise SystemExit(f'{password_name} does not match the confirmation password.')\n",
                "    sql_port = input('SQL Server port, default value is 1433')\n",
                "    if len(sql_port) == 0:\n",
                "        sql_port = '1433'\n",
                "print(f'{password_name}: ******')\n",
                "print(f'Port: {sql_port}')"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 3
        },
        {
            "cell_type": "markdown",
            "source": "### Pull the container image",
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "cmd = f'docker pull mcr.microsoft.com/mssql/server:2019-latest'\n",
                "run_command()"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 4
        },
        {
            "cell_type": "markdown",
            "source": "### Start a new container",
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "if env_var_flag:\n",
                "    container_name = os.environ[\"AZDATA_NB_VAR_DOCKER_CONTAINER_NAME\"]\n",
                "else:\n",
                "    container_name = 'sql2019-' + time.strftime(\"%Y%m%d%H%M%S\", time.localtime())\n",
                "print('New container name: ' + container_name)\n",
                "cmd = f'docker run -e ACCEPT_EULA=Y -e \"SA_PASSWORD={sql_password}\" -p {sql_port}:1433 --name {container_name} -d mcr.microsoft.com/mssql/server:2019-latest'\n",
                "run_command()"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 5
        },
        {
            "cell_type": "markdown",
            "source": "### List all the containers",
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "cmd = f'docker ps -a'\n",
                "run_command()"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 6
        },
        {
            "cell_type": "markdown",
            "source": [
                "### Connect to SQL Server in Azure Data Studio\n",
                "It might take a couple minutes for SQL Server to launch"
            ],
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "from IPython.display import *\n",
                "connectionParameter = '{\"serverName\":\"localhost,' + sql_port + '\",\"providerName\":\"MSSQL\",\"authenticationType\":\"SqlLogin\",\"userName\":\"sa\",\"password\":' + json.dumps(sql_password) + '}'\n",
                "display(HTML('<br/><a href=\"command:azdata.connect?' + html.escape(connectionParameter)+'\"><font size=\"3\">Click here to connect to SQL Server</font></a><br/>'))"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 7
        },
        {
            "cell_type": "markdown",
            "source": "### Stop and remove the container",
            "metadata": {}
        },
        {
            "cell_type": "code",
            "source": [
                "stop_container_command = f'docker stop {container_name}'\n",
                "remove_container_command = f'docker rm {container_name}'\n",
                "display(HTML(\"Use this link to: <a href=\\\"command:workbench.action.terminal.focus\\\">open the terminal window in Azure Data Studio</a> and use the links below to paste the command to the terminal.\"))\n",
                "display(HTML(\"Stop the container: <a href=\\\"command:workbench.action.terminal.sendSequence?%7B%22text%22%3A%22\"+stop_container_command.replace(\" \",\"%20\")+\"%22%7D\\\">\" + stop_container_command + \"</a>\"))\n",
                "display(HTML(\"Remove the container: <a href=\\\"command:workbench.action.terminal.sendSequence?%7B%22text%22%3A%22\"+remove_container_command.replace(\" \",\"%20\")+\"%22%7D\\\">\" + remove_container_command + \"</a>\"))"
            ],
            "metadata": {},
            "outputs": [],
            "execution_count": 8
        }
    ]
}
