| 1 | from sqlalchemy import Column |
|---|
| 2 | from supermodel.statements import Statement |
|---|
| 3 | |
|---|
| 4 | |
|---|
| 5 | class Field(object): |
|---|
| 6 | def __init__(self, type, *args, **kwargs): |
|---|
| 7 | self.colname = kwargs.pop('colname', None) |
|---|
| 8 | self.type = type |
|---|
| 9 | self.primary_key = kwargs.get('primary_key', False) |
|---|
| 10 | |
|---|
| 11 | self.args = args |
|---|
| 12 | self.kwargs = kwargs |
|---|
| 13 | |
|---|
| 14 | @property |
|---|
| 15 | def column(self): |
|---|
| 16 | """Returns the corresponding sqlalchemy-column""" |
|---|
| 17 | |
|---|
| 18 | if hasattr(self, '_column'): |
|---|
| 19 | return self._column |
|---|
| 20 | |
|---|
| 21 | self._column = Column(self.colname, self.type, |
|---|
| 22 | *self.args, **self.kwargs) |
|---|
| 23 | return self._column |
|---|
| 24 | |
|---|
| 25 | |
|---|
| 26 | class HasField(object): |
|---|
| 27 | """ |
|---|
| 28 | Specifies one field of an entity |
|---|
| 29 | """ |
|---|
| 30 | |
|---|
| 31 | def __init__(self, entity, name, *args, **kwargs): |
|---|
| 32 | field = Field(*args, **kwargs) |
|---|
| 33 | field.colname = name |
|---|
| 34 | entity._descriptor.add_field(field) |
|---|
| 35 | |
|---|
| 36 | has_field = Statement(HasField) |
|---|
| 37 | |
|---|
| 38 | |
|---|
| 39 | class WithFields(object): |
|---|
| 40 | |
|---|
| 41 | """ |
|---|
| 42 | Specifies all fields of an entity at once |
|---|
| 43 | """ |
|---|
| 44 | |
|---|
| 45 | def __init__(self, entity, *args, **fields): |
|---|
| 46 | columns = list() |
|---|
| 47 | desc = entity._descriptor |
|---|
| 48 | |
|---|
| 49 | for colname, field in fields.iteritems(): |
|---|
| 50 | if not field.colname: |
|---|
| 51 | field.colname = colname |
|---|
| 52 | desc.add_field(field) |
|---|
| 53 | |
|---|
| 54 | with_fields = Statement(WithFields) |
|---|