# Path: dbsync/utils.py
# def get_pk(sa_variant):
#     "Returns the primary key name for the given mapped class or object."
#     mapper = class_mapper(sa_variant) if inspect.isclass(sa_variant) \
#         else object_mapper(sa_variant)
#     return mapper.primary_key[0].key
# 
# def properties_dict(sa_object):
#     """
#     Returns a dictionary of column-properties for the given SQLAlchemy
#     mapped object.
#     """
#     mapper = object_mapper(sa_object)
#     return dict((prop.key, getattr(sa_object, prop.key))
#                 for prop in mapper.iterate_properties
#                 if isinstance(prop, ColumnProperty))
# 
# def construct_bare(class_):
#     """
#     Returns an object of type *class_*, without invoking the class'
#     constructor.
#     """
#     obj = class_.__new__(class_)
#     manager = getattr(class_, instrumentation.ClassManager.MANAGER_ATTR)
#     setattr(obj, manager.STATE_ATTR, state.InstanceState(obj, manager))
#     return obj
# 
# Path: dbsync/core.py
# MAX_SQL_VARIABLES = 900
# INTERNAL_SESSION_ATTR = '_dbsync_internal'
# def Session():
# def session_closing(fn):
#     def wrapped(*args, **kwargs):
# def session_committing(fn):
#     def wrapped(*args, **kwargs):
# def committing_context():
# def set_engine(engine):
# def get_engine():
#     def __setattr__(self, *args):
#     def __init__(self, model=None, id=None):
# def install(self, model):
# def tracked_model(operation):
# def extend(model, fieldname, fieldtype, loadfn, savefn, deletefn=None):
# def _has_extensions(obj):
# def _has_delete_functions(obj):
# def save_extensions(obj):
# def delete_extensions(old_obj, new_obj):
# def toggle_listening(enabled=None):
# def with_listening(enabled):
#     def wrapper(proc):
#         def wrapped(*args, **kwargs):
# def _track_added(fn, added):
#     def tracked(o, **kws):
# def _track_deleted(fn, deleted, session, always=False):
#     def tracked(o, **kws):
# def with_transaction(include_extensions=True):
#     def wrapper(proc):
#         def wrapped(*args, **kwargs):
# def make_content_type_id(model):
# def generate_content_types(session=None):
# def is_synched(obj, session=None):
# def get_latest_version_id(session=None):
# class ConfigurationError(Exception): pass
# class tracked_record(object):
# 
# Path: dbsync/models.py
# class PrefixTables(DeclarativeMeta):
# class ContentType(Base):
# class Node(Base):
# class Version(Base):
# class OperationError(Exception): pass
# class Operation(Base):
#     def __init__(cls, classname, bases, dict_):
#     def __repr__(self):
#     def __init__(self, *args, **kwargs):
#     def __repr__(self):
#     def __repr__(self):
#     def validate_command(self, key, command):
#     def __repr__(self):
#     def references(self, obj):
#     def perform(operation, container, session, node_id=None):
# 
# Path: dbsync/messages/codecs.py
# def decode_dict(class_):
#     """
#     Returns a function that transforms a dictionary, mapping the
#     types to richer ones, according to the given mapped class.
#     """
#     types = types_dict(class_)
#     decodings = dict((k, decode(t)) for k, t in types.iteritems())
#     return lambda dict_: dict((k, decodings[k](v))
#                               for k, v in dict_.iteritems()
#                               if k in decodings)
# 
# def encode_dict(class_):
#     """
#     Returns a function that transforms a dictionary, mapping the
#     types to simpler ones, according to the given mapped class.
#     """
#     types = types_dict(class_)
#     encodings = dict((k, encode(t)) for k, t in types.iteritems())
#     return lambda dict_: dict((k, encodings[k](v))
#                               for k, v in dict_.iteritems()
#                               if k in encodings)


import inspect
from dbsync.lang import *
from dbsync.utils import get_pk, properties_dict, construct_bare
from dbsync.core import null_model, synched_models, model_extensions
from dbsync import models
from dbsync.messages.codecs import decode_dict, encode_dict

class BaseMessage(object):
    "The base type for messages with a payload."

    #: dictionary of (model name, set of wrapped objects)
    payload = None

    def __init__(self, raw_data=None):
        self.payload = {}
        if raw_data is not None:
            self._from_raw(raw_data)

    def _from_raw(self, data):
        getm = lambda k: synched_models.model_names.get(k, null_model).model
        for k, v, m in ifilter(lambda (k, v, m): m is not None,
                               imap(lambda (k, v): (k, v, getm(k)),
                                    data['payload'].iteritems())):
            self.payload[k] = set(
                map(lambda dict_: ObjectType(k, dict_[get_pk(m)], **dict_),
                    imap(decode_dict(m), v)))

    def query(self, model):
        "Returns a query object for this message."
        return MessageQuery(model, self.payload)

    def to_json(self):
        "Returns a JSON-friendly python dictionary."
        encoded = {}
        encoded['payload'] = {}
        for k, objects in self.payload.iteritems():

