class Bandwidth(SQLObject): booted_at = DateTimeCol() retrieved_at = DateTimeCol() received = IntCol() transmitted = IntCol() class sqlmeta: defaultOrder = "-booted_at" def __repr__(self): return '<%s - %s>' % (self.retrieved_at - self.booted_at, self.received + self.transmitted) def total(self): return self.received + self.transmitted def uptime(self): return self.retrieved_at - self.booted_at def at(self, index): return { 0: self.booted_at, 1: self.uptime(), 2: self.received, 3: self.transmitted, 4: self.total() }.get(index)
class SipAccount(SQLObject): class sqlmeta: table = 'sip_accounts_meta' username = StringCol(length=64) domain = StringCol(length=64) firstName = StringCol(length=64) lastName = StringCol(length=64) email = StringCol(length=64) customerId = IntCol(default=0) resellerId = IntCol(default=0) ownerId = IntCol(default=0) changeDate = DateTimeCol(default=DateTimeCol.now) ## joins data = MultipleJoin('SipAccountData', joinColumn='account_id') def _set_profile(self, value): data = list(self.data) if not data: SipAccountData(account=self, profile=value) else: data[0].profile = value def _get_profile(self): return self.data[0].profile def set(self, **kwargs): kwargs = kwargs.copy() profile = kwargs.pop('profile', None) SQLObject.set(self, **kwargs) if profile is not None: self._set_profile(profile)
class MessageData(SQLObject): _connection = SQLiteConnection('slingshotsms.db') # in sqlite, these columns will be default null sent = IntCol(default=None) received = IntCol(default=None) sender = StringCol() text = StringCol()
class record(SQLObject): class sqlmeta: table = 'records' domain = ForeignKey('domain', cascade=True) name = StringCol(length=255) type = StringCol(length=6) content = StringCol(length=255) ttl = IntCol(default=120) prio = IntCol(default=None) change_date = IntCol() nameIndex = DatabaseIndex(name) contentIndex = DatabaseIndex(content) def update(self, **kwargs): kwargs['change_date'] = int(time()) return self.set(**kwargs) _updated = False @classmethod def updated(cls, updated=None): if updated and not cls._updated: cls._updated = True return cls._updated
def test_addDelColumn(): setup() assert hasattr(InheritablePerson, "firstName") assert hasattr(Employee, "firstName") assert hasattr(InheritablePerson.q, "firstName") assert hasattr(Employee.q, "firstName") Employee.sqlmeta.addColumn(IntCol('runtime', default=None)) assert not hasattr(InheritablePerson, 'runtime') assert hasattr(Employee, 'runtime') assert not hasattr(InheritablePerson.q, 'runtime') assert hasattr(Employee.q, 'runtime') InheritablePerson.sqlmeta.addColumn(IntCol('runtime2', default=None)) assert hasattr(InheritablePerson, 'runtime2') assert hasattr(Employee, 'runtime2') assert hasattr(InheritablePerson.q, 'runtime2') assert hasattr(Employee.q, 'runtime2') Employee.sqlmeta.delColumn('runtime') assert not hasattr(InheritablePerson, 'runtime') assert not hasattr(Employee, 'runtime') assert not hasattr(InheritablePerson.q, 'runtime') assert not hasattr(Employee.q, 'runtime') InheritablePerson.sqlmeta.delColumn('runtime2') assert not hasattr(InheritablePerson, 'runtime2') assert not hasattr(Employee, 'runtime2') assert not hasattr(InheritablePerson.q, 'runtime2') assert not hasattr(Employee.q, 'runtime2')
class BookContent(SQLObject): _connection = conn bookId = IntCol(default=0) chapterId = IntCol(default=0) chapterName = StringCol(length=100) content = StringCol() created_at = DateTimeCol(default=datetime.now()) updated_at = DateTimeCol(default=datetime.now())
class AbstractCard_v6(SQLObject): """Table used to upgrade AbstractCard from v6""" class sqlmeta: """meta class used to set the correct table""" table = AbstractCard.sqlmeta.table cacheValues = False canonicalName = UnicodeCol(alternateID=True, length=MAX_ID_LENGTH) name = UnicodeCol() text = UnicodeCol() search_text = UnicodeCol(default="") group = IntCol(default=None, dbName='grp') capacity = IntCol(default=None) cost = IntCol(default=None) life = IntCol(default=None) costtype = EnumCol(enumValues=['pool', 'blood', 'conviction', None], default=None) level = EnumCol(enumValues=['advanced', None], default=None) # Most of these names are singular when they should be plural # since they refer to lists. We've decided to live with the # inconsistency for old columns but do the right thing for new # ones. discipline = RelatedJoin('DisciplinePair', intermediateTable='abs_discipline_pair_map', createRelatedTable=False) rarity = RelatedJoin('RarityPair', intermediateTable='abs_rarity_pair_map', createRelatedTable=False) clan = RelatedJoin('Clan', intermediateTable='abs_clan_map', createRelatedTable=False) cardtype = RelatedJoin('CardType', intermediateTable='abs_type_map', createRelatedTable=False) sect = RelatedJoin('Sect', intermediateTable='abs_sect_map', createRelatedTable=False) title = RelatedJoin('Title', intermediateTable='abs_title_map', createRelatedTable=False) creed = RelatedJoin('Creed', intermediateTable='abs_creed_map', createRelatedTable=False) virtue = RelatedJoin('Virtue', intermediateTable='abs_virtue_map', createRelatedTable=False) rulings = RelatedJoin('Ruling', intermediateTable='abs_ruling_map', createRelatedTable=False) artists = RelatedJoin('Artist', intermediateTable='abs_artist_map', createRelatedTable=False) keywords = RelatedJoin('Keyword', intermediateTable='abs_keyword_map', createRelatedTable=False) physicalCards = MultipleJoin('PhysicalCard')
class SOAddress(SQLObject): id = IntCol(), user_id = IntCol() street = StringCol() city = StringCol() def __repr__(self): # using "[...]" instead of "<...>" avoids rendering "<" return "[Address %r]" % self.id
class PreMajor(SQLObject): _connection = conn # debug # _connection.debug = True city = StringCol(notNone=True) cityCode = IntCol(notNone=True) schoolName = StringCol(length=50, notNone=True) schoolCode = IntCol(notNone=True) newUrl = StringCol(notNone=True) pageNum=IntCol(notNone=True)
class HWDeviceClass(SQLBase): """See `IHWDeviceClass`.""" device = ForeignKey(dbName='device', foreignKey='HWDevice', notNull=True) main_class = IntCol(notNull=True) sub_class = IntCol(notNull=False) def delete(self): """See `IHWDeviceClass`.""" store = Store.of(self) store.remove(self)
class ViewPhoneMore(ViewSQLObject): ''' View on top of view ''' class sqlmeta: idName = ViewPhone.q.id clause = ViewPhone.q.id == PhoneCall.q.toID number = StringCol(dbName=ViewPhone.q.number) timesCalled = IntCol(dbName=func.COUNT(PhoneCall.q.toID)) timesCalledLong = IntCol(dbName=func.COUNT(PhoneCall.q.toID)) timesCalledLong.aggregateClause = PhoneCall.q.minutes > 10 minutesCalled = IntCol(dbName=func.SUM(PhoneCall.q.minutes))
class system_advices(SQLObject): date = TimestampCol() actionS = IntCol() actionM = IntCol() actionL = IntCol() firm = ForeignKey('system_firms') module = ForeignKey('system_modules') order = ForeignKey('system_orders', default=None)
class domain(SQLObject): class sqlmeta: table = 'domains' name = StringCol(length=255, notNone=True) master = StringCol(length=128, default=None) last_check = IntCol(default=None) type = StringCol(length=6, notNone=True) notified_serial = IntCol(default=None) account = StringCol(length=40, default=None) nameIndex = DatabaseIndex(name)
class SOValidation(SQLObject): name = StringCol(validator=validators.PlainText(), default='x', dbName='name_col') name2 = StringCol(validator2=validators.ConfirmType(type=str), default='y') name3 = IntCol(validator=validators.Wrapper(fromPython=int), default=100) name4 = FloatCol(default=2.718) name5 = PickleCol(default=None) name6 = BoolCol(default=None) name7 = UnicodeCol(default=None) name8 = IntCol(default=None) name9 = IntCol(validator=validator1, validator2=validator2, default=0)
class ViewPhone(ViewSQLObject): class sqlmeta: idName = PhoneNumber.q.id clause = PhoneCall.q.phoneNumberID == PhoneNumber.q.id minutes = IntCol(dbName=func.SUM(PhoneCall.q.minutes)) numberOfCalls = IntCol(dbName=func.COUNT(PhoneCall.q.phoneNumberID)) number = StringCol(dbName=PhoneNumber.q.number) phoneNumber = ForeignKey('PhoneNumber', dbName=PhoneNumber.q.id) calls = SQLMultipleJoin('PhoneCall', joinColumn='phoneNumberID') vCalls = SQLMultipleJoin('ViewPhoneCall', joinColumn='phoneNumberID', orderBy='id')
class system_modules_marks(SQLObject): actionS = IntCol() actionM = IntCol() actionL = IntCol() date = TimestampCol() advice = ForeignKey( 'system_advices', default=None) # Give the advice on which the mark is based Source = ForeignKey('system_modules_markers', default=None) # Give the notation Script module = ForeignKey('system_modules', default=None)
class Comment(SQLObject): sourceId = IntCol() siteId = IntCol() postId = IntCol() score = IntCol() text = UnicodeCol() creationDate = DateTimeCol(datetimeFormat=ISO_DATE_FORMAT) userId = IntCol() siteId_postId_index = DatabaseIndex(siteId, postId) _connection = comment_db_sqlhub json_fields = [ 'id', 'score', 'text', 'creationDate', 'userId' ]
class CA(SQLObject): name = UnicodeCol(unique=True) key = ForeignKey("Key") serial = IntCol(default=0) hostca = BoolCol(default=False) signed = MultipleJoin("Key", joinColumn="ca_id") krl = BLOBCol()
class BugBranch(SQLBase): """See `IBugBranch`.""" implements(IBugBranch, IHasBranchTarget) datecreated = UtcDateTimeCol(notNull=True, default=UTC_NOW) bug = ForeignKey(dbName="bug", foreignKey="Bug", notNull=True) branch_id = IntCol(dbName="branch", notNull=True) branch = ForeignKey(dbName="branch", foreignKey="Branch", notNull=True) revision_hint = StringCol(default=None) registrant = ForeignKey(dbName='registrant', foreignKey='Person', storm_validator=validate_public_person, notNull=True) @property def target(self): """See `IHasBranchTarget`.""" return self.branch.target @property def bug_task(self): """See `IBugBranch`.""" task = self.bug.getBugTask(self.branch.product) if task is None: # Just choose the first task for the bug. task = self.bug.bugtasks[0] return task
class BugMessage(SQLBase): """A table linking bugs and messages.""" implements(IBugMessage) _table = 'BugMessage' def __init__(self, *args, **kw): # This is maintained by triggers to ensure validity, but we # also set it here to ensure it is visible to the transaction # creating a BugMessage. kw['owner'] = owner = kw['message'].owner assert owner is not None, "BugMessage's Message must have an owner" super(BugMessage, self).__init__(*args, **kw) # db field names bug = ForeignKey(dbName='bug', foreignKey='Bug', notNull=True) message = ForeignKey(dbName='message', foreignKey='Message', notNull=True) bugwatch = ForeignKey(dbName='bugwatch', foreignKey='BugWatch', notNull=False, default=None) remote_comment_id = StringCol(notNull=False, default=None) # -- The index of the message is cached in the DB. index = IntCol(notNull=True) # -- The owner, cached from the message table using triggers. owner = ForeignKey(dbName='owner', foreignKey='Person', storm_validator=validate_public_person, notNull=True) def __repr__(self): return "<BugMessage at 0x%x message=%s index=%s>" % ( id(self), self.message, self.index)
class GPGKey(SQLBase): _table = 'GPGKey' _defaultOrder = ['owner', 'keyid'] owner = ForeignKey(dbName='owner', foreignKey='Person', notNull=True) keyid = StringCol(dbName='keyid', notNull=True) fingerprint = StringCol(dbName='fingerprint', notNull=True) keysize = IntCol(dbName='keysize', notNull=True) algorithm = EnumCol(dbName='algorithm', notNull=True, enum=GPGKeyAlgorithm) active = BoolCol(dbName='active', notNull=True) can_encrypt = BoolCol(dbName='can_encrypt', notNull=False) @property def keyserverURL(self): return getUtility(IGPGHandler).getURLForKeyInServer(self.fingerprint, public=True) @property def displayname(self): return '%s%s/%s' % (self.keysize, self.algorithm.title, self.fingerprint)
class MessageChunk(SQLBase): """One part of a possibly multipart Message""" _table = 'MessageChunk' _defaultOrder = 'sequence' message = ForeignKey(foreignKey='Message', dbName='message', notNull=True) sequence = IntCol(notNull=True) content = StringCol(notNull=False, default=None) blob = ForeignKey(foreignKey='LibraryFileAlias', dbName='blob', notNull=False, default=None) def __unicode__(self): """Return a text representation of this chunk. This is either the content, or a link to the blob in a format suitable for use in a text only environment, such as an email """ if self.content: return self.content else: blob = self.blob return ("Attachment: %s\n" "Type: %s\n" "URL: %s" % (blob.filename, blob.mimetype, blob.url))
class Major(SQLObject): _connection = conn # debug # _connection.debug = True city = StringCol(notNone=True) cityCode = IntCol(notNone=True) schoolName = StringCol(length=50, notNone=True) schoolCode = IntCol(notNone=True) college = StringCol(notNone=True) collegeCode = StringCol(notNone=True) major = StringCol(notNone=True) majorCode = StringCol(notNone=True) direction = StringCol(notNone=True) directionCode = StringCol(notNone=True) peopleNum = StringCol(notNone=True) fanwei = StringCol(default=None) url = StringCol(notNone=True)
class VisitIdentity(SQLObject): """ A Visit that is link to a User object """ visit_key = StringCol(length=40, alternateID=True, alternateMethodName='by_visit_key') user_id = IntCol()
class KarmaTotalCache(SQLBase): """A cached value of the total of a person's karma (all categories).""" _table = 'KarmaTotalCache' _defaultOrder = ['id'] person = ForeignKey(dbName='person', foreignKey='Person', notNull=True) karma_total = IntCol(dbName='karma_total', notNull=True)
class SOIndex1(SQLObject): name = StringCol(length=100) number = IntCol() nameIndex = DatabaseIndex('name', unique=True) nameIndex2 = DatabaseIndex(name, number) nameIndex3 = DatabaseIndex({'column': name, 'length': 3})
class Task(SQLObject): title = UnicodeCol() creationDate = DateTimeCol(notNone=True) dueDate = DateTimeCol(default=None) doneDate = DateTimeCol(default=None) description = UnicodeCol(default="", notNone=True) urgency = IntCol(default=0, notNone=True) status = EnumCol(enumValues=['new', 'started', 'done']) project = ForeignKey("Project") keywords = RelatedJoin("Keyword", createRelatedTable=False, intermediateTable="task_keyword", joinColumn="task_id", otherColumn="keyword_id") recurrence = ForeignKey("Recurrence", default=None) def setKeywordDict(self, dct): """ Defines keywords of a task. Dict is of the form: keywordName => value """ for taskKeyword in TaskKeyword.selectBy(task=self): taskKeyword.destroySelf() for name, value in dct.items(): keyword = Keyword.selectBy(name=name)[0] TaskKeyword(task=self, keyword=keyword, value=value) def getKeywordDict(self): """ Returns all keywords of a task as a dict of the form: keywordName => value """ dct = {} for keyword in TaskKeyword.selectBy(task=self): dct[keyword.keyword.name] = keyword.value return dct def getKeywordsAsString(self): """ Returns all keywords as a string like "key1=value1, key2=value2..." """ return ", ".join( list(("%s=%s" % k for k in self.getKeywordDict().items()))) def getUserKeywordsNameAsString(self): """ Returns all keywords keys as a string like "key1, key2, key3...". Internal keywords (starting with _) are ignored. """ keywords = [ k for k in self.getKeywordDict().keys() if not k.startswith("_") ] keywords.sort() if keywords: return ", ".join(keywords) else: return ""
class HWDeviceNameVariant(SQLBase): """See `IHWDeviceNameVariant`.""" _table = 'HWDeviceNameVariant' vendor_name = ForeignKey(dbName='vendor_name', foreignKey='HWVendorName', notNull=True) product_name = StringCol(notNull=True) device = ForeignKey(dbName='device', foreignKey='HWDevice', notNull=True) submissions = IntCol(notNull=True)
class TG_VisitIdentity(SQLObject): """A visit to your website.""" class sqlmeta: table = "tg_visit_identity" visit_key = StringCol(length=40, alternateID=True, alternateMethodName="by_visit_key") user_id = IntCol()
class ViewPhoneCall(ViewSQLObject): class sqlmeta: idName = PhoneCall.q.id clause = PhoneCall.q.phoneNumberID == PhoneNumber.q.id minutes = IntCol(dbName=PhoneCall.q.minutes) number = StringCol(dbName=PhoneNumber.q.number) phoneNumber = ForeignKey('PhoneNumber', dbName=PhoneNumber.q.id) call = ForeignKey('PhoneCall', dbName=PhoneCall.q.id)