Coder Social home page Coder Social logo

caminte's People

Contributors

amilajack avatar atha-github avatar biggora avatar bitdeli-chef avatar c-o-d-e-a-r-t-i-s-t avatar cyrilzhao avatar deiga avatar eliascodes avatar foxdog05000 avatar huttj avatar innerdvations avatar jbenden avatar jmlaya avatar joaoafrmartins avatar justkant avatar kukuhpro avatar lisandromc avatar lpj145 avatar mdpauley avatar mgenereu avatar neuroscr avatar novan avatar picharras avatar rhalff avatar samirbr avatar timbowhite avatar tyronedougherty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

caminte's Issues

SQLITE between bug

Using {where: {fld: {between: [1,10]}}}
Generates following SQL, ' fld BETWEEN 1,10 '
which should be ' fld BETWEEN 1 AND 10'

Changed the function parseCond in sqllite3.js:751
with
case 'between':
sqlCond += ' BETWEEN ';
val = self.toDatabase(props[key], conds[key]);
break;

Have created a pull request.

save() does not update

The model's save() method does not update because the model's id is not being passed in data to the adapter's own save() method.

Example:

var caminte = require('caminte'),
    Schema  = caminte.Schema,
    schema  = new Schema('sqlite3', {database: ':memory:'}),
    Foo = schema.define('foo', {
        bar: { type: schema.String}
    },{
        primaryKeys: ['id'],
    });

schema.on('connected', function(){
    var f = new Foo({
        bar: 'baz'
    });

    f.save(function(err, fnew){
        if (err) throw err;
        console.log('f saved', fnew);
        fnew.bar = 'baaaaaaaaaaaaaaaaaaz';
        fnew.save(function(err, fnewer){
            if (err) throw err;
            console.log('fnew saved', fnew);
        });
    });
});

Results in:

/.../foo.js:20
            if (err) throw err;
                           ^
Error: SQLITE_ERROR: no such column: undefined

I'll issue a pull request shortly.

Slow Redis?