# Path: dbsync/utils.py
# def get_pk(sa_variant):
#     "Returns the primary key name for the given mapped class or object."
#     mapper = class_mapper(sa_variant) if inspect.isclass(sa_variant) \
#         else object_mapper(sa_variant)
#     return mapper.primary_key[0].key
# 
# def properties_dict(sa_object):
#     """
#     Returns a dictionary of column-properties for the given SQLAlchemy
#     mapped object.
#     """
#     mapper = object_mapper(sa_object)
#     return dict((prop.key, getattr(sa_object, prop.key))
#                 for prop in mapper.iterate_properties
#                 if isinstance(prop, ColumnProperty))
# 
# def construct_bare(class_):
#     """
#     Returns an object of type *class_*, without invoking the class'
#     constructor.
#     """
#     obj = class_.__new__(class_)
#     manager = getattr(class_, instrumentation.ClassManager.MANAGER_ATTR)
#     setattr(obj, manager.STATE_ATTR, state.InstanceState(obj, manager))
#     return obj
# 
# Path: dbsync/core.py
# MAX_SQL_VARIABLES = 900
# INTERNAL_SESSION_ATTR = '_dbsync_internal'
# def Session():
# def session_closing(fn):
#     def wrapped(*args, **kwargs):
# def session_committing(fn):
#     def wrapped(*args, **kwargs):
# def committing_context():
# def set_engine(engine):
# def get_engine():
#     def __setattr__(self, *args):
#     def __init__(self, model=None, id=None):
# def install(self, model):
# def tracked_model(operation):
# def extend(model, fieldname, fieldtype, loadfn, savefn, deletefn=None):
# def _has_extensions(obj):
# def _has_delete_functions(obj):
# def save_extensions(obj):
# def delete_extensions(old_obj, new_obj):
# def toggle_listening(enabled=None):
# def with_listening(enabled):
#     def wrapper(proc):
#         def wrapped(*args, **kwargs):
# def _track_added(fn, added):
#     def tracked(o, **kws):
# def _track_deleted(fn, deleted, session, always=False):
#     def tracked(o, **kws):
# def with_transaction(include_extensions=True):
#     def wrapper(proc):
#         def wrapped(*args, **kwargs):
# def make_content_type_id(model):
# def generate_content_types(session=None):
# def is_synched(obj, session=None):
# def get_latest_version_id(session=None):
# class ConfigurationError(Exception): pass
# class tracked_record(object):
# 
# Path: dbsync/models.py
# class PrefixTables(DeclarativeMeta):
# class ContentType(Base):
# class Node(Base):
# class Version(Base):
# class OperationError(Exception): pass
# class Operation(Base):
#     def __init__(cls, classname, bases, dict_):
#     def __repr__(self):
#     def __init__(self, *args, **kwargs):
#     def __repr__(self):
#     def __repr__(self):
#     def validate_command(self, key, command):
#     def __repr__(self):
#     def references(self, obj):
#     def perform(operation, container, session, node_id=None):
# 
# Path: dbsync/messages/codecs.py
# def decode_dict(class_):
#     """
#     Returns a function that transforms a dictionary, mapping the
#     types to richer ones, according to the given mapped class.
#     """
#     types = types_dict(class_)
#     decodings = dict((k, decode(t)) for k, t in types.iteritems())
#     return lambda dict_: dict((k, decodings[k](v))
#                               for k, v in dict_.iteritems()
#                               if k in decodings)
# 
# def encode_dict(class_):
#     """
#     Returns a function that transforms a dictionary, mapping the
#     types to simpler ones, according to the given mapped class.
#     """
#     types = types_dict(class_)
#     encodings = dict((k, encode(t)) for k, t in types.iteritems())
#     return lambda dict_: dict((k, encodings[k](v))
#                               for k, v in dict_.iteritems()
#                               if k in encodings)


# Path: dbsync/messages/base.py
import inspect
from dbsync.lang import *
from dbsync.utils import get_pk, properties_dict, construct_bare
from dbsync.core import null_model, synched_models, model_extensions
from dbsync import models
from dbsync.messages.codecs import decode_dict, encode_dict


class BaseMessage(object):
    "The base type for messages with a payload."

    #: dictionary of (model name, set of wrapped objects)
    payload = None

    def __init__(self, raw_data=None):
        self.payload = {}
        if raw_data is not None:
            self._from_raw(raw_data)

    def _from_raw(self, data):
        getm = lambda k: synched_models.model_names.get(k, null_model).model
        for k, v, m in ifilter(lambda (k, v, m): m is not None,
                               imap(lambda (k, v): (k, v, getm(k)),
                                    data['payload'].iteritems())):
            self.payload[k] = set(
                map(lambda dict_: ObjectType(k, dict_[get_pk(m)], **dict_),
                    imap(decode_dict(m), v)))

    def query(self, model):
        "Returns a query object for this message."
        return MessageQuery(model, self.payload)

    def to_json(self):
        "Returns a JSON-friendly python dictionary."
        encoded = {}
        encoded['payload'] = {}
        for k, objects in self.payload.iteritems():

            model = synched_models.model_names.get(k, null_model).model