New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

grand-central-records

Package Overview
Dependencies
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

grand-central-records

An activerecord-inspired ORM for Node.js

  • 0.1.35
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1
decreased by-90.91%
Maintainers
1
Weekly downloads
 
Created
Source

Grand Central Records

A basic ORM/ActiveRecord library for use in smaller Node projects or frameworks. Work in progress.

TODO

  • Implement Promises in SQL adapters
  • Query joins (see https://www.npmjs.org/package/sql)
  • MySQL Pool Connections
  • Migration / synchronization

Custom ORM

  • Connects with
    • MySQL
    • Postgres
    • SQLite3
  • Chainable queries
  • Raw queries
    • .query() -- executes the given query
    • .queue(query string or chain) (accepts array, string, object)
    • .run() -- executes all queries in the queue
  • Callbacks or promises

Inspiration


Documentation

Getting started

Raw queries

Models

Other functions

Query methods

Postgres


Getting started

### new GCR(connection, [table], [options])

Creating a new instance of the GCR object creates a connection to a new database.

var GCR = require('grand-central-records');

var Model = new GCR({
    adapter: "mysql",
    host: "localhost",
    database: "test",
    username: "admin",
    password: "admin"
}, "users");

Model.find(8, function(err, user){
    if (err) throw err;
    console.log(user.name);
});

Model.select(["name","address"]).where({admin: true}, function(err, result) {
    if (err) throw err;
    result.forEach(function(user) {
        ...
    });
});
### model(table, [options])
  • table string — The name of the table the model is associated with.
  • options json — See above.

Multiple models can also be created from the same database.

var GCR = require('grand-central-records');

var db = new GCR({
    adapter: "mysql",
    host: "localhost",
    database: "test",
    username: "admin",
    password: "admin"
}, { verbose: true });

var User = db.model("users"),
    Project = db.model("projects");

Promises

Execute a query using a callback:

Model.find(52, function(err, res) {...});
Model.find(52).select('id').run(function(err, res) {...});

Or by using promises:

Model.find(52)
  .then(function(res) {
    return res;
  })
  .then(function(res) {
    // do something...
  })
  .fail(function(err) {
    throw err;
  });

// Or in parallel using #parallel() as an alieas for Q's 'all'
db.parallel([
    Model.find(52).run(),
    Model.where({ type: 2 }).run()
]).done(function(res) {
    // do something...
}).fail(function(err) {...});

Raw Queries

### query(query, [values], callback)

Execute raw query to database.

db.query('SELECT 1 AS a', function(err, res) {
    console.log(res[0].a); //= 1
});

// Substitute with array of values
db.query('SELECT 1 AS a; SELECT %1 AS a;', ['hello'], function(err, res) {
    console.log(res[0].a); //= 1
    console.log(res[1].a); //= hello
});

// Substitute with key/values
db.query('SELECT :name AS a', { name: 'hello' }, function(err, res) {
    console.log(res[0].a); //= hello
})
### queue()

Add query to queue for later execution. Query can be a raw query string, a chained method object, or an array of either. Values can't be passed to objects or arrays (only raw strings);

queue.add(query, [values])
queue.print() || queue.get()
queue.run(callback)
var queue = db.queue();

queue.add('SELECT 1 AS a')
  .add('SELECT %1', [2])
  .add('SELECT :name AS a', { name: 'hello' })
  .run(function(err, res) {
    console.log(res[0].a); //= 1
    console.log(res[2].a); //= hello
});

queue.add(Model.find(1))
  .add(Model.select('name').limit(1))
  .run(function(err, res) {
    console.log(res[0]); // (row with ID of 1)
    console.log(res[1]); // (first row with only name column)
});

queue.add(['SELECT 1 AS a', 'SELECT 2 AS a']);
. . .
console.log(queue.print()); //= "SELECT 1 AS a; SELECT 2 AS a;"
queue.run(function(err, res) {
    console.log(res[0].a); //= 1
    console.log(res[1].a); //= 2
});
// OR as promise //
queue.run().then(function(res) {...})
  .fail(function(err) {...});
// Add custom mapping function for results
queue.add(...).map(function(row) {
    return row.id;
}).run();

## Models

To map query results to a model, define a schema for default values and validations. (To map results to a model without a schema, just define as an empty object schema: {}.)

var User = db.model('users', {
    schema: {
        first: String,
        last:  String,
        admin: { type: Boolean, default: false },
        created_at: Date,
        updated_at: Date
    }
});
### Validations
  • type: type of input
    • String
    • Number
    • Boolean
    • Date
    • Buffer
    • [value1, value2, value3, ...] list of options
    • [String] array of values (Postgres only)
  • default: default value if empty
  • allowNull: false requires a value (default is true)
  • length: the maximum length of a string
  • max: the maximum value of a number or length of a string
  • min: the minimum value of a number or length of a string
  • not: an array of incompatible values
  • match: a RegEx the string must match

Custom Messages (%n replaced with required value):

  • wrongType: message if type doesn't match
  • tooShort: message if string/number is too low
  • tooLong: message if string/number is too high
  • doesntMatch: message if RegEx doesn't match
  • isNull: message if value is empty
  • notInList: message if value isn't in list of options
  • inList: message if value is in list of incompatible values
### Creating & updating models

Creating a new model:

var tiger = Animal.new({ name: 'Tiger' });

// Run validations and insert into DB:
tiger.save(function(err) { ... });
// PROMISES //
tiger.save().then(function(err) { ... });

Updating a model:

Animal.where({ name: 'Tiger' }, function(err, animals) {
    animals[0].name = 'Siberian Tiger';
    // Run validations and update in DB:
    animals[0].save(function(err) { ... });
});
// PROMISES //
Animal.where({ name: 'Tiger' }).then(function(animals) {
    animals[0].name = 'Siberian Tiger';
    return animals[0].save().run();
}).fail(function(err) { ... });
### Expansion of models

Methods are functions that can be called on the model.

var User = db.model('users', {
    schema: {},
    methods: {
        add: function(n) {
            return this.number + n;
        }
    }
});
. . .
console.log(user.number); //= 5
console.log(user.add(5)); //= 10

Getters are methods that are called immediately and act as regular values for a model. They can supplement or replace previous values.

var User = db.model('users', {
    schema: {},
    getters: {
        first: function() { // No arguments
            return this.first.toUpperCase();
        },
        fullName: function() {
            return this.first + ' ' + this.last;
        }
    }
});
. . .
console.log(user.first);    //= PETER
console.log(user.last);     //= Parker
console.log(user.fullName); //= PETER Parker
### reload()

Reloads the model's original data.

User.find(1, function(err, user) {
    user.name = 'Mark';
    console.log(user.name); //= Mark
    user.reload();
    console.log(user.name); //= Adam (the original)
});

Other functions:

### setTable(table)

Changes the table name of the database/model.

db.setTable('products');
// or
Products.setTable('products').find(1);
### addGetter(name, fn) ### addMethod(name, fn)

Common Query Methods:

### all(callback)

Gets all table rows (SELECT * FROM table).

### find(ids, [callback])
  • ids int int[] — The ID, or an array of IDs, of the row(s) to return.
  • callback(err, rows) — Optional callback to run the query.
Animal.find(88, function(err, animals) {
    console.log(animals[0]); //= [{ id: 88, name: 'Tiger' }]
});
Animal.find([6, 18]);
### where(expression, [values], [callback])
  • expression string object — An expression string ("sales < 500 AND type = 'new'") or an object of property values to match ({ type: 'new' }).
  • values array object — Optional values to escape & substitute into expression string. An array of [0, 1, 2] replaces %1 %2 %3. An object of {a: 1, b: 2} replaces :a :b.
  • callback(err, rows) — Optional callback to run the query.
Person.where("age >= 21");
    //= SELECT * FROM people WHERE age >= 21;
Person.where({ gender: "female", hand: "left" });
    //= SELECT * FROM people WHERE gender = 'female' AND hand = 'left';
Person.where("name = %1 OR name = %2", ['Jill', 'Jane']);
    //= SELECT * FROM people WHERE name = 'Jill' OR name = 'Jane';
Person.where("age >= :age", { age: 21 });
    //= SELECT * FROM people WHERE age >= 21;
// Subqueries (Postgres only):
Person.where({ id: Client.select('person_id').order('sales').limit(1) });
    //= SELECT * FROM people WHERE id = (SELECT person_id FROM clients ORDER BY sales LIMIT 1);
### select(fields, [callback])
  • fields string string[] — An array or comma-separated string of the columns you want returned.
  • callback(err, rows) — Optional callback to run the query.
Book.select("author");
Book.select("author, publisher");
Book.select(["author", "publisher", "title"]);
### order(fields, [callback])
  • fields string string[] — An array or comma-separated string of the columns (and optionally ASC/DESC) you want ordered.
  • callback(err, rows) — Optional callback to run the query.
Animal.order('size');
Animal.order('size ASC, bones DESC');
Animal.order(['size', 'number']);
// Shortcuts
Animal.orderDesc('size');
    //= SELECT * FROM animals ORDER BY size DESC;
Animal.orderAsc('bones');
    //= SELECT * FROM animals ORDER BY bones ASC;
### limit(number, [callback])
  • number int — A number to limit the results by.
  • callback(err, rows) — Optional callback to run the query.
### offset(number, [callback])
  • number int — A number to offset the results by.
  • callback(err, rows) — Optional callback to run the query.
### insert(data, [callback]), create()
  • data object array query — An object of the data, with correctly named columns, to be inserted into the table. With Postgres & SQLite it also can be an array of objects or a subquery.
  • callback(err, rows) — Optional callback to run the query.

For Postgres, #insert() also returns the ID attribute.

Animal.insert({ name: 'Siberian Tiger', species: 'P. tigris altaica' });
    //= INSERT INTO animals (name,species) VALUES ('Siberian Tiger','P. tigris altaica') RETURNING id;
Animal.insert([
    { name: 'Puma', species: 'Puma concolor' },
    { name: 'Jackalope' }
]);
    //= INSERT INTO animals (name,species) VALUES ('Puma','Puma concolor'), ('Jackalope',NULL);
Person.create(Client.select('name').where({ type: 'new' }));
    //= INSERT INTO people (SELECT name FROM clients WHERE type = 'new');
### update([id], data, [callback])
  • id int int[] — The optional id(s) of the items to update (if omitted, a where() method is required).
  • data object — An object of the data, with correctly named columns, to be updated.
  • callback(err, rows) — Optional callback to run the query.
Book.update(55688, { title: 'The Great Gatsby' });
    //= UPDATE books SET (title) = ('The Great Gatsby') WHERE id IN (55688);
Book.update({ publisher: 'Brown Little' }).where({ publisher: 'Brown' });
    //= UPDATE books SET (publisher) = ('Brown Little') WHERE publisher = 'Brown';
### remove(id, [callback])
  • id int int[] — The optional id(s) of the items to update (if omitted, a where() method is required before remove is called).
  • callback(err, rows) — Optional callback to run the query.
Person.remove(345267);
Person.remove([5610, 5615]);
Person.where({ name: 'Mark' }).remove();
    //= DELETE FROM people WHERE name = 'Mark';

Postgres

### db.end()

Ends the Postgres pool connection. Connection will end automatically after 10 seconds if no queries are running. (Otherwise a new connection begins when a query is run.)

### Query: returning(fields, [callback])
  • fields string string[] — the name of the field to return, or an array of fields.

Adding the #returning() method to a query chain (either insert or update)

### Data type: Array

Values provided as an Array will be sent to the server as a Postgres Array data type (see more in the Postgres docs). So [1, 2, 3, 4] will be stored in Postgres as '{1, 2, 3, 4}'.

### Data type: hstore

Values provided as a JSON will be sent to the server as an hstore data type, a storage of key/values (see more in the Postgres docs). So { one: 1, two: 'three' } will be stored in Postgres as 'one => 1, two => "three"'.

### Data type: no escape (raw string)

Enclose the value in two nested arrays to avoid any value escaping. So [['\n']] will result in a String of '\n' and not '\\n' as usual.

Keywords

FAQs

Package last updated on 04 Jul 2014

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc