Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
ORM for every database: redis, mysql, neo4j, mongodb, rethinkdb, postgres, sqlite, tingodb
CaminteJS is cross-db ORM for nodejs, providing common interface to access most popular database formats.
mysql, sqlite3, riak, postgres, couchdb, mongodb, redis, neo4j, firebird, rethinkdb, tingodb
First install node.js. Then:
$ npm install caminte -g
First, we need to define a connection.
For MySQL database need install mysql client. Then:
$ npm install mysql -g
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "mysql",
host : "localhost",
port : "3306",
username : "test",
password : "test",
database : "test"
pool : true // optional for use pool directly
};
var schema = new Schema(db.driver, db);
For Redis database need install redis client. Then:
$ npm install redis -g
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "redis",
host : "localhost",
port : "6379"
};
var schema = new Schema(db.driver, db);
For SQLite database need install sqlite3 client. Then:
$ npm install sqlite3 -g
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "sqlite3",
database : "/db/mySite.db"
};
var schema = new Schema(db.driver, db);
Models are defined through the Schema
interface.
// define models
var Post = schema.define('Post', {
title: { type: schema.String, limit: 255 },
content: { type: schema.Text },
params: { type: schema.JSON },
date: { type: schema.Date, default: Date.now },
published: { type: schema.Boolean, default: false, index: true }
});
// simplier way to describe model
var User = schema.define('User', {
name: String,
bio: schema.Text,
approved: Boolean,
joinedAt: Date,
age: Number
});
// models also accessible in schema:
schema.models.User;
schema.models.Post;
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
// creates instance methods:
// user.posts(conds)
// user.posts.build(data) // like new Post({userId: user.id});
// user.posts.create(data) // build and save
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
// creates instance methods:
// post.author(callback) -- getter when called with function
// post.author() -- sync getter when called without params
// post.author(user) -- setter when called with object
// work with models:
var user = new User;
user.save(function (err) {
var post = user.posts.build({title: 'Hello world'});
post.save(console.log);
});
User.validatesPresenceOf('name', 'email')
User.validatesLengthOf('password', {min: 5, message: {min: 'Password is too short'}});
User.validatesInclusionOf('gender', {in: ['male', 'female']});
User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']});
User.validatesNumericalityOf('age', {int: true});
User.validatesUniquenessOf('email', {message: 'email is not unique'});
user.isValid(function (valid) {
if (!valid) {
user.errors // hash of errors {attr: [errmessage, errmessage, ...], attr: ...}
}
})
var post = new Post();
Save model (of course async)
Post.create(function(err){
// your code here
});
// same as new Post({userId: user.id});
user.posts.build
// save as Post.create({userId: user.id}, function(err){
// your code here
});
user.posts.create(function(err){
// your code here
});
Get all instances
// all published posts
var Query = Post.all();
Query.where('published', true).desc('date');
Query.run({}, function(err, post){
// your code here
});
// all posts
Post.all(function(err, posts){
// your code here
});
// all posts by user
Post.all({where: {userId: 2}, order: 'id', limit: 10, skip: 20}, function(err, posts){
// your code here
});
// the same as prev
user.posts(function(err, posts){
// your code here
})
Find instances
// all posts
Post.find(function(err, posts){
// your code here
});
// all posts by user
var Query = Post.find();
Query.where('userId', 2);
Query.order('id', 'ASC');
Query.skip(20).limit(10);
Query.run({},function(err, posts){
// your code here
});
// the same as prev
Post.find({where: {userId: user.id}, order: 'id', limit: 10, skip: 20}, function(err, posts){
// your code here
});
Find if exists or create instance.
// find user by email
User.findOrCreate({
email : 'example@example.com'
}, {
name : 'Gocha',
age : 31
}, function(err, user){
// your code here
});
Get one latest instance {where: {published: true}, order: 'date DESC'}
Post.findOne({where: {published: true}, order: 'date DESC'}, function(err, post){
// your code here
});
// or
var Query = Post.findOne();
Query.where('published',true).desc('date');
Query.run({}, function(err, post){
// your code here
});
Find instance by id
User.findById(1, function(err, user){
// your code here
})
Update if exists or create instance
Post.updateOrCreate({
id: 100
}, {
title: 'Riga',
tag: 'city'
}, function(err, post){
// your code here
});
// or
User.updateOrCreate({
email: 'example@example.com'
}, {
name: 'Alex',
age: 43
}, function(err, user){
// your code here
});
Update if exists instance
User.update({
where : {
email: 'example@example.com'
}
}, {
active: 0
}, function(err, user){
// your code here
});
// or
Post.update({
id: {
inq: [100, 101, 102]
}
}, {
tag: 'city'
}, function(err, post){
// your code here
});
Count instances
// count posts by user
Post.count({where: {userId: user.id}}, function(err, count){
// your code here
});
Remove instances.
// remove all unpublished posts
Post.remove({where: {published: false}},function(err){
// your code here
});
Destroy instance
User.findById(22, function(err, user) {
user.destroy(function(err){
// your code here
});
});
// or
User.destroyById(22, function(err) {
// your code here
});
Destroy all instances
User.destroyAll(function(err){
// your code here
});
Post.scope('active', { published : true });
Post.active(function(err, posts){
// your code here
});
User.prototype.getNameAndAge = function () {
return this.name + ', ' + this.age;
};
var Query = User.find();
Query.where('active', 1);
Query.order('id DESC');
Query.run({}, function(err, users) {
// your code here
});
var Query = User.find();
Query.where('userId', user.id);
Query.run({}, function(err, count){
// your code here
});
// the same as prev
User.find({where: {userId: user.id}}, function(err, users){
// your code here
});
Specifies a greater than expression.
Query.gt('userId', 100);
Query.where('userId').gt(100);
// the same as prev
User.find({
where: {
userId: {
gt : 100
}
}
}}, function(err, users){
// your code here
});
Specifies a greater than or equal to expression.
Query.gte('userId', 100);
Query.where('userId').gte(100);
// the same as prev
User.find({
where: {
userId: {
gte : 100
}
}
}}, function(err, users){
// your code here
});
Specifies a less than expression.
Query.lt('visits', 100);
Query.where('visits').lt(100);
// the same as prev
Post.find({
where: {
visits: {
lt : 100
}
}
}}, function(err, posts){
// your code here
});
Specifies a less than or equal to expression.
Query.lte('visits', 100);
Query.where('visits').lte(100);
// the same as prev
Post.find({
where: {
visits: {
lte : 100
}
}
}}, function(err, posts){
// your code here
});
Matches all values that are not equal to the value specified in the query.
Query.ne('userId', 100);
Query.where('userId').ne(100);
// the same as prev
User.find({
where: {
userId: {
ne : 100
}
}
}}, function(err, users){
// your code here
});
Matches any of the values that exist in an array specified in the query.
Query.in('userId', [1,5,7,9]);
Query.where('userId').in([1,5,7,9]);
// the same as prev
User.find({
where: {
userId: {
in : [1,5,7,9]
}
}
}}, function(err, users){
// your code here
});
Selects rows where values match a specified regular expression.
Query.regex('title', 'intel');
Query.where('title').regex('intel');
// the same as prev
Post.find({
where: {
title: {
regex : 'intel'
}
}
}}, function(err, posts){
// your code here
});
Pattern matching using a simple regular expression comparison.
Query.like('title', 'intel');
// the same as prev
Post.find({
where: {
title: {
like : 'intel'
}
}
}}, function(err, posts){
// your code here
});
Pattern not matching using a simple regular expression comparison.
Query.nlike('title', 'intel');
// the same as prev
Post.find({
where: {
title: {
nlike : 'intel'
}
}
}}, function(err, posts){
// your code here
});
Matches values that do not exist in an array specified to the query.
Query.nin('id', [1,2,3]);
// the same as prev
Post.find({
where: {
title : {
nin : [1,2,3]
}
}
}}, function(err, posts){
// your code here
});
Sets the sort column and direction.
Query.sort('title DESC');
Query.sort('title', 'DESC');
// the same as prev
Post.find({
order: 'title DESC'
}}, function(err, posts){
// your code here
});
Sets the group by column.
Query.group('title');
// is the same as
Post.find({
group: 'title'
}}, function(err, posts){
// your code here
});
Sets the sort column and direction ASC.
Query.asc('title');
// is the same as
Query.sort('title ASC');
// the same as prev
Post.find({
order: 'title ASC'
}}, function(err, posts){
// your code here
});
Sets the sort column and direction DESC.
Query.desc('title');
// is the same as
Query.sort('title DESC');
// the same as prev
Post.find({
order: 'title DESC'
}}, function(err, posts){
// your code here
});
The skip method specifies at which row the database should begin returning results.
Query.skip(10);
// the same as prev
Post.find({
skip: 10
}}, function(err, posts){
// your code here
});
The limit method specifies the max number of rows to return.
Query.limit(10);
// the same as prev
Post.find({
limit: 10
}}, function(err, posts){
// your code here
});
Limits the number of elements projected from an array. Supports skip and limit slices.
Query.slice([20,10]);
// the same as prev
Post.find({
skip: 20,
limit: 10
}}, function(err, posts){
// your code here
});
Check whether a value is within a range of values.
Query.between('created', ['2013-01-01','2013-01-08']);
// the same as prev
Post.find({
where: {
created: {
between : ['2013-01-01','2013-01-08']
}
}
}}, function(err, posts){
// your code here
});
The following callbacks supported:
- afterInitialize
- beforeCreate
- afterCreate
- beforeSave
- afterSave
- beforeUpdate
- afterUpdate
- beforeDestroy
- afterDestroy
- beforeValidation
- afterValidation
User.afterUpdate = function (next) {
this.updated_ts = new Date();
this.save();
// Pass control to the next
next();
};
Each callback is class method of the model, it should accept single argument: next
, this is callback which
should be called after end of the hook. Except afterInitialize
because this method is syncronous (called after new Model
).
required only for mysql NOTE: it will drop User and Post tables
schema.automigrate();
var user = new User;
// afterInitialize
user.save(callback);
// beforeValidation
// afterValidation
// beforeSave
// beforeCreate
// afterCreate
// afterSave
// callback
user.updateAttribute('email', 'email@example.com', callback);
// beforeValidation
// afterValidation
// beforeUpdate
// afterUpdate
// callback
user.destroy(callback);
// beforeDestroy
// afterDestroy
// callback
User.create(data, callback);
// beforeValidate
// afterValidate
// beforeCreate
// afterCreate
// callback
Read the tests for usage examples: ./test/common_test.js Validations: ./test/validations_test.js
To use custom adapter, pass it's package name as first argument to Schema
constructor:
mySchema = new Schema('couch-db-adapter', {host:.., port:...});
Make sure, your adapter can be required (just put it into ./node_modules):
require('couch-db-adapter');
To run all tests (requires all databases):
npm test
If you run this line, of course it will fall, because it requres different databases to be up and running, but you can use js-memory-engine out of box! Specify ONLY env var:
ONLY=memory nodeunit test/common_test.js
of course, if you have redis running, you can run
ONLY=redis nodeunit test/common_test.js
Now all common logic described in ./lib/*.js
, and database-specific stuff in ./lib/adapters/*.js
. It's super-tiny, right?
If you have found a bug please write unit test, and make sure all other tests still pass before pushing code to repo.
(The MIT License)
Copyright (c) 2011 by Anatoliy Chakkaev <mail [åt] anatoliy [døt] in>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
ORM for every database: redis, mysql, neo4j, mongodb, rethinkdb, postgres, sqlite, tingodb
The npm package caminte receives a total of 216 weekly downloads. As such, caminte popularity was classified as not popular.
We found that caminte demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.