On a redis backend, I've tried a combination of
postModel.findOne({ where: {}, order: 'id DESC'}, function(err, post) {
postModel.find().order('id', 'DESC').limit(1).run({},function(err, posts) {
postModel.all().order('id', 'DESC').limit(1).run({},function(err, posts) {
to get a max id on a large collection of posts with non-contigous IDs
They all take around 68 seconds to complete.

By if I manually run
sort s:post BY post:*->id DESC LIMIT 0 1
directly on redis, I can get the max id in under 2 secs

Is there another way I should be writing the query?

Error when using Model.update Postgres

I got this message when call the method update of Model:

E:\projects\lounge-api\node_modules\caminte\lib\adapters\postgres.js:145
if (props[key] || key === 'id') {
^
ReferenceError: props is not defined
at E:\projects\lounge-api\node_modules\caminte\lib\adapters\postgres.js:145:
13
at Array.forEach (native)
at PG.update (E:\projects\lounge-api\node_modules\caminte\lib\adapters\postg
res.js:143:23)
at Function.update (E:\projects\lounge-api\node_modules\caminte\lib\abstract
-class.js:1018:29)
at E:\projects\lounge-api\app\controllers\UsersController.js:39:26
at E:\projects\lounge-api\node_modules\caminte\lib\abstract-class.js:542:17
at E:\projects\lounge-api\node_modules\caminte\lib\abstract-class.js:503:17
at PG. (E:\projects\lounge-api\node_modules\caminte\lib\adapters
postgres.js:191:13)
at null.callback (E:\projects\lounge-api\node_modules\caminte\lib\adapters\p
ostgres.js:56:9)
at Query.handleReadyForQuery (E:\projects\lounge-api\node_modules\pg\lib\que
ry.js:82:10)

It seems to be missing the definition of props.

Please check and fix it
Regards

Adapter loses client

After initialization of two classes creating two mongodb connections, I attempt a findOne using on of the class. At this point, the call to constr.schema.adapter.all in the abstract-class.js#all function appears to be correct except the adapter.client is gone. There's no property even though the mongo class assigned it successfully (saw this in trace). I'll add more to this ticket as I discover more.

Redis allows duplicate entries on a unique column

When I defined a model with the property 'email' which should be unique, I was able to create multiple entries that had the same value with no errors.

My model definition looks like this

var Model = schema.define('Model', {
    email: { type: schema.String, "null": false, unique: true, index: true }
});

I am creating the instances like this

var model = new Model({ email: "[email protected]" });
model.save(function (err) {
    err == null;  //true
});

After doing the above twice, I query all entries like this

Model.all().run({}, function (err, results) {
    err == null;  
    results == [
        { email: '[email protected]', id: 1 },
        { email: '[email protected]', id: 2 }
    ]; 
});

Unless there is a different way to specify a property as unique, this seems broken.

Error cannot call method defineForeignKey

Hi, i am using neo4j adapter, but for some reason i am not able to use relations

My user model

var userSchema =  caminte.define('Users', {
    username:     { type: String, length: 20 },
    email:        { type: String, length: 65  },
    password:     { type: String, length: 12 },
    activated:    { type: Number},
    account_type: { type: Number},
    created_at:   { type: Date,  default: Date.now },
    last_seen:    { type: Date },
    userId:       { type: Number}
});

userSchema.hasMany('Post',   {as: 'posts',  foreignKey: 'userId'});

module.exports = userSchema;

My post model

var postSchema =  caminte.define('Post', {
    title:     { type: String, length: 20 }
});

postSchema.belongsTo('User', {as: 'author', foreignKey: 'userId'});

module.exports = postSchema;

My controller

User.create(userData, function(err, user){
        if(user)
        {
             var post = user.posts.build({title: 'Hello world'});
             post.create(console.log);
            return self.redirect('/activated');
        }
    });

All other methods like Create, All, are working but if i define a relation, i get the following error

Cannot call method defineForeignKey

And its refering to user model on line 14 which is

userSchema.hasMany('Post',   {as: 'posts',  foreignKey: 'userId'});

Could you please give me hint?

Please stop violating copyrights

I don't mind of using my code in your project while you keep my authorship in copyright. Please read copyright notice in jugglingdb project.

Neo4j

I've looked at the documentation, but I dont see examples related for Neo4j. Any chance there can be some example showing relationships and some of the advanced Cypher querying?

All schema types

what are all the schema types? Do you support Array of integers? Array of strings? Enum?
If yes, how?

no database selected if using connection pooling

Hi,

if i am using connection pooling i get the error "no database selected". If i set pool to false in the settings it works.
the database option is set in the connection settings.

thanks and best

SQLITE_ERROR: no such table

This code

var Schema = require('caminte').Schema;


var schema = new Schema('sqlite', { database: 'test.db' });


var User = schema.define('User', {
    name:         String,
    bio:          Schema.Text,
    approved:     Boolean,
    joinedAt:     Date,
    age:          Number
});

var U = schema.models.User;
var u = new U({
    name: "Herro my name is ..."
});
u.save(function(err, usr){
    if(err){
        console.log("Save err", err, err.stack);
        return;
    }
    console.log("Saved:", usr);
    U.count({}, function(err,c){
        if(err){
            console.log("Count err", err, err.stack);
            return;
        }
        console.log("User has "+c+" objects.");
    })
});

gives this output

/usr/local/bin/node sqlite.js
Save err { [Error: SQLITE_ERROR: no such table: User] errno: 1, code: 'SQLITE_ERROR' } Error: SQLITE_ERROR: no such table: User

Process finished with exit code 0

Am I doing something wrong ?

Error with abstract-class.js

Hello,

below of is a piece of code, please explain me what I'm doing wrong?
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "redis",
host : "localhost",
port : "6379"
};
var schema = new Schema(db.driver, db);

var User = schema.define('User', {
title: { type: schema.String, limit: 255 },
fname: { type: schema.String},
lname: { type: schema.String}
});
User.create({title: "dok", fname: "Max", lname: "Manus"}, function(err, data){
console.log(err, data);
})

The error i get is:

****/caminte/lib/abstract-class.js:114
if (BASE_TYPES.indexOf(type.name) === -1) {
^
TypeError: Cannot read property 'name' of undefined

How to fix this?

Best regards,
Mr. Love

JSON values converted to strings with some NoSQL adapters

Columns of type JSON result in objects being written as strings with some adapters (redis in my case), e.g.:

{"foo": "bar"}

yields:

"{\"foo\":\"bar\"}"

The immediate cause is that AbstractClass._forDB method checks this.schema.adapter.name (which is not always set inside adapters) against a pre-defined list of NoSQL drivers, from which redis is absent.

Possible MongoDB race condition

If the MongoDB adapter can't get a connection in one second, the setTimeout section of the define accesses the collection method to create indices. The collection method expects the this.client to have a value but the connection hasn't been established yet. Accessing the collection property of this.client results in an "TypeError: Cannot read property 'collection' of undefined". Here's the patch that added the this.client dependency:
ec6718c#diff-644d15beeed31d7ee15ce6aae98c3fc8

Usage: What is a good way to organize models into different files?

I like to create my models with prototype methods and I'm a bit at a loss as to how this is supposed to be achieved with caminte.
Currently my model looks like this

module.exports = function (schema) {
    var Session = schema.define("Schema", {
        expires:    {type: String, default: ""},
        userId:      {type: String, default: ""},
        token:   {type: String, default: ""},
    });

    Session.prototype.lifetime = function () {
        return 0; // + config.session.lifetime;
    };
...
        return Session;

But it's really clunky to declare everything in an anonymous function. And since I have multiple models I don't want to initialize the schema in each model

MongoDB driver 2.0

The current adapter dosen't work with new mongodb driver. I indexed a couple of problems and, if nobody is already working on it, I could write a new adapter.

Let me know

Finding objects from relations/setup relations

Hi everyone,

I have been trying 2 for days to figure the way the relations work with Caminte and I can't figure out.

I have the following Models :

var Class1 = schema.define(className, {
    objectId          : { type: schema.String, unique: true, index: true },
    createdAt         : { type: schema.Date,                 index: true },
    updatedAt         : { type: schema.Date,                 index: true }
}, {
    primaryKeys: ["objectId"]
});

///// RELATIONS /////
Class1.hasMany(Class2,  {as: 'otherclasses',  foreignKey: "objectId"});

var Class2 = schema.define(className, {
    objectId          : { type: schema.String, unique: true, index: true },
    createdAt         : { type: schema.Date,                 index: true },
    updatedAt         : { type: schema.Date,                 index: true }
}, {
    primaryKeys: ["objectId"]
});

I would like to be able to query all the objects in "otherclasses".
I'm trying this way : but obviously it doesn't sound to be the right way :

var query = instanceOfClass1.otherclasses.find();
      query.limit(10);
      query.run({}, function(err, results){
      });

Can anyone help me out with that ?

Adapter : REDIS
Error thrown :

TypeError: undefined is not a function
    at ModelConstructor.<anonymous> (node_modules/caminte/lib/abstract-class.js:1117:24)
    at Function.<anonymous> (node_modules/caminte/lib/abstract-class.js:455:9)
    at BridgeToRedis.<anonymous> (node_modules/caminte/lib/adapters/redis.js:390:9)
    at node_modules/caminte/lib/adapters/redis.js:85:25
    at node_modules/redis/index.js:592:9)
    at RedisClient.return_reply (node_modules/redis/index.js:685:13)
    at ReplyParser.<anonymous> (node_modules/redis/index.js:321:14)
    at ReplyParser.EventEmitter.emit (events.js:95:17)
    at ReplyParser.send_reply (node_modules/redis/lib/parser/javascript.js:300:10)
    at ReplyParser.execute (node_modules/redis/lib/parser/javascript.js:211:22)

Promise support feature

Hi there, I'm going to implement support for Promise in my caminte fork and I''ll create pull request when ready. Is there any hints or idea from you?

Transactions

Hi,

How to use transactions?

Maybe looks like this:

schema.begin();

Model1.create()...
Model2.update()...

schema.commit() / rollback()

Thanks

Field "id" in SQL Databases

Hi, my name is Alan and I've a problem using SQL databases. Caminte force that my tables have an "id" field and I do not use the default name. How can I fix this?

Best Regards

Pool

Can i configure caminte to use mysql pool?

Mongo - User.find() returns always and only first result

Schema:

var User = schema.define('user', {
      //User details
          steamid       :{ type: String },
          personaname   :{ type: String },
          avatar        :{ type: String },
          openID        :{ type: String}
    // Other unrelated schema
        [...]
    });

Search DB

// Should be false, returns true
      User.find({'steamid' : '76561198150261243'}, function (err, doc) {
        console.log(doc);
        if (!doc) {
          console.log('creating user, beeboobeeboop');
        } else {
          console.log('User already in DB');
        }
      })

Database collections:
Collection

The single collection has a 'steamid' of '76561198077435075'. And when running the User.find(), I am giving it a different ID to search (76561198150261243). However, the doc still returns the first entry for steamid 76561198077435075

logging out doc

Schema.autoupdate - sqlite3

Hi found several issue:

SQLite3.prototype.autoupdate = function (cb) {
    var self = this;
    var wait = 0;
    Object.keys(this._models).forEach(function (model) {
        wait += 1;
        //self.queryAll('SHOW FIELDS FROM ' + this.tableEscaped(model), function (err, fields) {
        self.queryAll('PRAGMA table_info(' + self.tableEscaped(model) + ')', function (err, fields) {
            self.alterTable(model, fields, done);
        });
    });
this.tableEscaped // caused error no tableEscaped. 'this' was different context (not adapter instance)

//this should change to self
self.tableEscaped 
SHOW FIELDS FROM <tablename> // is not supported by sqlite

use PRAGMA table_info(<tablename>> instead

By the way, the functions return fails:

{ [Error: SQLITE_ERROR: duplicate column name: name] errno: 1, code: SQLITE_ERROR' }

JSON datatype to postgre

I want to use new datatype JSONB and original JSON type for postgresql 9.4 .

Coud you implement in caminte?

Thanks

Server error on "select from Class group by field" with 1,000,000+ records

Hi! I have a class containing 1,000,000+ records with the following properties start_of_life, end_of_life, hist_id. hist_id is shared among different versions of a record. The following query "select min(start_of_life), max(end_of_life), hist_id from SomeVertex group by hist_id" causes the server to throw an exception (SEVERE Internal server error: java.net.SocketException: Socket closed [ONetworkProtocolHttpDb])

Orientdb versions: 2.0-M2, 2.0-M3

Any ideas or advice?

How select just some fields?

Hello guys, I was looking for some way to select just some fields on my db.
I'm using MySQL, and my database has a field with big Text but I don't want to get it.

I was thinking about create 2 separated models, one with the big field an other without.

Anyone has any ideia about?

Thanks.

caminte conflicts with "cheerio" module

Conflict with https://github.com/cheeriojs/cheerio

TypeError: Cannot redefine property: length
    at Function.defineProperty (native)
    at \node_modules\caminte\lib\abstract-class.js:24:24
    at Array.forEach (native)
    at Function.Object.defineProperty.value (\node_modules\caminte\lib\abstract-class.js:21:15)
    at Object.<anonymous> (\node_modules\cheerio\lib\cheerio.js:99:3)

Problem in

Object.defineProperty(Object.prototype, "extend", {
    enumerable: false,
    value: function(from) {
        var props = Object.getOwnPropertyNames(from);
        var dest = this;
        props.forEach(function(name) {
            if (name in dest) {
                var destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
            }
        });
        return this;
    }
});

Error in redis-adaptor, line 416

Hi,

I was getting TypeError: Cannot set property 'id' of undefined on line 416 when calling all on a model using the redis adaptor. I had a quick look into the source and the culprit appears to be the line:

 filter.where.id = {
        gt: 0
      }

I modified it locally to:

 filter.where = {
      id: {
        gt: 0
      }

and it appears to have worked successfully.

parameter of count API in Abstract-class.js

Hi, biggora

Thank you very much for caminte.js.
This is my first message on github in English.
I have a problem with the count API, please have a check whether it is a issue or not.

A.We have these code in Common API [count] from wiki.

// count posts by user
Post.count({where: {userId: user.id}}, function(err, count){
// your code here

});

There is a [where] condition({userId: user.id}) in a json object in the first parameter, let's call this parameter a [filter].

B.In Abstract-class.js, the first parameter is the [filter] with [where] condition, and it be passed to count API of every adapter class, like MongoDB.js.

AbstractClass.count = function (params, callback) {
if (stillConnecting(this.schema, this, arguments)) {
return;
}
if (typeof params === 'function') {
callback = params;
params = null;
}
params = buildQuery(params, this);
this.schema.adapter.count(this.modelName, callback, params); // passing parameter

};

C: In MongoDB.js, the 3trd parameter is the filter come from first step A, and parse it as a object of where condition directly.

MongoDB.prototype.count = function count(model, callback, filter) {
var cond = buildWhere(filter); // I got {where: {'$columnName':{gt: 999}}" here while I using a filter like {where: {'columnName':{gt: 999}}} in the step A
this.collection(model).count(cond, callback);

};

I saw most of count API in other adapter class, parameter like the [filter] in count API of MongoDB.js is a json object of where condition only, but not a filter object with a where condition.

If I change the last code of AbstractClass.count as below, it seems ok.

AbstractClass.count = function (params, callback) {
...
this.schema.adapter.count(this.modelName, callback, params.where ? params.where : params);

}

please have a check on it.

Have a nice day.

updateOrCreate - Redis - update - errors

orm.autoparts.updateOrCreate({where:{id:data.id}}, {need:0} , function(err, part)

-->>Error: parts: no indexes found for where impossible to sort and filter using
redis adapter

orm.autoparts.update({where:{id:data.id}}, {need:0} , function(err, part)

-->> Method update undefined for this adapter

Tests do not pass

***/node_modules/caminte/lib/schema.js:217
this.adapter.define({
^
TypeError: Cannot call method 'define' of undefined

MySQL combination of OR and AND

Hello

After hours of searching through the documentation of why my OR was causing an SQL error I found a bug in the mysql.js file (https://github.com/biggora/caminte/blob/master/lib/adapters/mysql.js)

At line 563 you can find this line of code:

return 'WHERE ' + orop + cs.join(' AND ');

But when using a combination of AND and OR like this:

newsitem.find({where: {id: 217, or: [{department: 1}, {department: 2}]}}, function(error, items) {
});

it will result in

SELECT * FROM newsitem WHERE (department=1 OR department=2) id=217

It misses an AND. By changing line 563 in the mysql.js file to

var glue = or.length > 0 && cs.length > 0 ? 'AND' : '';
return 'WHERE ' + orop + glue + cs.join(' AND ');

will fix the error

Complex statements like

SELECT * FROM newsitem_view WHERE (
    (showfrom < "2013-11-20 15:18:24" AND showuntil > "2013-11-20 15:16:16") OR 
    (showfrom IS NULL AND showuntil IS NULL) OR 
    (showfrom IS NULL AND showuntil > "2013-11-20 15:16:16") OR 
    (showuntil IS NULL AND showfrom < "2013-11-20 15:18:24")
) AND department=3

does not seem possible with CaminteJS, isn't it?

.all doesn't work with just the callback argument

doing the following:

    MyModel.all(function(err, models) {
         console.log(err, models);
    });

produces zero output - the console.log and callback is never called. However the following works:

    MyModel.all({}, function(err, models) {
         console.log(err, models);
    });

So either there is a bug, or the documentation is wrong :)

User defined primary keys in sqlite3 table

I am creating a cloud application. The application involves maintaining a database and so i have designed a table with the following schema :

create table connectioninfo
(
device_id integer primary key,
date_updated integer not null, unique(device_id)
);

The database used is sqlite3 and I am using caminte for performing database related operations. When I am trying to insert or update a record in the table, I am getting the following error :

{ [Error: SQLITE_ERROR: table connectioninfo has no column named id] errno: 1, code: 'SQLITE_ERROR' }

I don't have any field with name 'id' . Is it necessary to have a field with the name 'id' in each table ? Can't I have user defined auto increment primary keys ? If so, how ?

Автоматическое создание таблиц MySQL

Доброго времени суток!

Создал модель, подключаю БД, а она ругается что таблица не создана. Судя по исходникам таблицы должны создаваться сами, но не создаются в чём проблема?

Table 'cryptoengine.block' doesn't exist

Модель

var Block = Schema.define('Block',{
        number: {
            type: Number,
            required: true,
            index: {
                unique: true,
                dropDups: true
            }
        },
        difficulty: {
            type: String
        },
        hash: {
            type: String,
            required: true,
            index: {
                unique: true,
                dropDups: true
            }
        },
        ended_at: {type: Date},
        updated_at: {type: Date, default: Date.now},
        created_at: {type: Date, default: Date.now}
    });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.