Creating a Mysql user within a Rails controller action - mysql

Working on an app that wil be used by admin only to create multiple instances of another app.
In other words, app A will be used to create clones of app B on server and create all the configurations needed to run that cloned app on a subdomain new_clone.domain.com.
Managed to clone the app, created the apache config file, unicorn server settings file too. Managed to run rake db:create; db:migrate but I did this with the root user of mysql.
At the point where I clone the app, I generate a database.yml file for the new cloned app that has at this moment username and password set as root, but I woould like to have a different user for each cloned app.
The app A has a model called Subdomain, in the subdomains_controller.rb at the create action I do all the things, clone, generate config files, running rake tasks, etc... and also in this create action I need to create a new Mysql user with privileges for a specific database.
What I have tried so far, can't say I did much, I tried to run the mysql command within controller create action:
def create
if #subdomain.save
....
system "mysql -u root -p root; create database new_database;..."
....
else
....
end
end
but this puts my create action on hold until I type in the password, and even if I'll find a way to go over it I am not sure the rest of mysql commands will work. Probably there is a better way to add a Mysql user with one command line without going into mysql console.
Thank you.

As far as I understood, your create method runs under Rails app with root mysql user.
Then you can simply execute mysql commands via AR adapter:
# Create DB
ActiveRecord::Base.connection.execute("CREATE DATABASE IF NOT EXISTS \
`#{ActiveRecord::Base.sanitize(db_name)}` CHARACTER SET = `utf8` \
COLLATE = `utf8_general_ci`")
# Create User
ActiveRecord::Base.connection.execute("REPLACE INTO mysql.user \
(Host, User, Password) VALUES(\"localhost\", \
\"#{ActiveRecord::Base.sanitize(db_user)}\", \
PASSWORD(\"#{ActiveRecord::Base.sanitize(db_password)}\"))")
# Grant access
ActiveRecord::Base.connection.execute("GRANT ALL PRIVILEGES ON \
`#{ActiveRecord::Base.sanitize(db_name)}`.* TO \
`#{ActiveRecord::Base.sanitize(db_user)}`")
# Apply
ActiveRecord::Base.connection.execute("FLUSH PRIVILEGES")

