vidigami / backbone-sql

PostgreSQL, MySQL, and SQLite3 storage for BackboneORM
http://vidigami.github.io/backbone-orm/backbone-sql.html
MIT License
14 stars 8 forks source link

Bug with associations on empty tables #1

Open mateomurphy opened 11 years ago

mateomurphy commented 11 years ago

I've run into a bug, when there's an association on an empty table. My (simplified) models:

class Wall extends Backbone.Model
  schema:
    created_at: 'DateTime'
    name: 'String'
    messages: -> ['hasMany', require('./message')]

class Message extends Backbone.Model
  schema:
    created_at: 'DateTime'
    text: 'Text'
    wall: -> ['belongsTo', require('./wall')]
    user: -> ['belongsTo', require('./user')]

When the message table is empty, I get Error: HasMany.set: Unexpected type to set messages. Expecting array: null

This seems to happen because SqlCursor._joinedResultsToJSON takes

[ { walls_created_at: null,
    walls_name: 'test wall',
    walls_id: 1,
    messages_created_at: null,
    messages_text: null,
    messages_wall_id: null,
    messages_user_id: null,
    messages_id: null } ]

and converts it to

[ { created_at: null, name: 'test wall', id: 1, messages: null } ]

rather than

[ { created_at: null, name: 'test wall', id: 1, messages: [] } ]
gwilymhumphreys commented 11 years ago

Thanks mate! Change is merged, leaving this open to remind myself to add a test for that case & publish.