How to write an ORM

ORM stands for Object Relationship Mapping, basically an abstraction layer on top the database.

Basic ORM structure:


var _ = require('underscore');
var mysql = require('mysql');

var connection = mysql.createConnection({
  user     : 'root',
  password : "root",
  database : 'chat',
  socketPath  : '/Applications/MAMP/tmp/mysql/mysql.sock',
});

connection.connect(function(err) {
  if (err) {
    console.log('db_connection_err', err);
    return;
  }
});


//do NOT use 'new'
var makeORM = function(name){
  //class-level variables
  var tableName = name;

  //plese use 'new'
  var ORM = function(param){
    this.tableName = tableName;
    if(param){
      //init variables on instance
      this.msg_id = param.msg_id;
      this.text = param.text;
    }
  };

  ORM.findAll = function(callback){
    var sql_query = "select * from " + tableName;
    connection.query(sql_query,  function(err, rows){
      var result = _(rows).map(function(row){
        return ( new ORM(row) );
      });
      callback(result);
    });
  };

  ORM.find = function(){

  };

  ORM.prototype = {
    getID: function(){
      return this.msg_id;
    },
    save: function(){
      //
    },
    update: function(){
      //
    }
  }

  return ORM;
};

//this refers to the 'messages' table
var Messages = makeORM('messages');
Messages.findAll(function(result){
  console.log('result', result);
  _(result).each(function(obj){
    console.log( 'each result also has methods such as getID: ', obj.getID() );
  });
});

connection.end();

ORM results vs. normal database query results

ORM provides another layer of abstraction, and ORM queries tend to return non-generic objects.

Regular database query returns a generic object or most likely, an array of generic objects. Those generic objects haven’t gone through construction, hence don’t have methods. On a side note, SQL language was designed such that the query only specify what is returned but not how the result is returned.

Join table vs join query

Join table is indeed a real table existing in the database.

A join query tends to produce a temporary join table during execution, but that temporary join table is destroyed as soon as the join query is finished.

Advertisements
Standard

One thought on “How to write an ORM

  1. Pingback: Day 28, coffee shop and ORM | Shao

Comments are closed.