SA—MySQL Administration Page 1

1 -- From Linux command-line: MySQL Administration 2 sudo install -server mysql by Terry Sergeant 3 sudo mysql_secure_installation 4 mysql -u root 5 Contents 6 -- now we are in the MySQL client: 7 SELECT user, host, authentication_string, plugin FROM mysql.user; 1 Introduction 1 8 ALTER USER ’root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ’password’; 1.1 Installation ...... 1 9 FLUSH PRIVILEGES; 1.2 First Steps ...... 1 10 \q 1.3 Some Other Useful Commands ...... 1 11 12 -- Back at Linux command-line ... test new password 2 Server Configuration 1 13 mysql -u root -p 2.1 SQL Mode ...... 1 2.2 Logging ...... 2 1.3 Some Other Useful Commands 3 MySQL Clients 2 From Linux command-line:

4 Data Types 2 1 systemctl status mysql 4.1 Numeric ...... 2 2 systemctl restart mysql 4.2 Character ...... 2 3 systemctl enable mysql 4.3 Binary ...... 2 4 systemctl is-enabled mysql 4.4 Temporal ...... 2 4.5 Other ...... 2 From MySQL command-line:

5 Obtaining Metadata 3 1 show ; 2 use DBNAME; 6 Storage Engines 3 3 show tables; 6.1 MyISAM (default) ...... 3 4 desc TNAME; 6.2 InnoDB ...... 3 5 create DBNAME; 6.3 InnoBase ...... 3 6 source SQLFILE; -- same as \. SQLFILE 6.4 MEMORY ...... 3 7 select @@datadir; 6.5 Other Engines ...... 3 7 Security and User Management 3 2 Server Configuration 7.1 Risks ...... 3 7.2 Some Commands ...... 3 Here are some common ways to tweak the server’s configuration.

8 Backup and Recovery 4 ˆ mysqld --verbose --help (to see runtime options sup- 8.1 Backup Types ...... 4 ported by server) 8.2 Recovery ...... 4 ˆ typically adjust configuration through startup file (rather than command-line options) 1 Introduction ˆ options files are organized in to [groups] ˆ connection parameters are typcially given in [client] group 1.1 Installation ˆ /etc/mysql/my.cnf is global file; ~/.my.cnf is local Some OS’s automatically enable an anonymous account. This should be disabled. In Windows the my.ini contains initialization 1 [mysqld] files There are example databases provided for experimenting, etc. 2 log # normal logging 3 log-bin # binary logging 1.2 First Steps 4 log-slow-queries = /var/log/slow.log # slow query log 5 default-storage-engine=InnoDB # set default storage engine When you first install MySQL the root account is accessible with- 6 max_connections=20 out a password and there are test databases, etc. These commands 7 key_buffersize-128M # default is 8MB will allow you to install and configure your account: 2.1 SQL Mode Can change mode to improve SQL standards compliance or other characteristics.

Server Administration Terry Sergeant SA—MySQL Administration Page 2 ˆ terminate commands with ; or \G (\g for vertical format) 1 [mysqld] ˆ 2 sql-mode=IGNORE_SPACES # after function name prompt will change depending on what else is expected 3 SELECT @@sql_mode; ˆ can do input line editing (use up arrow)

Common modes are: ANSI-QUOTES,IGNORE-SPACE, ERROR_FOR_DIVISION_BY_ZEROˆ source scriptname, is used to execute an SQL file STRICT_TRANS_TABLES, STRICT_ALL_TABLES,TRADITIONAL,ANSI ˆ commands have long form (word) and short form (\char) 2.2 Logging ˆ tee file.txt causes queries to be logged to a file There are several types of logs that can be kept: error log for errors 4 Data Types general query log shows all querys that have been performed 4.1 Numeric slow query log shows querys that take a long time 1 INT 2 FLOAT,DOUBLE binary log keeps results of all statements that modify data 3 DECIMAL(10,2) 4 BIT(4) --stores 4 bits Common use cases: ˆ use binary and slow to debug then disable them 4.2 Character ˆ error log can stay on 1 CHAR ˆ startup data is put in error log 2 VARCHAR 3 TEXT ˆ If replicating servers, MySQL uses log shipping of the binary 4 ENUM log. 5 SET 6 SHOW CHARACTER SET; To delete old log files do one of these:

1 SET GLOBAL expire_logs_days=7; 4.3 Binary 2 PURGE BINARY LOGS BEFORE now() - INTERVAL 1 WEEK;

1 BINARY(L) To view binary log data: 2 VARBINARY(L) 3 for holding images, sound files, etc. 1 mysqlbinlog logfile 4 BLOG --binary large object 2 SHOW BINARY LOGS;

Some helpful options for use with mysqlbinlog: 4.4 Temporal

ˆ --start-datetime and --stop-datetime can be used to 1 TIME -- of day or INTERVAL display log data within a specified range; these can be used 2 YEAR -- separately or together 3 DATE -- calendar date 4 DATETIME -- both date and time ˆ --start-position and --stop-position can be used to 5 TIMESTAMP -- ditto filter log data by position numbers 6 ...DEFAULT CURRENT_TIMESTAMP...ON UPDATE CURRENT_TIMESTAMP ˆ NOTE: results of mysqlbinlog can be piped to more or to mysql -u root -p 4.5 Other The value NULL means “unknown”. It cannot be applied to pri- 3 MySQL Clients mary keys or to timestamps. The type AUTOINCREMENT generates successive values on inserts

1 mysql # command-line client only one column per table must be indexed and not NULL. 2 mysqladmin # for managing server The query SELECT LAST_INSERT_ID() returns last autoincre- 3 mysqlimport # ment value for the current client. 4 mysqldump # for backups, etc. You can use DEFAULT to specify default values for a field. The specified value must be a constant with the allowed exception of The above command can be invoked with –help to get infor- TIMESTAMP fields which can make use of functions that return time mation about various options. stamps. Helpful facts about the mysql client: ˆ can be used in interactive mode or batch mode ˆ use SELECT VERSION(); for version info Server Administration Terry Sergeant SA—MySQL Administration Page 3 5 Obtaining Metadata 6.2 InnoDB

Metadata describes structure of data (e.g., names and structure The InnoDB engine provides support for transactions and is, of tables, etc.). There are various commands that can show this therefore, the common choice for concurrent web applications. information: ˆ represented by .frm file and other files growing as needed 1 INFORMATION_SCHEMA database ˆ supports transactions (ACID compliant) 2 SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES \ 3 WHERE TABLE_SCHEMA= ’information_schema’ ORDER BY TABLE_NAME; ˆ auto-recovery after crash ˆ The SHOW command is MySQL-only but provides shortcuts row-level locking to accessing the INFORMATION_SCHEMA database directly. ˆ foreign key constraints are maintained if requested

1 SHOW DATABASES; -- LIKE ... ˆ uses graph detection for deadlock 2 SHOW TABLES; -- FROM database; 3 SHOW COLUMNS FROM table; -- WHERE ... 4 DESCRIBE table; 6.3 InnoBase InnoBase is a plugin that provides advantages over InnoDB. From the command-line you can use mysqlshow to provide metadata. 6.4 MEMORY Used for tables stored in memory. The result is that access to the 6 Storage Engines tables is very fast. Also the tables are temporary.

Storage engines are independent of SQL commands. Storage en- 6.5 Other Engines gine determines storage medium, transactional capabilities, lock- ing, backup and recovery, and optimization ARCHIVE for compression ... but slower Use SHOW ENGINES; to see what engines are supported by your installation. Add ENGINE=engine to a CREATE TABLE statement CSV just what it sounds like! stored in table_name.csv if you want something other than the default engine. BLACKHOLE does’t store data, but can hold structure Use SHOW TABLE STATUS tablename; to see engine for a given table. MySQL Cluster group of nodes working together to store/retrieve data 6.1 MyISAM (default) Falcon developed by Sun. special release. for high-traffic, trans- The MyISAM engine is the default. Some characteristics of My- actional apps ISAM tables: ˆ each table has 3 files (.frm, .MYD, .MYI) 7 Security and User Management

ˆ flexibile auto_increment MySQL restricts access via ACLs (Access Control Lists). ˆ can be compressed and read-only 7.1 Risks ˆ table-level locking Some risks to be aware of: ˆ portable storage format ˆ network security risks ˆ tables take up litte space ˆ operating system security risks ˆ fixed row format / dynamic row format / compressed format ˆ filesystem security risks ˆ to compress a table use myisampack

ˆ concurrent behavior: writer preference 7.2 Some Commands Grant tables store access control info: ˆ NO SUPPORT FOR TRANSACTIONS! ˆ user table stores privileges ˆ NO SUPPORT FOR FOREIGN KEY CONSTRAINTS! ˆ db db-level privileges An account contains both a host name and a user name

Server Administration Terry Sergeant SA—MySQL Administration Page 4 ˆ --all-databases will copy everything 1 FLUSH PRIVILEGES; -- forces reload of modifications ˆ --lock-all-tables will make all tables across all 2 GRANT SELECT world.* TO ’kari’@’localhost’ \ databases read-only during the backup 3 IDENTIFIED BY ’password’; 4 GRANT whichprivs whichdbs TO user@host \ ˆ --single-transaction in an database using InnoDB 5 IDENTIFIED BY ’password’; engine, this provides a consistent snapshot while allow- 6 SHOW GRANTS; -- FOR CURRENT_USER(); ing some concurrent write activity; if not using InnoDB 7 SHOW GRANTS FOR ’kari’@’myhost.example.com’; then use --lock-all-tables instead; do not use this 8 SELECT user, host, password FROM mysql.user; -- WHERE ... option if there is a possibility of table structure being 9 CREATE USER ’jim’@’localhost’ IDENTIFIED BY ’password’; modified during the backup 10 DROP USER ’jim’@’localhost’; 11 REVOKE whichprivs ON whichdbs FROM user; ˆ --routines include stored procedures/functions in the backup MySQL replication : Multiple database hosts keep current 8 Backup and Recovery copy of the database in a master/slave arrangment that au- tomatically backs up master to slave. Queries can be dis- 8.1 Backup Types tributed among the hosts and backups are implicit. There are three categories of backups: 8.2 Recovery HOT happen while server is actively being used Recovery methods, of course, depend on the type of backup used: COLD happen when user’s are not allowed to access server disk : Simply move the copied files back to the original location WARM allows data to be read, but not modified during backup from which they were copied. There are several ways to backup a MySQL database: binary log : Re-execute changes in binary log since last backup. disk : Copy actual files on disk. This is a COLD procedure and Use the command mysqlbinlog to extract portions of a file. provides for a fast restore. Can only restore to same engine. e.g., mysqlbinlog bin.000050 bin000051 | mysql Example steps for disk backup on InnoDB tables: logical/textual : These are some ways to dump/restore files. 1. Stop Server Suppose we have a database named world and a table named Country saved in a file named dump.sql: 2. Confirm proper shutdown

1 mysql -u root -p world < dump.sql 3. 1 cp /var/lib/mysql/data/ib_logfile* /var/backup 2 cp /var/lib/mysql/data/ibdata* /var/backup 3 cp /var/lib/mysql/data/*.frm /var/backup NOTE: if --tab was given then import via mysqlimport 4 cp /etc/my.cnf /var/backup/ NOTE: We can use mysqldump and mysql and the pipe to 4. Restart server copy table(s) from one database to another: binary log : Records modifications to data; is HOT; pro- 1 mysqldump world Country | mysql test vides sequential/incremental (not total) backup. Use 2 mysqldump world Country | mysql -h other.host.com world SET SQL_LOG_BIN = ON to turn on binary logging. MySQL replication : Database is always replicated. logical/textual : Use the mysqldump command to dump database to a file. This is a WARM technique:

1 mysqldump --opt mydbname -u root \ 2 -p > mydb_backup.sql 3 mysqldump --opt mydbname --table=tablename \ 4 -u root -p > mytable_backup.sql 5 mysqldump --opt --all-databases -u root -p > \ 6 alldb_backup.sql

Some common options for use with mysqldump: ˆ --opt shorthand for a variety of commonly needed op- tions ˆ --flush-logs will start a new set of binary logs after the backup is made ˆ --master-data will write the binary log file name and position to the dump file; NOTE: --master-data=2 will also name binary log that that was started after the backup Server Administration Terry Sergeant