一个自用的极简 ORM,带三方缓存支持——Toshihiko

目前花瓣网和大搜车都有项目在用该 ORM。

使用很简单,且在上层没做类似于 group byjoin 等降低效率的 API 支持,因为 mysql 本身效率就不是特别高。

支持三方缓存——比如 memcached,也可以自己实现一个 toshihiko-xxx 作为自己的缓存层。

Repo 地址在:https://github.com/XadillaX/Toshihiko

具体用法看文档。


Toshihiko

Toshihiko
Toshihiko
Build Status
Build Status
Coverage Status
Coverage Status
Code Quality
Code Quality
License
License

A simple ORM for node.js in Huaban with :heart:. For performance, this ORM does not provide operations like in, group by, join
and so on.

Toshihiko
Toshihiko

Installation

$ npm install toshihiko

Document

Initialize

You should create a Toshihiko object to connect to MySQL:

var T = require("toshihiko");
var toshihiko = new T.Toshihiko(database, username, password, options);

Options can include these things:

  • host: hostname or IP of MySQL. Defaults to localhost.
  • port: port of MySQL. Defaults to 3306.
  • cache: if you want to cache support, let it be an cache layer object or cache layer configuration which will be mentioned below. Defaults to undefined.
  • etc... (All options in module mysql will be OK)

Cache

Toshihiko now is using new cache layer! You can choose your cache layer by your self!

Pass an object to cache of options like:

var toshihiko = new T.Toshihiko(database, username, password, {
    cache: YOUR_CACHE_LAYER
});

The YOUR_CACHE_LAYER may be an instance of Toshihiko cache layer object like toshihiko-memcacehd (you can implement a cache layer by yourself).

What's more, YOUR_CACHE_LAYER may be a configuration object which should include name or path.

For an example,

var toshihiko = new T.Toshihiko(database, username, password, {
    cache: {
        name: "memcached",
        servers: "...",
        options: {}
    }
});

will search for package toshihiko-memcached and pass servers, options to create a toshihiko-memcached object. By default, Toshihiko support memcached as cache layer by using package toshihiko-memcacehd.

You can get the cache object in Toshihiko by getting the variable:

var cache = toshihiko.cache;

Define a Model

Define a model schema:

var Model = toshihiko.define(tableName, [
    { name: "key1", column: "key_one", primaryKey: true, type: Toshihiko.Type.Integer },
    { name: "key2", type: Toshihiko.Type.String, defaultValue: "Ha~" },
    { name: "key3", type: Toshihiko.Type.Json, defaultValue: [] },
    { name: "key4", validators: [
        function(v) {
            if(v > 100) return "`key4` can't be greater than 100";
        },
        function(v) {
            // blahblah...
        }
    ] },
    { name: "key5", type: Toshihiko.Type.String, allowNull: true }
], options);

You can add extra model functions by yourself:

Model.sayHello = function() {
    this.find(function(err, rows) {
        console.log(err);
        console.log(rows);
    });
};

options is optional. You can specify Memcached here if you haven't defined it in Toshihiko. Otherwise, you can let
it be null when you don't want to use Memcached in this Model but you had specify it in Toshihiko.

Query & Update

Toshihiko uses chain operations. Eg:

Model.where(condition).limit(limit).orderBy(order).find(callback);
Model.where(condition).limit(limit).delete(callback);
Model.findById(primaryKeysId, callback);
Model.where(condition).update(data, callback);

where

condition is an JSON object with keys:

  • A field name
  • $and
  • $or
Field Name
Value

For field name, the value can be a certain value. Eg:

{
    key1: 1
}
Operators

The value can be a JSON object with comparison operators $eq / ===, $neq / !==, $gt(e) / >(=), $lt(e) / <(=), $like.

Eg:

{
    keys1: {
        $neq: value
    }
}

value can be a certain value or an array with logic AND.

Eg. $neq: 5 or $neq: [ 5, 2 ].

Logic

You can use logic symbols as well:

{
    keys1: {
        $or: {
            $eq: 1,
            $neq: 2
        }
    }
}

Notice: you can define logic and operators with many many levels.

$and And $or

You can use these two logic with many many levels.

{
    $or: {
        $or: { $or: ... },
    }
}

And the last level can be like that:

{
    $and: {
        KEY: { REFER TO ABOVE `Field Name` }
    }
}

limit

For examples:

foo.limit("1");         ///< skip 1
foo.limit("0,30");      ///< skip 0, limit 30
foo.limit([ 0, 30 ]);   ///< skip 0, limit 30
foo.limit([ 1 ]);       ///< skip 1
foo.limit({ skip: 0, limit: 1 });   ///< skip 0, limit 1
foo.limit({ skip: 1 }); ///< skip 1
foo.limit({ limit: 1 });///< limit 1

