Search code examples
mysqlherokuexpresscleardb

How to create a MySQL schema when deploying with Heroku (Express Server)


Suppose I have the following server.js file:

server.js

var express = require('express');
var app = express();
var mysql = require('mysql');
var dbhelpers = require('./public/database_helpers.js')
var bodyParser = require('body-parser')



app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use(express.static(__dirname + '/public/controlers'));
app.use(express.static(__dirname + '/public/lib'));

app.use(bodyParser())


var connection = mysql.createConnection({
   **Correct info**
});


connection.connect(function(err){
if(!err) {
    console.log("Database is connected ... \n\n");  
} else {
    console.log("Error connecting database ... \n\n");  
}
});


app.post('/signup',function(req,res){
  var newUser = req.body;


  connection.query('INSERT INTO users SET ?',newUser, function(err, rows,fields){
    if (!err){
      console.log("posted to database")
      res.sendStatus(200);
    } else{
      console.log('Error while performing Query.');
      res.sendStatus(500);
    }
  }); 
})

app.get('/artistsearch',dbhelpers.checkDbArtist)

app.post('/artistsearch', dbhelpers.insertDb)

app.post('/reviews',dbhelpers.insertReviewDb)


app.listen(process.env.PORT || 3000);

console.log("Listening at 3000")

I have recently deployed to heroku and used the clearDB addon since I am using MySQL. The logs indicate that I have been able to connect to the database, but the thing is that I believe Heroku creates an empty database. How can I create the following schema in my with clearDB:

schema.sql

CREATE TABLE users(
  users_id INT NOT NULL AUTO_INCREMENT,
  user_username VARCHAR(100) NOT NULL,
  user_password VARCHAR(40) NOT NULL,
  PRIMARY KEY ( users_id )
);

CREATE TABLE artist(
  artist_id INT NOT NULL AUTO_INCREMENT,
  artist_name VARCHAR(100) NOT NULL,
  artist_genre VARCHAR(100) NOT NULL,
  artist_imageurl VARCHAR(100) NOT NULL,
  artist_bio VARCHAR(1000) NOT NULL,
  PRIMARY KEY ( artist_id )
);

CREATE TABLE reviews (
  review_id INT NOT NULL AUTO_INCREMENT,
  user_name  VARCHAR(100) NOT NULL,
  venue VARCHAR(100) NOT NULL,
  number_of_stars INT NOT NULL,
  review_details VARCHAR(10000) NOT NULL,
  artist_id VARCHAR(100) NOT NULL,
  PRIMARY KEY ( review_id )
);

Anyone had any idea?


Solution

  • First, you should type heroku config to get your clearDB credentials.

    Then, you can ran this command from your terminal : mysql --host=us-cdbr-east.cleardb.com --user=xxxx --password=xxxx --reconnect heroku_xxxxxx < schema.sql