How to get the metadata of a mysql table on sailsjs - mysql

I was wondering if you can get the metadata or the entire structure of the table and columns using sailsjs or waterline's mysql module

After hours of searching, I've finally found the holy grail. Well half of the holy grail.
Anyway, I just followed the instructions given here: https://github.com/balderdashy/sails/issues/780 then created my own custom query.

Yes its very easy to get structure of MySQL table by Waterline SalsJS...
Model.query("desc table_name",function (err, models) {
if(!err)
{
//Do somethng wth your data in models variable
}
}
)
Here table_name is your table name
For me, below code was working fine...
db('users_table').query("SHOW COLUMNS FROM users_table",function (err, models) {
if (! err )
// working with data
});

Related

Are there any way to create singular-name DB table?

development environment
Lnaguage : Golang ver.1.9.2
DB : mySQL
Framework : not decided (Maybe I'll use revel)
situation
I already have DB which has singular-name table ,like "user", "page". It can't be changed.
Now I'll develop new application using this DB.
I created simple application to connect this DB, and tried to auto migrate using gorm(https://github.com/jinzhu/gorm).
I defined some models, like "user" which is same as existing DB table name, and run auto-migrate just as it written in (http://jinzhu.me/gorm/database.html#connecting-to-a-database )
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
Then, new table "users" was created.
Question
Can I create singular-name table, like "user" with auto-migrate or those things ?
Using gorm is not required, so I'll use another orm library if it works.
I hope anyone help me !
Implement function TableName on struct User to return a custom name for the table. The ORM uses this function to get the table name for all DB operations.
func (user *User) TableName() string {
return "user"
}
Refer docs here: http://jinzhu.me/gorm/models.html#table-name-is-the-pluralized-version-of-struct-name
You have set with db instance to use singular table, like this:
db.SingularTable(true)

How to use DB indexes with Datatables and yajra/laravel-datatables

So far when I try column filtering I'm able to use LIKE or REGEXP but nether of them are using table indexes, which is a great concern given the amount of data I need to filter.
Is there a way to get an exact match using indexes? (DB indexes)
I'm using:
https://github.com/yajra/laravel-datatables v6.11.3 and
https://datatables.net v1.10.10
With datatables laravel package you can customise parameter search on laravel side in lookup function with the "filterColumn" function. Like so:
return Datatables::of($users)
->filterColumn('user_id', function($query, $keyword) {
$query->whereRaw("CONCAT(users.id,'-',users.id) like ?", ["%{$keyword}%"]);
})
->make(true);
See more in Documentation

Create a new table on sails

my question is pretty simple but I can't find my answer over the web.
I'm on a project Sails/AngularJS and I simply would like to create a new table in mysql when a specific route is called.
It seems that it's not possible with waterline to create one afterwards.
I would be pleased if someone as a clue of how to resolve that.
Regards.
Waterline does not provide any function to create table.
Method 1:
But it provides Model.query() method which you can use to perform any kind of query you want.
//TestController.js
module.exports = {
action1:function(req,res){
var queryString='CREATE TABLE if not exists sailsusers.test (id INT NOT NULL,name VARCHAR(45) NULL,PRIMARY KEY (id))'
Test.query(queryString,function(err,a){
if(err)
return console.log(err);
console.log(a,'\n',b);
res.ok();
});
}
};
So that's how you can do that!
Method 2:(Risk of loosing data so never do in production)
in config/models.js add the following.
migrate: 'alter'
whenever you lift the server one table for each model will be created automatically.But No one suggest to do that in production.
This way is not preferred.

MongoDB is much slower in comparision to MySQL - basic find() method

It is my first Stackoverflow question but I'm long time reader.
I'm working on some home project and I tried to compare the speed of MongoDB and MySQL. Suprisingly.. MongoDB is almost 5 times slower even with very basic table? I was reading that they are almost the same speed but it got me thinking.
Can someone explain to me why is this happening?
The MongoDB code:
app.get('/mongodb', function(req, res, next) {
var time = process.hrtime();
User.find(function(err, users) {
if (err) return next(err);
var diff = process.hrtime(time);
if(diff[0] == 0) {
res.send(diff[1].toString());
} else {
res.send(diff[0]+"."+diff[1]);
}
});
});
The MySQL code:
app.get('/mysql', function(req, res, next) {
var time = process.hrtime();
mysql.query("SELECT * FROM users", function(err, results) {
if (err) throw err;
var diff = process.hrtime(time);
if(diff[0] == 0) {
res.send(diff[1].toString());
} else {
res.send(diff[0]+"."+diff[1]);
}
});
});
MySQL returns: 1.52201348
MongoDB returns: 9.746405351
Schema is:
User {
id integer,
name string,
email string,
}
There are around 500000 of Users.
Index is on _id in MongoDB and id in MySQL.
MongoDB shell version: 2.4.6
MySQL version: 5.5.37
Any ideas? Any help or suggestions will be much appreciated.
Regards,
Wnzl.
I think the main problem here is that benchmarking should always be done with respect to a special use case.
The assumption, that they perfom with same speed is pretty unspecific.
So the use case you examine here is defined by your example and means getting all entities of a schema. Even if the use case is pretty simple, the meaningfulness of your result won't be.
MongoDB and SQL are database systems designed for different use cases. This means that each system is optimized for different queries. This is where I think you should dig deeper to get the reason for different performances.
Also take into account, that based on hat, querying all entity's of one schema, perhaps could be realized with multiple but in total faster queries. Last think about bootstrap, caching and indexing mechanisms that may be total different due to optimizations to system specific use cases.

converting database from mysql to mongoDb

is there any easy way to change the database from mysql to mongoDB ?
or better any one suggest me good tutorial do it
is there any easy way to change the database from mysql to mongoDB ?
Method #1: export from MySQL in a CSV format and then use the mongoimport tool. However, this does not always work well in terms of handling dates of binary data.
Method #2: script the transfer in your language of choice. Basically you write a program that reads everything from MySQL one element at a time and then inserts it into MongoDB.
Method #2 is better than #1, but it is still not adequate.
MongoDB uses collections instead of tables. MongoDB does not support joins. In every database I've seen, this means that your data structure in MongoDB is different from the structure in MySQL.
Because of this, there is no "universal tool" for porting SQL to MongoDB. Your data will need to be transformed before it reaches MongoDB.
If you're using Ruby, you can also try: Mongify
It's a super simple way to transform your data from a RDBS to MongoDB without losing anything.
Mongify will read your mysql database, build a translation file for you and all you have to do is map how you want your data transformed.
It supports:
Auto updating IDs (to BSON ObjectID)
Updating referencing IDs
Type Casting values
Embedding tables into other documents
Before save filters (to allow changes to the data manually)
and much much more...
Read more about it at: http://mongify.com/getting_started.html
There is also a short 5 min video on the homepage that shows you how easy it is.
Here's what I did it with Node.js for this purpose:
var mysql = require('mysql');
var MongoClient = require('mongodb').MongoClient;
function getMysqlTables(mysqlConnection, callback) {
mysqlConnection.query("show full tables where Table_Type = 'BASE TABLE';", function(error, results, fields) {
if (error) {
callback(error);
} else {
var tables = [];
results.forEach(function (row) {
for (var key in row) {
if (row.hasOwnProperty(key)) {
if(key.startsWith('Tables_in')) {
tables.push(row[key]);
}
}
}
});
callback(null, tables);
}
});
}
function tableToCollection(mysqlConnection, tableName, mongoCollection, callback) {
var sql = 'SELECT * FROM ' + tableName + ';';
mysqlConnection.query(sql, function (error, results, fields) {
if (error) {
callback(error);
} else {
if (results.length > 0) {
mongoCollection.insertMany(results, {}, function (error) {
if (error) {
callback(error);
} else {
callback(null);
}
});
} else {
callback(null);
}
}
});
}
MongoClient.connect("mongodb://localhost:27017/importedDb", function (error, db) {
if (error) throw error;
var MysqlCon = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
port: 8889,
database: 'dbToExport'
});
MysqlCon.connect();
var jobs = 0;
getMysqlTables(MysqlCon, function(error, tables) {
tables.forEach(function(table) {
var collection = db.collection(table);
++jobs;
tableToCollection(MysqlCon, table, collection, function(error) {
if (error) throw error;
--jobs;
});
})
});
// Waiting for all jobs to complete before closing databases connections.
var interval = setInterval(function() {
if(jobs<=0) {
clearInterval(interval);
console.log('done!');
db.close();
MysqlCon.end();
}
}, 300);
});
MongoVUE's free version can do this automatically for you.
It can connect to both databases and perform the import
I think one of the easiest ways is to export the MySQL database to JSON and then use mongorestore to import it to a MongoDB database.
Step 1: Export the MySQL database to JSON
Load the mysql dump file into a MySQL database if necessary
Open MySQL Workbench and connect to the MySQL database
Go to the Schema viewer > Select database > Tables > right-click on the name of the table to export
Select 'Table Data Export Wizard'
Set the file format to .json and type in a filename such as tablename.json
Note: All tables will need to be exported individually
Step 2: Import the JSON files to a MongoDB using the mongorestore command
The mongorestore command should be run from the server command line (not the mongo shell)
Note that you may need to provide the authentication details as well as the --jsonArray option, see the mongorestore docs for more information
mongoimport -d dbname -u ${MONGO_USERNAME} -p ${MONGO_PASSWORD} --authenticationDatabase admin -c collectionname --jsonArray --file tablename.json
Note: This method will not work if the original MySQL database has BLOBs/binary data.
I am kind of partial to TalendOpenStudio for those kind of migration jobs. It is an eclipse based solution to create data migration "scripts" in a visual way. I do not like visual programming, but this is a problem domain I make an exception.
Adrien Mogenet has create a MongoDBConnection plugin for mongodb.
It is probably overkill for a "simple" migration but ut is a cool tool.
Mind however, that the suggestion of Nix will probably save you time if it is a one-of migration.
You can use QCubed (http://qcu.be) framework for that. The procedure would be something like this:
Install QCubed (http://www.thetrozone.com/qcubed-installation)
Do the codegen on your database. (http://www.thetrozone.com/php-code-generation-qcubed-eliminating-sql-hassle)
Take your database offline from the rest of the world so that only one operation runs at a time.
Now write a script which will read all rows from all tables of the database and use the getJson on all objects to get the json. You can then use the data to convert to array and push it into the mongoDB!
If anyone's still looking for a solution, i found that the easiest way is to write a PHP script to connect to your SQL DB, retrieve the information you want using the usual Select statement, transform the information into JSON using the PHP JSON Encode functions and simply output your results to file or directly to MongoDB. It's actually pretty simple and straight forward, the only thing to do is to double check your output against a Json validator, you may have to use functions such as explode to replace certain characters and symbols to make it valid. I have done this before however i currently do not have the script at hand but from what i can remember it was literally half a page of code.
Oh also remember Mongo is a document store so some data mapping is required to get it to be acceptable with mongo.
For those coming to this with the same problem, you can check out this Github project. This is an ongoing development that will help you migrate data from MySQL database to MongoDB by simply running a simple command.
It will generate MongoDB Schemas in TypeScript so you can use them later in your project. Each MySQL table will be a MongoDB collection, and datatypes will be efficiently converted to their MongoDB compatibles.
The documentation for the same can be found in the project's README.md. Feel free to come in and contribute. Would like to help if need be.
If you are looking for a tool to do it for you, good luck.
My suggestion is to just pick your language of choice, and read from one and write to another.
If I could quote Matt Briggs (it solved my roblem one time):
The driver way is by FAR the most straight forward. The import/export tools are fantastic, but only if you are using them as a pair. You are in for a wild ride if your table includes dates and you try to export from the db and import into mongo.
You are lucky too, being in c#. We are using ruby, and have a 32million row table we migrated to mongo. Our ending solution was to craft an insane sql statement in postgres that output json (including some pretty kludgy things to get dates going properly) and piped the output of that query on the command line into mongoimport. It took an incredibly frustrating day to write, and is not the sort of thing that can ever really be changed.
So if you can get away with it, use ado.net with the mongo driver. If not, I wish you well :-)
(note that this is coming from a total mongo fanboi)
MySQL is very similar to other SQL databases, so I send You to the topić:
Convert SQL table to mongoDB document
You can use the following project.It requires solr like configuration file to be written.Its very simple and straight forward.
http://code.google.com/p/sql-to-mongo-importer/
Try this:
Automated conversion of MySQL dump to Mongo updates using simple r2n mappings.
https://github.com/virtimus/mysql2mongo