Skip to content

Instantly share code, notes, and snippets.

@larsyencken
Created June 5, 2023 11:03
Show Gist options
  • Save larsyencken/0c7f745f067d9cb0e77e555c908425b3 to your computer and use it in GitHub Desktop.
Save larsyencken/0c7f745f067d9cb0e77e555c908425b3 to your computer and use it in GitHub Desktop.
Nushell: MySQL access

MySQL in Nushell

Here are some helpers for using MySQL in Nushell. You need the MySQL client installed, and also the separate MySQL Shell client (for JSON output).

The mysql-profile command is an optional helper for keeping multiple MySQL connection profiles around in your ~/.my.cnf and switching between them, instead of having to give credentials every time.

Enjoy!

def "db list-profiles" [] {
~/.local/bin/mysql-profile list
}
def "db use-profile" [name] {
~/.local/bin/mysql-profile use $name
}
def "db tables" [] {
(mysql -e 'show tables' --batch) | from tsv | rename table
}
def "db table" [table_name] {
(mysqlsh --sql -e $"select * from ($table_name)" --json) | from json | get rows
}
def "db sql" [sql] {
(mysqlsh --sql -e $sql --json) | from json | get rows
}
#!/usr/bin/env python
#
# mysql-profile
#
# Switch between mysql profiles. This command manages the [client] section of ~/.my.cnf.
# To add a profile called "readonly", make [client-readonly] section in ~/my.cnf. Then
# this command will detect it and let you switch to and from it.
#
from pathlib import Path
import configparser
from dataclasses import dataclass
import click
MYSQL_CONFIG = Path.home() / '.my.cnf'
@click.group()
def cli():
pass
@cli.command()
def list():
config = _parse_config()
profiles = []
for section in config.sections():
if section.startswith('client-'):
name = section.split('-', 1)[1]
profiles.append(name)
for profile in sorted(profiles):
print(profile)
@cli.command()
@click.argument('profile')
def use(profile):
config = _parse_config()
name = f'client-{profile}'
config['client'] = config[name]
with open(MYSQL_CONFIG, 'w') as f:
config.write(f)
def _parse_config() -> configparser.ConfigParser:
config = configparser.ConfigParser()
config.read(MYSQL_CONFIG)
return config
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment