mercoledì 20 marzo 2013

Using MySQL in Macintosh as personal database


In few minutes, you'are able to use a MySQL database running with your user.
You have to install MacPorts !!!

Search the MySQL servers available on MacPort:
sudo port search mysql
Install the last version available:
sudo port install mysql55

Create a system variable with the MySQL home installed by Mac port
export MYSQL_HOME=/opt/local/lib/mysql55
# create a variable containing the personal MySQL installation
# NOTE: the directory name must contain no spaces !!!!
export MYSQL_DATADIR=$HOME/Documents/MySQL-davidez
export MYSQL_SOCKET=$MYSQL_DATADIR/mysql.sock
export MYSQL_CONFIG=$MYSQL_DATADIR/my.cnf
# replace the default TCP port (3306)
export MYSQL_PORT=3399
Launch  the MySQL installation
sh $MYSQL_HOME/scripts/mysql_install_db --datadir=$MYSQL_DATADIR
Create the MySQL configuration file to run the personal MySQL server
NOTE: the following configuration is a BASIC version !!!!
cat > $MYSQL_CONFIG << EOF
[mysqld]
datadir=$MYSQL_DATADIR
socket=$MYSQL_SOCKET
port=$MYSQL_PORT
user=$USER
[mysql.server]
basedir=$MYSQL_DATADIR
[client]
socket=$MYSQL_SOCKET
EOF
chmod 400 $MYSQL_CONFIG
Add the alias in order to simplify your life!
cat >> $HOME/.bash_profile << EOF
#
# Your personal MySQL database commands
#
alias mysqladmin-davidez="$MYSQL_HOME/bin/mysqladmin --socket $MYSQL_SOCKET"
alias mysqld-davidez="$MYSQL_HOME/bin/mysqld_safe  --defaults-file=$MYSQL_CONFIG"
alias mysql-davidez="$MYSQL_HOME/bin/mysql --socket $MYSQL_SOCKET"
alias mysql2-davidez="$MYSQL_HOME/bin/mysql -h localhost -P $MYSQL_PORT"
EOF
source $HOME/.bash_profile
Start the server
mysqld-davidez &
Set the MySQL root password
NOTE: this command changes only the root user from localhost
mysqladmin-davidez -u root password 'admin'
Clean the MySQL users in order to increase the security of your data!
NOTE: password is admin
echo "\
select host,user,password from mysql.user; \
delete from mysql.user where user!='root'; \
update mysql.user set password=PASSWORD('admin'); \
FLUSH PRIVILEGES; \
" | mysql-davidez -u root -p
Create a database user and his database
echo " \
CREATE DATABASE davidez_db; \
CREATE USER 'davidez'@'localhost' IDENTIFIED BY 'test'; \
GRANT ALL ON davidez_db.* TO 'davidez'@'localhost'; \
" | mysql-davidez -u root -p
Test the MySQL client
NOTE: password is test
mysql-davidez -u davidez -p davidez_db
Stop the server
mysqladmin-davidez -u root -p shutdown

References:
http://dev.mysql.com/doc/refman/5.5/en/problems-with-mysql-sock.html
http://dev.mysql.com/doc/refman/5.5/en/create-user.html
http://dev.mysql.com/doc/refman/5.5/en/grant.html
http://dev.mysql.com/doc/refman/5.5/en/batch-commands.html