Thanks to Yuriy's answer I got it working in a shorter way:
def create_mysql_user
#db_name = "#{#subdomain.name}_domain_production"
#db_user = "#{#subdomain.name}_user"
#db_password = "#{#subdomain.name}domain_password"
ActiveRecord::Base.connection.execute("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER,
INDEX ON `#{#db_name}`.* TO #{ActiveRecord::Base.sanitize(#db_user)}#localhost
IDENTIFIED BY #{ActiveRecord::Base.sanitize(#db_password)};")
# Apply
ActiveRecord::Base.connection.execute("FLUSH PRIVILEGES")
end

Related

Delete ruby user records

I'm developing a ruby app and want to delete my testing users in the SQL database is there a command line to delete them all. Like to start fresh through testing
You can do rails db:migrate:resetto delete everything and recreate your database
To delete database in rails using command lines run in this command in the rails app directory.
bundle exec rake db:drop:all
The above code will delete the entire database. Alternatively you can delete the database using mysql also by listing all the databases present and choosing the one to delete.
Open up terminal and type mysql -u yourusername -p, hit enter and type your root password.
show databases;
drop database yourdatabase;

How can I create the root administration user root:rootroot for MySQL?

I am creating a Software configuration for MySQL 5.6.22 and I'll need to create the root administration user root:rootroot.
Next step, I'll need to install as service/daemon with auto-start option and finally this installation needs:
MySQL Workbench 6.2.4
MySQL Connector/J 5.1.34
To configure the Data Base on RNL Lab of the project the programmer shell do:
The mysql -uroot -p try to connect to the server and it won't have access to it.
The programmer shell always use mysql-local-client, this might work as an alias to the root, while the pass maintains the same as "root".
For running the project it must be started by the MySQL Server on the working Computer:
mysql-local-start
At the end it might encounter the running server port (should be the 10000 or 10001).
After that it must have a connection to the server, using other command line, to creating the user, give the right privilege and finally for creating the Data Base with:
mysql-local-client
It's necessary to use this command, that works as an alias for the last server created.
Please run the next commands on MySQL Shell from the mysql-local-client:
CREATE USER 'bubble'#'localhost' IDENTIFIED BY 'bubbl3';
CREATE USER 'bubble'#'%' IDENTIFIED BY 'bubbl3';
GRANT ALL PRIVILEGES ON bubbledb.* TO 'bubble'#'localhost';
GRANT ALL PRIVILEGES ON bubbledb.* TO 'bubble'#'%';
CREATE DATABASE bubbledb;
At last it needed to change the properties for the Fenix Framework so that the next code runs (where 10000 is the running server port):
dbAlias=//localhost:10000/bubbledb?useUnicode=true&characterEncoding=UTF-8&clobCharacterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
dbUsername=bubble
dbPassword=bubbl3"

Migrating a satchmo store from sqlite3 to mysql

I have a fully functional satchmo store running on sqlite3. I need to change to mysql though. Whether I create a new database or port the old database, I get http error 500s in all sorts of places. For example if I have a new db, and I create a user account all seems to be fine. If I then attempt to update the user's profile (which is actually and extended user profile), immediately I get the server 500 error. Its like it just isn't interested in that URL any more (http://127.0.0.1:8000/accounts/update/)
The weird thing is that if I log in as an admin and go to the admin pages, then I can update that user's (extended) profile no problem at all. In fact I've never seen any errors on the admin pages.
Here is how I set it up for mysql:
apt-get install mysql-client
apt-get install mysql-server
apt-get install python-mysqldb
mysql -u root -p
mysql> USE mysql;
mysql> CREATE DATABASE mystore CHARACTER SET utf8;
mysql> GRANT ALL PRIVILEGES ON mystore.* TO storeuser#localhost IDENTIFIED BY 'secret';
mysql> FLUSH PRIVILEGES;
settings.py:
DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'mystore'
DATABASE_USER = 'storeuser'
DATABASE_PASSWORD = 'secret'
DATABASE_HOST = ''
DATABASE_PORT = ''
DATABASE_OPTIONS = { "init_command": 'SET NAMES "utf8"' , "init_command":'SET storage_engine=INNODB' , }
Then to create a new db I just did ths:
python manage.py syncdb
python manage.py runserver
Edit 1
Here is the code where it bombs out:
class myExtendedContactInfoForm(ExtendedContactInfoForm):
def __init__(self, *args, **kwargs):
# The following line is where it produces the error
super(myExtendedContactInfoForm, self).__init__(*args, **kwargs)
Edit 2
It seems like there is something missing from the db because if I go back to using a sqlite back-end, and then delete the sqlite db (and then run 'python manage.py syncdb') I get exactly the same symptoms. Seems like I need to do something more than just syncdb.
What am I missing here?

How to get started with PostgreSQL similar to MySQL

I am not getting a clue to:
simply login to postgreSQL
Create a database
Add a table
Insert a record
Delete , update etc
These things are normally very very easy using mysql . Can someone help me setup following alternative for postgresql
a) Reset default password -- Very Clean description ,
I do not find same level of clarity for PostgreSQL
(Any documentation link is highly appreciated)
b) We know the superuser for mysql is "root" what is the same for PostgreSQL
c) from command line how to ( PostgreSQL ones ?):
mysql -uroot -proot
create database testdb;
use testdb;
create table test(id int(11) auto_increment, name varchar(20), primary key(id));
insert into test(name) values("testing one"),("testing two"),("testing three"),("testing four");
select * from test;
update test set name=concat(name,now()) where id =3;
delete from test where id =4;
drop table if exists test;
drop database if exists testdb;
EDIT MAC OS
# Default password reset
sudo mate /Library/PostgreSQL/9.2/data/pg_hba.conf
replaced (md5 with trust)
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
with
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
save
executed the Reload Configuration.app
login to postgresql without password :
$ psql -U postgres
postgres# ALTER USER postgres WITH PASSWORD 'new password';
\q
-revert back all the changes in pg_hba.conf (replace trust with md5) and save
-reload configuration
Now I can login to postgresql with new password
psql -U postgres
Password for user postgres:[my new password]
To login:
psql -d postgres_dbname -U postgres
Create Database:
create database testuser;
\c testuser; /*use testuse as mysql*/
Create Table:
create table employee (Name char(20));
Insert :
insert into employee VALUES ('XAS');
Update Link
Delete Link
Reset Password : See Here &
See Here Too
Simply login to postgreSQL
psql -U postgres -W template1
-U = username
postgres is root
-W = ask for password
tempalte1 = default database
Create a database
-- Create the database from within postgresql
create database my_database_name
-- Connect to the database
\c my_database_name
-- Create the database without logging in
createdb -U postgres -W my_database_name
Add a table
Insert a record
Delete , update etc
All the above from 3 to 5 are like in MySQL
For resetting postgres forgotten password this link is a good reference.
postgresql is a completely different system than mysql; so do not assume things will be like mysql. They are completely different animals entirely; some of your SQL statements might not work, especially if you are using a MySQL proprietary command.
To login to postgresql, use the psql command shell
CREATE DATABASE
CREATE TABLE
INSERT
For all other basic SQL commands, consider going through the tutorial
User access control is something more fine grained and detailed in postgresql. There are users and roles. A user is simply a role that has the ability to login (like MySQL), but in postgresql you can have roles (an account) that cannot login.
What access a role has is defined in pg_hba.conf. This file defines if a role can login at all, by what means are they authenticated, from where they can login and what database they have access to.
ALTER USER is used to reset credentials.
The "root user" for postgresql is typically postgres; and this is a system user that is created during the install process. For Windows, the binary installer will ask if you want to launch the service as this user as well.
Please take a look at this PostgreSQL error 'Could not connect to server: No such file or directory'
Try to install postgresApp, this solved my problem which was the same of yours.

Can I switch the 'connected' user within an sql script that is sourced by mysql?

I was wondering if I can switch the "connected" user within an sql script that is executed by mysql.
Here's a description of my goal. Perhaps, it's not necessary to swich the user and another solution gives me what I want.
I want to write a database creation script like so:
create databse some_db;
create user u#localhost identified by 'pw';
grant all on u.* to u;
-- Here's where I want to switch the user, but *obviously* the
-- following command fails
connect u#localhost/pw;
-- Now, as new user, create the tables:
use some_db;
create table t (...
This script would then be called from the command line like
$ mysql -u root -p"....." < create_db.sql
Is this possible or do I have to leave the script in order to switch the connected user?
AFAIK, you can not change the user in the middle of the script unless you create a brand new connection with the credentials of the other user.
BTW, connect command only reconnects but there are only two optional parameters as documentation states: db and host.
I am not aware of a regular way to switch the user from within an SQL script.
An irregular could be the usage of a stored procedure or the usage of table triggers. Both allow setting a DEFINER. So you could try to put the "special user code" into a stored procedure or a trigger, call the stored procedure or trigger the trigger and get the code executed.
If even that does not work, you need one script:
#!/bin/sh -eu
mysql --host localhost --user root --password root_pw < create_user.sql
mysql --host localhost --user u --password pw < create_table.sql