orderBy

For examples:

foo.orderBy("key1 asc");
foo.orderBy([ "key1 asc", "key2 desc" ]);
foo.orderBy({ key1: "asc", key2: "desc", key3: 1, key4: -1 });

count

Count the records with a certain condition:

foo.where(condition).count(function(err, count) {});

find

With the conditions, limit and orders to find all records:

foo.where(condition).find(function(err, rows) {
    //...
}, withJson);

Notice: the parameter withJson is an optional parameter. If it's true, elements in rows are JSON objects. Otherwise,
they are all Yukari objects.

findOne

It's similar with find, but it will just find only one record.

foo.where(condition).findOne(function(err, row) {
    //...
}, withJson);

Notice: withJson is the same as above.

findById

foo.findById(primaryKeysId, function(err, bar) {
}, withJson);

primaryKeysId can be a string or an object.

When there're several primary keys in one table, this value may be like:

{
    key1: 1,
    key2: 2,
}

If there's only one primary key, you can just pass a string, number or some other base type value.

For examples:

foo.findById({ key1: 1, key2: 2 }, callback);
foo.findById(1, callback);

update

foo.where(condition).update(data, function(err, result) {});

data is an object that includes your changed data. Eg:

{
    key1: 12,
    key2: "123",
    key3: "{{key3 + 1}}"
}

String with {{...}} will be parsed as SQL statement. For example, you can let it be {{CONCAT(`key3`, ".suffix")}}
or any others statement you want to use.

Notice: result is something like:

{ fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '(Rows matched: 1  Changed: 1  Warnings: 0',
  protocol41: true,
  changedRows: 1 }

delete

foo.where(condition).delete(function(err, result) { /** ... */ });

┏ (゜ω゜)=☞ Promise-Liked

For find, findOne, findById, update and delete, you can use it without callback function.

Whether you used callback function or not, these function will return a ResultPromisor object. You can use it like:

ResultPromisor::success
var Q = foo.find();
Q.success(function(result) { /** ... */ });
ResultPromisor::error
var Q = foo.find();
Q.error(function(err) { /** ... */ });
ResultPromisor::finished
var Q = foo.find();
Q.finished(function(err, result) { /** ... */ });

Yukari Object

Yukari object is the data entity object.

rows in Model.find(function(err, rows) {}) is an array with Yukari objects unless you use withJson parameter.

Also, you can get a new Yukari object by calling Model.build().

We assume all Yukari(s) below are created from Model.find() except Model.build().

Model.build()

You can pass a JSON object to this function to generate a new Yukari object:

Model.build({
    key1    : 1,
    key2    : 2,
    key3    : "3"
});

Yukari::toJSON()

Transform Yukari object to a simple original JSON object:

var json = yukari.toJSON();
console.log(json);

Yukari::insert()

If your Yukari object is created from Model.build(), you should use this function to insert data to database.

var yukari = Model.build({ ... });
yukari.insert(function(err, yukari) {
    //...
});

Yukari::update()

Change this Yukari data to database.

yukari.update(function(err, yukari) {
    //...
});

Notice: "{{..}}" operation is not supported here.

Yukari::save()

If it's a new Yukari object, it will call insert. Otherwise, it will call update.

yukari.save(function(err, yukari) {
    //...
});

Yukari::delete()

Delete this record from database.

yukari.delete(function(err, affectedRows) {});

Custom Field Type

There're 4 kind of types in Toshihiko as default.

  • Type.Float
  • Type.Integer
  • Type.Json
  • Type.String

You can code a custom field type by yourself.

Here's the template:

var Type = {};
Type.name = "type";
Type.needQuotes = false;    ///< Is this type need quotes in SQL statement?
Type.restore = function(v) {
    // v is a parsed value,
    // you should transform
    // it to the type that
    // SQL can recognize
    return v;
};
Type.parse = function(v) {
    // v is a original value,
    // you should parse it
    // into your own type
    return v;
};
Type.defaultValue = 0.1;    ///< Default value

You can refers to lib/fieldType/json.js to get more information.

Contribute

You're welcome to pull requests!

Thanks to:

「雖然我覺得不怎麼可能有人會關注我」

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,631评论 18 399
  • 一. Java基础部分.................................................
    wy_sure阅读 3,811评论 0 11
  • 一、MemCache简介 session MemCache是一个自由、源码开放、高性能、分布式的分布式内存对象缓存...
    李伟铭MIng阅读 3,810评论 2 13
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,657评论 18 139
  • 沉没成本:是指由于过去的决策已经发生了的,而不能由现在或将来的任何决策改变的成本。人们在决定是否去做一件事情的时候...
    好听的暖阳阅读 203评论 0 1