示例#1
0
from sqlalchemy import MetaData
from sqlalchemy import Column, MetaData, Table, types
from datetime import datetime


class Message(object):
    pass


metadata = sqlalchemy.MetaData()

message = Table("message",
                metadata,
                Column('id', types.BigInteger(20), primary_key=True),
                Column('parent_id', types.BigInteger(20)),
                Column('incident_id', types.Integer(11)),
                Column('user_id', types.Integer(11)),
                Column('reporter_id', types.BigInteger(20)),
                Column('service_messageid', types.Unicode(100)),
                Column('message_from', types.Unicode(100)),
                Column('message_to', types.Unicode(100)),
                Column('message', types.Unicode),
                Column('message_detail', types.Unicode),
                Column('message_type', types.SmallInteger(4)),
                Column('message_date', types.DateTime),
                Column('message_level', types.SmallInteger(4)),
                Column('type', types.Integer(4)),
                mysql_engine='InnoDB',
                mysql_charset='utf8')

示例#2
0
class MultiplePrimaryKey(Model):
    _id1 = Column(types.Integer(), primary_key=True)
    _id2 = Column(types.Integer(), primary_key=True)
    _id3 = Column(types.Integer(), primary_key=True)
示例#3
0
class C(Model):
    _id = Column(types.Integer(), primary_key=True)
示例#4
0
class Doz(Model):
    qux_id = Column(types.Integer(), ForeignKey('qux._id'), primary_key=True)
    name = Column(types.String())
示例#5
0
class AutoGenTableName(Model):
    _id = Column(types.Integer(), primary_key=True)
    name = Column(types.String())
示例#6
0
from sqlalchemy import schema, types

metadata = schema.MetaData()

projects = schema.Table(
    'projects',
    metadata,
    schema.Column('id', types.Integer, primary_key=True, unique=True),
    schema.Column('num', types.Integer(), default=0),
    schema.Column('loc', types.Text(), default=u''),
    schema.Column('geo', types.Text(), default=u''),
)

updates = schema.Table(
    'updates',
    metadata,
    schema.Column('id', types.Integer),
    schema.Column('date', types.Integer(), default=0),
    schema.Column('type', types.Text(), default=u''),
)

from sqlalchemy.engine import create_engine

db = create_engine('sqlite:///25th_ward.db', echo=False)
metadata.bind = db

metadata.create_all(checkfirst=True)
示例#7
0
def init_schema(url):
    """
    Setup the songs database connection and initialise the database schema.

    :param url: The database to setup

    The song database contains the following tables:

        * authors
        * authors_songs
        * media_files
        * media_files_songs
        * song_books
        * songs
        * songs_songbooks
        * songs_topics
        * topics

    **authors** Table
        This table holds the names of all the authors. It has the following
        columns:

        * id
        * first_name
        * last_name
        * display_name

    **authors_songs Table**
        This is a bridging table between the *authors* and *songs* tables, which
        serves to create a many-to-many relationship between the two tables. It
        has the following columns:

        * author_id
        * song_id
        * author_type

    **media_files Table**
        * id
        * file_name
        * type

    **song_books Table**
        The *song_books* table holds a list of books that a congregation gets
        their songs from, or old hymnals now no longer used. This table has the
        following columns:

        * id
        * name
        * publisher

    **songs Table**
        This table contains the songs, and each song has a list of attributes.
        The *songs* table has the following columns:

        * id
        * title
        * alternate_title
        * lyrics
        * verse_order
        * copyright
        * comments
        * ccli_number
        * theme_name
        * search_title
        * search_lyrics

    **songs_songsbooks Table**
        This is a mapping table between the *songs* and the *song_books* tables. It has the following columns:

        * songbook_id
        * song_id
        * entry  # The song number, like 120 or 550A

    **songs_topics Table**
        This is a bridging table between the *songs* and *topics* tables, which
        serves to create a many-to-many relationship between the two tables. It
        has the following columns:

        * song_id
        * topic_id

    **topics Table**
        The topics table holds a selection of topics that songs can cover. This
        is useful when a worship leader wants to select songs with a certain
        theme. This table has the following columns:

        * id
        * name
    """
    session, metadata = init_db(url)

    # Definition of the "authors" table
    authors_table = Table(
        'authors', metadata, Column('id', types.Integer(), primary_key=True),
        Column('first_name', types.Unicode(128)),
        Column('last_name', types.Unicode(128)),
        Column('display_name', types.Unicode(255), index=True, nullable=False))

    # Definition of the "media_files" table
    media_files_table = Table(
        'media_files', metadata, Column('id',
                                        types.Integer(),
                                        primary_key=True),
        Column('song_id',
               types.Integer(),
               ForeignKey('songs.id'),
               default=None),
        Column('file_name', types.Unicode(255), nullable=False),
        Column('type', types.Unicode(64), nullable=False, default='audio'),
        Column('weight', types.Integer(), default=0))

    # Definition of the "song_books" table
    song_books_table = Table(
        'song_books', metadata, Column('id', types.Integer(),
                                       primary_key=True),
        Column('name', types.Unicode(128), nullable=False),
        Column('publisher', types.Unicode(128)))

    # Definition of the "songs" table
    songs_table = Table(
        'songs', metadata, Column('id', types.Integer(), primary_key=True),
        Column('title', types.Unicode(255), nullable=False),
        Column('alternate_title', types.Unicode(255)),
        Column('lyrics', types.UnicodeText, nullable=False),
        Column('verse_order', types.Unicode(128)),
        Column('copyright', types.Unicode(255)),
        Column('comments', types.UnicodeText),
        Column('ccli_number', types.Unicode(64)),
        Column('theme_name', types.Unicode(128)),
        Column('search_title', types.Unicode(255), index=True, nullable=False),
        Column('search_lyrics', types.UnicodeText, nullable=False),
        Column('create_date', types.DateTime(), default=func.now()),
        Column('last_modified',
               types.DateTime(),
               default=func.now(),
               onupdate=func.now()),
        Column('temporary', types.Boolean(), default=False))

    # Definition of the "topics" table
    topics_table = Table(
        'topics', metadata, Column('id', types.Integer(), primary_key=True),
        Column('name', types.Unicode(128), index=True, nullable=False))

    # Definition of the "authors_songs" table
    authors_songs_table = Table(
        'authors_songs', metadata,
        Column('author_id',
               types.Integer(),
               ForeignKey('authors.id'),
               primary_key=True),
        Column('song_id',
               types.Integer(),
               ForeignKey('songs.id'),
               primary_key=True),
        Column('author_type',
               types.Unicode(255),
               primary_key=True,
               nullable=False,
               server_default=text('""')))

    # Definition of the "songs_songbooks" table
    songs_songbooks_table = Table(
        'songs_songbooks', metadata,
        Column('songbook_id',
               types.Integer(),
               ForeignKey('song_books.id'),
               primary_key=True),
        Column('song_id',
               types.Integer(),
               ForeignKey('songs.id'),
               primary_key=True),
        Column('entry', types.Unicode(255), primary_key=True, nullable=False))

    # Definition of the "songs_topics" table
    songs_topics_table = Table(
        'songs_topics', metadata,
        Column('song_id',
               types.Integer(),
               ForeignKey('songs.id'),
               primary_key=True),
        Column('topic_id',
               types.Integer(),
               ForeignKey('topics.id'),
               primary_key=True))

    mapper(Author,
           authors_table,
           properties={
               'songs':
               relation(Song, secondary=authors_songs_table, viewonly=True)
           })
    mapper(AuthorSong,
           authors_songs_table,
           properties={'author': relation(Author)})
    mapper(SongBookEntry,
           songs_songbooks_table,
           properties={'songbook': relation(Book)})
    mapper(Book, song_books_table)
    mapper(MediaFile, media_files_table)
    mapper(
        Song,
        songs_table,
        properties={
            # Use the authors_songs relation when you need access to the 'author_type' attribute
            # or when creating new relations
            'authors_songs':
            relation(AuthorSong, cascade="all, delete-orphan"),
            # Use lazy='joined' to always load authors when the song is fetched from the database (bug 1366198)
            'authors':
            relation(Author,
                     secondary=authors_songs_table,
                     viewonly=True,
                     lazy='joined'),
            'media_files':
            relation(MediaFile,
                     backref='songs',
                     order_by=media_files_table.c.weight),
            'songbook_entries':
            relation(SongBookEntry,
                     backref='song',
                     cascade='all, delete-orphan'),
            'topics':
            relation(Topic, backref='songs', secondary=songs_topics_table)
        })
    mapper(Topic, topics_table)

    metadata.create_all(checkfirst=True)
    return session
示例#8
0
class SearchMany(Model):
    _id = Column(types.Integer(), primary_key=True)
    string = Column(types.String())
    search_id = Column(types.Integer(), ForeignKey('search._id'))
class RouterTestModel(Base):
    __tablename__ = "routertest"
    id = Column(types.Integer(), default=3, primary_key=True)
    text = Column(types.String(length=200))
示例#10
0
class Owner(Base):
    __tablename__ = "owners"

    id = Column(types.Integer(), primary_key=True)
    first_name = Column(types.Unicode(length=50))
    last_name = Column(types.Unicode(length=50))
示例#11
0
    [1, 2, 3],
]

ONE_ROW_CONTENTS_DML = [
    588,
    datetime.datetime(2013, 10, 10, 11, 27, 16, tzinfo=timezone('UTC')),
    'test', 40.76727216, False,
    datetime.date(2013, 10, 10),
    datetime.datetime(2013, 10, 10, 11, 27, 16),
    datetime.time(11, 27, 16), 'test_bytes'
]

SAMPLE_COLUMNS = [
    {
        'name': 'integer',
        'type': types.Integer(),
        'nullable': True,
        'default': None
    },
    {
        'name': 'timestamp',
        'type': types.TIMESTAMP(),
        'nullable': True,
        'default': None
    },
    {
        'name': 'string',
        'type': types.String(),
        'nullable': True,
        'default': None
    },
示例#12
0
class ModelWithJson(Base):
    __tablename__ = "model_with_json"

    id = Column(types.Integer(), Sequence("seq_id"), primary_key=True)
示例#13
0
class Invoice(meta.BaseObject):
    """An invoice."""

    __tablename__ = "invoice"

    id = schema.Column(types.Integer(),
                       schema.Sequence("invoice_id_seq", optional=True),
                       primary_key=True,
                       autoincrement=True)
    _number = schema.Column("number", types.Integer())
    customer_id = schema.Column(types.Integer(),
                                schema.ForeignKey(Customer.id,
                                                  onupdate="CASCADE",
                                                  ondelete="CASCADE"),
                                nullable=False)
    customer = orm.relationship(Customer, backref="invoices")
    sent = schema.Column(types.Date())
    payment_term = schema.Column(types.Integer(), nullable=False, default=30)
    paid = schema.Column(types.Date())
    note = schema.Column(types.UnicodeText())

    @orm.reconstructor
    def _add_acls(self):
        account_id = self.customer.account_id
        self.__acl__ = [(security.Allow, account_id, ("comment", "view"))]
        if not self.sent:
            self.__acl__.append(
                (security.Allow, account_id, ("delete", "edit")))
            if len(self.entries):
                self.__acl__.append((security.Allow, account_id, "send"))
        if self.sent and not self.paid:
            self.__acl__.append((security.Allow, account_id, "mark-paid"))

    @property
    def due(self):
        if self.sent:
            return self.sent + datetime.timedelta(days=self.payment_term)
        return None

    def total(self, type="gross"):
        assert type in ["gross", "net", "vat"]
        gross = sum([entry.total for entry in self.entries])
        if type == "gross":
            return gross

        vat = sum([v[1] for v in self.VAT()])
        if type == "vat":
            return vat
        return gross + vat

    def VAT(self):
        totals = {}
        for entry in self.entries:
            if not entry.vat:
                continue
            current = entry.total
            totals[entry.vat] = totals.get(entry.vat, 0) + current
        for (vat, total) in totals.items():
            totals[vat] = (totals[vat] * vat) / 100
        return sorted(totals.items())

    @synonym_for("_number")
    @property
    def number(self):
        if not self._number:
            return None
        return "%s.%04d" % (self.customer.invoice_code, self._number)

    def state(self):
        if not self.sent:
            return "unsend"
        elif self.paid:
            return "paid"
        today = datetime.date.today()
        due = self.sent + datetime.timedelta(days=self.payment_term)
        if due < today:
            return "overdue"
        else:
            return "pending"

    def overdue(self):
        if self.paid or not self.sent:
            return None
        today = datetime.date.today()
        due = self.sent + datetime.timedelta(days=self.payment_term)
        if due >= today:
            return None
        return (today - due).days

    def send(self):
        assert self.sent is None
        self.sent = datetime.datetime.now()
        self._number = self.customer.account.newInvoiceNumber()
示例#14
0
from sqlalchemy import orm
import datetime
from sqlalchemy import schema, types

metadata = schema.MetaData()


def now():
    return datetime.datetime.now()


page_table = schema.Table(
    'page',
    metadata,
    schema.Column('id',
                  types.Integer(),
                  schema.Sequence('page_seq_id', optional=True),
                  primary_key=True),
    schema.Column('content', types.Text(), nullable=False),
    schema.Column('posted', types.DateTime(), default=now),
    schema.Column('title', types.Unicode(255), default=u'Unititled Page'),
    schema.Column('heading', types.Unicode(255)),
)

comment_table = schema.Table(
    'comment',
    metadata,
    schema.Column('id',
                  types.Integer(),
                  schema.Sequence('page_seq_id', optional=True),
                  primary_key=True),
示例#15
0
文件: models.py 项目: tekd/noi2
class User(db.Model, UserMixin, DeploymentMixin):  #pylint: disable=no-init,too-few-public-methods
    '''
    User
    '''
    __tablename__ = 'users'

    id = Column(types.Integer, autoincrement=True, primary_key=True)  #pylint: disable=invalid-name

    picture_id = Column(
        types.String,
        default=lambda: base64.urlsafe_b64encode(os.urandom(20))[0:-2])

    has_picture = Column(types.Boolean, default=False)

    first_name = Column(types.String,
                        info={
                            'label': lazy_gettext('First Name'),
                        })
    last_name = Column(types.String,
                       info={
                           'label': lazy_gettext('Last Name'),
                       })

    email = Column(EmailType,
                   nullable=False,
                   info={
                       'label': lazy_gettext('Email'),
                   })

    password = Column(types.String,
                      nullable=False,
                      info={
                          'label': lazy_gettext('Password'),
                      })
    active = Column(types.Boolean, nullable=False)

    last_login_at = Column(types.DateTime())
    current_login_at = Column(types.DateTime())
    confirmed_at = Column(types.DateTime())
    last_login_ip = Column(types.Text)
    current_login_ip = Column(types.Text)
    login_count = Column(types.Integer)

    position = Column(types.String, info={
        'label': lazy_gettext('Position'),
    })
    organization = Column(types.String,
                          info={
                              'label': lazy_gettext('Organization'),
                          })
    organization_type = Column(
        types.String,
        info={
            'label': lazy_gettext('Type of Organization'),
            'description':
            lazy_gettext('The type of organization you work for'),
            'choices': [(k, v) for k, v in ORG_TYPES.iteritems()]
        })
    country = Column(CountryType, info={
        'label': lazy_gettext('Country'),
    })

    city = Column(types.String, info={'label': lazy_gettext('City')})

    latlng = Column(types.String,
                    info={
                        'label': lazy_gettext('Location'),
                        'description': lazy_gettext('Enter your location')
                    })

    projects = Column(
        types.Text,
        info={
            'label':
            lazy_gettext('Projects'),
            'description':
            lazy_gettext(
                'Add name and url or short description of any current work projects.'
            )
        })

    tutorial_step = Column(types.Integer())

    created_at = Column(types.DateTime(), default=datetime.datetime.now)
    updated_at = Column(types.DateTime(),
                        default=datetime.datetime.now,
                        onupdate=datetime.datetime.now)

    def is_admin(self):
        return self.email in current_app.config.get('ADMIN_UI_USERS', [])

    @property
    def full_name(self):
        return u"%s %s" % (self.first_name, self.last_name)

    @property
    def full_location(self):
        loc = []
        if self.city:
            loc.append(self.city)
        if self.country and self.country.code != 'ZZ':
            loc.append(self.country.name)
        return ", ".join(loc)

    @property
    def display_in_search(self):
        '''
        Determine whether user has filled out bare minimum to display in search
        results.

        Specifically, we want to make sure that the first and last name
        are both non-NULL and non-blank.
        '''
        return bool(self.first_name and self.last_name)

    @property
    def picture_path(self):
        '''
        Path where picture would be found (hosted on S3).
        '''
        return "{}/static/pictures/{}/{}".format(
            current_app.config['NOI_DEPLOY'], self.id, self.picture_id)

    @property
    def picture_url(self):
        '''
        Full path to picture.
        '''
        return 'https://s3.amazonaws.com/{bucket}/{path}'.format(
            bucket=current_app.config['S3_BUCKET_NAME'],
            path=self.picture_path)

    def remove_picture(self):
        conn = S3Connection(current_app.config['S3_ACCESS_KEY_ID'],
                            current_app.config['S3_SECRET_ACCESS_KEY'])
        bucket = conn.get_bucket(current_app.config['S3_BUCKET_NAME'])

        if bucket.get_key(self.picture_path):
            bucket.delete_key(self.picture_path)

        self.has_picture = False

    def upload_picture(self, fileobj, mimetype):
        '''
        Upload the given file object with the given mime type to S3 and
        mark the user as having a picture.
        '''

        conn = S3Connection(current_app.config['S3_ACCESS_KEY_ID'],
                            current_app.config['S3_SECRET_ACCESS_KEY'])
        bucket = conn.get_bucket(current_app.config['S3_BUCKET_NAME'])
        bucket.make_public(recursive=False)

        k = bucket.new_key(self.picture_path)
        k.set_metadata('Content-Type', mimetype)
        k.set_contents_from_file(fileobj)
        k.make_public()

        self.has_picture = True

    @property
    def helpful_users(self, limit=10):
        '''
        Returns a list of (user, score) tuples with matching positive skills,
        ordered by the most helpful (highest score) descending.
        '''
        my_skills = aliased(UserSkill, name='my_skills', adapt_on_names=True)
        their_skills = aliased(UserSkill,
                               name='their_skills',
                               adapt_on_names=True)

        return User.query_in_deployment().\
                add_column(func.sum(their_skills.level - my_skills.level)).\
                filter(their_skills.user_id != my_skills.user_id).\
                filter(User.id == their_skills.user_id).\
                filter(their_skills.name == my_skills.name).\
                filter(my_skills.user_id == self.id).\
                filter(my_skills.level == LEVELS['LEVEL_I_WANT_TO_LEARN']['score']).\
                group_by(User).\
                order_by(desc(func.sum(their_skills.level - my_skills.level))).\
                limit(limit)

    @property
    def nearest_neighbors(self, limit=10):
        '''
        Returns a list of (user, score) tuples with the closest matching
        skills.  If they haven't answered the equivalent skill question, we
        consider that a very big difference (12).

        Order is closest to least close, which is an ascending score.
        '''
        my_skills = aliased(UserSkill, name='my_skills', adapt_on_names=True)
        their_skills = aliased(UserSkill,
                               name='their_skills',
                               adapt_on_names=True)

        # difference we assume for user that has not answered question
        unanswered_difference = (LEVELS['LEVEL_I_CAN_DO_IT']['score'] -
                                 LEVELS['LEVEL_I_WANT_TO_LEARN']['score']) * 2

        return User.query_in_deployment().\
                add_column(((len(self.skills) - func.count(func.distinct(their_skills.id))) *
                            unanswered_difference) + \
                       func.sum(func.abs(their_skills.level - my_skills.level))).\
                filter(their_skills.user_id != my_skills.user_id).\
                filter(User.id == their_skills.user_id).\
                filter(their_skills.name == my_skills.name).\
                filter(my_skills.user_id == self.id).\
                group_by(User).\
                order_by(((len(self.skills) - func.count(func.distinct(their_skills.id)))
                          * unanswered_difference) + \
                     func.sum(func.abs(their_skills.level - my_skills.level))).\
                limit(limit)

    @property
    def has_fully_registered(self):
        '''
        Returns whether the user has fully completed the registration/signup
        flow.
        '''

        return db.session.query(UserJoinedEvent).\
               filter_by(user_id=self.id).\
               first() is not None

    def set_fully_registered(self):
        '''
        Marks the user as having fully completed the registration/signup
        flow, if they haven't already.
        '''

        if self.has_fully_registered:
            return
        db.session.add(UserJoinedEvent.from_user(self))

    def match(self, level, limit=10):
        '''
        Returns a list of UserSkillMatch objects, in descending order of number
        of skills matched for each user.
        '''

        skills_to_learn = [
            s.name for s in self.skills
            if s.level == LEVELS['LEVEL_I_WANT_TO_LEARN']['score']
        ]
        if skills_to_learn:
            matched_users = User.query_in_deployment().\
                            add_column(func.string_agg(UserSkill.name, ',')).\
                            add_column(func.count(UserSkill.id)).\
                            filter(UserSkill.name.in_(skills_to_learn)).\
                            filter(User.id == UserSkill.user_id).\
                            filter(UserSkill.level == level).\
                            filter(UserSkill.user_id != self.id).\
                            group_by(User).\
                            order_by(func.count().desc()).\
                            limit(limit)
        else:
            matched_users = []

        for user, question_ids_by_comma, count in matched_users:
            yield UserSkillMatch(user, question_ids_by_comma.split(','))

    def match_against(self, user):
        '''
        Returns a list of three-tuples in the format:

        (<questionnaire id>, <count of matching questions>, <skill dict>, )

        In descending order of <count of matching questions>.

        <skill dict> is keyed by the skill level of the other user, with each
        value being a set of questions they can answer at that level.
        '''
        skills = UserSkill.query.\
                filter(UserSkill.user_id == user.id).\
                filter(UserSkill.name.in_(
                    [s.name for s in
                     self.skills if s.level == LEVELS['LEVEL_I_WANT_TO_LEARN']['score']
                    ])).all()

        resp = {}
        for skill in skills:
            question = QUESTIONS_BY_ID[skill.name]
            questionnaire_id = question['questionnaire']['id']
            if questionnaire_id not in resp:
                resp[questionnaire_id] = dict()

            if skill.level not in resp[questionnaire_id]:
                resp[questionnaire_id][skill.level] = set()
            resp[questionnaire_id][skill.level].add(skill.name)

        resp = [(qname,
                 sum([len(questions)
                      for questions in skill_levels.values()]), skill_levels)
                for qname, skill_levels in resp.items()]

        return sorted(resp, lambda a, b: a[1] - b[1], reverse=True)

    def match_against_with_progress(self, user):
        '''
        Like match_against(), but also includes information about
        areas of expertise the target user has that we don't match
        on.
        '''

        progress = user.questionnaire_progress
        matches = self.match_against(user)
        match_areas = {}

        for questionnaire_id, _, _ in matches:
            match_areas[questionnaire_id] = True

        for questionnaire_id, progress in progress.items():
            if (questionnaire_id not in match_areas
                    and progress['answered'] > 0):
                matches.append((questionnaire_id, 0, {}))

        return matches

    def match_against_with_progress_in_area(self, user, areaid):
        '''
        Return a tuple of (matched_skill_dict, unmatched_skill_dict)
        for the given area.

        matched_skill_dict contains information about skills that
        the target user has which we want to learn, while
        unmatched_skill_dict contains all other skills the target
        user has.

        Each dict is keyed by the skill level of the other user,
        with each value being a set of questions they can answer at that
        level.
        '''

        questionnaire = QUESTIONNAIRES_BY_ID[areaid]
        matches = self.match_against(user)

        matched_skill_dict = {}
        matched_skills = {}

        for questionnaire_id, _, skill_dict in matches:
            if questionnaire_id == areaid:
                matched_skill_dict = skill_dict
                break

        for question_ids in matched_skill_dict.values():
            for question_id in question_ids:
                matched_skills[question_id] = True

        unmatched_skill_dict = {}
        skill_levels = user.skill_levels
        for topic in questionnaire.get('topics', []):
            for question in topic['questions']:
                qid = question['id']
                if (qid in skill_levels and qid not in matched_skills):
                    level = skill_levels[qid]
                    if level not in unmatched_skill_dict:
                        unmatched_skill_dict[level] = []
                    unmatched_skill_dict[level].append(qid)

        return (matched_skill_dict, unmatched_skill_dict)

    @property
    def questionnaire_progress(self):
        '''
        Return a dictionary mapping top-level skill area IDs (e.g.,
        'opendata', 'prizes') to information about how many questions
        the user has answered in that skill area.
        '''

        skill_levels = self.skill_levels
        progress = {}
        for questionnaire in QUESTIONNAIRES:
            topic_progress = {'answered': 0, 'total': 0}
            progress[questionnaire['id']] = topic_progress
            for topic in questionnaire.get('topics', []):
                for question in topic['questions']:
                    topic_progress['total'] += 1
                    if question['id'] in skill_levels:
                        topic_progress['answered'] += 1
        return progress

    @property
    def skill_levels(self):
        '''
        Dictionary of this user's entered skills, keyed by the id of the skill.
        '''
        return dict([(skill.name, skill.level) for skill in self.skills])

    @property
    def connections(self):
        '''
        Count the number of distinct email addresses this person has sent or
        received messages from in the deployment.
        '''
        sent = db.session.query(func.count(func.distinct(Email.to_user_id))).\
                filter(Email.to_user_id != self.id).\
                filter(Email.from_user_id == self.id).first()[0]
        received = db.session.query(func.count(func.distinct(Email.from_user_id))).\
                filter(Email.from_user_id != self.id).\
                filter(Email.to_user_id == self.id).first()[0]
        return sent + received

    def set_skill(self, skill_name, skill_level):
        '''
        Set the level of a single skill by name.
        '''
        if skill_name not in QUESTIONS_BY_ID:
            return
        try:
            if int(skill_level) not in VALID_SKILL_LEVELS:
                return
        except ValueError:
            return
        for skill in self.skills:
            if skill_name == skill.name:
                skill.level = skill_level
                db.session.add(skill)
                return
        db.session.add(
            UserSkill(user_id=self.id, name=skill_name, level=skill_level))

    def email_connect(self, users):
        '''
        Indicate that this user has opened an email window with this list of
        users as recipients.
        '''
        event = ConnectionEvent()
        for user in users:
            event.emails.append(Email(from_user_id=self.id,
                                      to_user_id=user.id))

        db.session.add(event)
        return event

    roles = orm.relationship('Role',
                             secondary='role_users',
                             backref=orm.backref('users', lazy='dynamic'))

    expertise_domains = orm.relationship('UserExpertiseDomain',
                                         cascade='all,delete-orphan',
                                         backref='user')
    languages = orm.relationship('UserLanguage',
                                 cascade='all,delete-orphan',
                                 backref='user')
    skills = orm.relationship('UserSkill',
                              cascade='all,delete-orphan',
                              backref='user')

    @classmethod
    def get_most_complete_profiles(cls, limit=10):
        '''
        Obtain a list of most complete profiles, as (User, score) tuples.
        '''
        return User.query_in_deployment().\
                add_column(func.count(UserSkill.id)).\
                filter(User.id == UserSkill.user_id).\
                group_by(User).\
                order_by(func.count(UserSkill.id).desc()).\
                limit(limit)

    @classmethod
    def get_most_connected_profiles(cls, limit=10):
        '''
        Obtain a list of most connected profiles, as descending (User, score)
        tuples.
        '''
        count_of_unique_emails = func.count(
            func.distinct(
                cast(Email.to_user_id, String) + '-' +
                cast(Email.from_user_id, String)))
        return User.query_in_deployment().\
                add_column(count_of_unique_emails).\
                filter((User.id == Email.from_user_id) | (User.id == Email.to_user_id)).\
                group_by(User).\
                order_by(count_of_unique_emails.desc()).\
                limit(limit)

    @hybrid_property
    def expertise_domain_names(self):
        '''
        Convenient list of expertise domains by name.
        '''
        return [ed.name for ed in self.expertise_domains]

    @expertise_domain_names.setter
    def _expertise_domains_setter(self, values):
        '''
        Update expertise domains in bulk.  Values are array of names.
        '''
        # Only add new expertise
        for val in values:
            if val not in self.expertise_domain_names:
                db.session.add(UserExpertiseDomain(name=val, user_id=self.id))
        # delete expertise no longer found
        expertise_to_remove = []
        for exp in self.expertise_domains:
            if exp.name not in values:
                expertise_to_remove.append(exp)

        for exp in expertise_to_remove:
            self.expertise_domains.remove(exp)

    def get_area_scores(self):
        skill_levels = self.skill_levels
        result = {}

        NO_ANSWER = -999

        for questionnaire in QUESTIONNAIRES:
            if not questionnaire['questions']:
                continue
            max_score = NO_ANSWER
            answers_with_score = {}
            for question in questionnaire['questions']:
                if question['id'] in skill_levels:
                    score = skill_levels[question['id']]
                    if score > max_score:
                        max_score = score
                    if score not in answers_with_score:
                        answers_with_score[score] = 0
                    answers_with_score[score] += 1
            reported_max_score = None
            if max_score != NO_ANSWER:
                reported_max_score = max_score
            result[questionnaire['id']] = {
                'skills': scores_to_skills(answers_with_score),
                'max_score': reported_max_score
            }

        return result

    @hybrid_property
    def locales(self):
        '''
        Convenient list of locales for this user.
        '''
        return [l.locale for l in self.languages]

    @locales.setter
    def _languages_setter(self, values):
        '''
        Update locales for this user in bulk.  Values are an array of language
        codes.
        '''
        locale_codes = [l.language for l in self.locales]
        # only add new languages
        for val in values:
            if val not in locale_codes:
                db.session.add(UserLanguage(locale=val, user_id=self.id))

        # delete languages no longer found
        languages_to_remove = []
        for lan in self.languages:
            if lan.locale.language not in values:
                languages_to_remove.append(lan)

        for lan in languages_to_remove:
            self.languages.remove(lan)

    __table_args__ = (UniqueConstraint('deployment', 'email'), )
def test_should_integer_convert_int():
    assert get_field(types.Integer()).type == graphene.Int
示例#17
0
class Post(BaseTable):
    __tablename__ = 'posts'

    id = Column(types.Integer(10), primary_key=True)
    title = Column(types.Unicode(255))
    content = Column(types.UnicodeText)
    summary = Column(types.UnicodeText, nullable=True)
    slug = Column(types.Unicode(255), unique=True)
    category_id = Column(types.Integer(10), ForeignKey('categories.id'))
    category = relation('Category')
    user_id = Column(types.Integer(10), ForeignKey('users.id'))
    user = relation('User')
    posted = Column(types.DateTime, default=datetime.datetime.now)
    comments = relation('Comment', order_by=['id'])
    comments_count = Column(types.Integer(10), nullable=True, default=0)

    def __init__(self, title, category_id, content, user_id, **kwargs):
        self.title = title
        self.category_id = category_id
        self.content = content
        self.user_id = user_id
        self.slug = slug(kwargs.get('slug', ''))
        if not self.slug:
            # Automatically generate a slug (URL) from the title if there was
            # none supplied.
            self.slug = slug(self.title)
        self.summary = kwargs.get('summary', '')

    def __repr__(self):
        return '<Post: "%s" by %s>' % (self.title, self.user.name)

    @classmethod
    def all(self):
        q = session.query(Post).order_by(Post.posted.desc())
        return q.all()

    @classmethod
    def by_category(self, id):
        q = session.query(Post).filter(Post.category_id == id)
        return q

    @classmethod
    def by_id(self, id):
        q = session.query(Post).filter(Post.id == id)
        return q

    @classmethod
    def by_slug(self, slug):
        q = session.query(Post).filter(Post.slug == slug)
        return q

    @classmethod
    def by_slug_category(self, slug, category):
        q = session.query(Post).filter(
            and_(Post.slug == slug, Category.slug == category))
        return q

    @classmethod
    def by_user(self, id):
        q = session.query(Post).filter(Post.user_id == id)
        return q
def test_should_primary_integer_convert_id():
    assert get_field(types.Integer(), primary_key=True).type == graphene.NonNull(graphene.ID)
示例#19
0
from six import text_type

import vdm.sqlalchemy
import meta
import core
import domain_object

__all__ = [
    'system_info_revision_table', 'system_info_table', 'SystemInfo',
    'SystemInfoRevision', 'get_system_info', 'set_system_info'
]

system_info_table = Table(
    'system_info',
    meta.metadata,
    Column('id', types.Integer(), primary_key=True, nullable=False),
    Column('key', types.Unicode(100), unique=True, nullable=False),
    Column('value', types.UnicodeText),
    Column('state', types.UnicodeText, default=core.State.ACTIVE),
)

system_info_revision_table = core.make_revisioned_table(system_info_table)


class SystemInfo(vdm.sqlalchemy.RevisionedObjectMixin,
                 core.StatefulObjectMixin, domain_object.DomainObject):
    def __init__(self, key, value):

        super(SystemInfo, self).__init__()

        self.key = key
示例#20
0
        class TestModel(Model):
            __tablename__ = 'test'
            _id = Column(types.Integer(), primary_key=True)

            query_class = None
示例#21
0
文件: base.py 项目: zzyifan/superset
class BaseEngineSpec:  # pylint: disable=too-many-public-methods
    """Abstract class for database engine specific configurations"""

    engine = "base"  # str as defined in sqlalchemy.engine.engine
    engine_aliases: Optional[Tuple[str]] = None
    engine_name: Optional[
        str] = None  # used for user messages, overridden in child classes
    _date_trunc_functions: Dict[str, str] = {}
    _time_grain_expressions: Dict[Optional[str], str] = {}
    column_type_mappings: Tuple[Tuple[Pattern[str],
                                      Union[TypeEngine, Callable[[Match[str]],
                                                                 TypeEngine]],
                                      GenericDataType, ],
                                ..., ] = (
                                    (
                                        re.compile(r"^smallint",
                                                   re.IGNORECASE),
                                        types.SmallInteger(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^integer", re.IGNORECASE),
                                        types.Integer(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^bigint", re.IGNORECASE),
                                        types.BigInteger(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^decimal", re.IGNORECASE),
                                        types.Numeric(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^numeric", re.IGNORECASE),
                                        types.Numeric(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^real", re.IGNORECASE),
                                        types.REAL,
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^smallserial",
                                                   re.IGNORECASE),
                                        types.SmallInteger(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^serial", re.IGNORECASE),
                                        types.Integer(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^bigserial",
                                                   re.IGNORECASE),
                                        types.BigInteger(),
                                        GenericDataType.NUMERIC,
                                    ),
                                    (
                                        re.compile(r"^string", re.IGNORECASE),
                                        types.String(),
                                        utils.GenericDataType.STRING,
                                    ),
                                    (
                                        re.compile(r"^N((VAR)?CHAR|TEXT)",
                                                   re.IGNORECASE),
                                        UnicodeText(),
                                        utils.GenericDataType.STRING,
                                    ),
                                    (
                                        re.compile(
                                            r"^((VAR)?CHAR|TEXT|STRING)",
                                            re.IGNORECASE),
                                        String(),
                                        utils.GenericDataType.STRING,
                                    ),
                                    (
                                        re.compile(r"^date", re.IGNORECASE),
                                        types.Date(),
                                        GenericDataType.TEMPORAL,
                                    ),
                                    (
                                        re.compile(r"^timestamp",
                                                   re.IGNORECASE),
                                        types.TIMESTAMP(),
                                        GenericDataType.TEMPORAL,
                                    ),
                                    (
                                        re.compile(r"^interval",
                                                   re.IGNORECASE),
                                        types.Interval(),
                                        GenericDataType.TEMPORAL,
                                    ),
                                    (
                                        re.compile(r"^time", re.IGNORECASE),
                                        types.Time(),
                                        GenericDataType.TEMPORAL,
                                    ),
                                    (
                                        re.compile(r"^boolean", re.IGNORECASE),
                                        types.Boolean(),
                                        GenericDataType.BOOLEAN,
                                    ),
                                )
    time_groupby_inline = False
    limit_method = LimitMethod.FORCE_LIMIT
    time_secondary_columns = False
    allows_joins = True
    allows_subqueries = True
    allows_alias_in_select = True
    allows_alias_in_orderby = True
    allows_sql_comments = True
    force_column_alias_quotes = False
    arraysize = 0
    max_column_name_length = 0
    try_remove_schema_from_table_name = True  # pylint: disable=invalid-name
    run_multiple_statements_as_one = False

    @classmethod
    def get_dbapi_exception_mapping(
            cls) -> Dict[Type[Exception], Type[Exception]]:
        """
        Each engine can implement and converge its own specific exceptions into
        Superset DBAPI exceptions

        Note: On python 3.9 this method can be changed to a classmethod property
        without the need of implementing a metaclass type

        :return: A map of driver specific exception to superset custom exceptions
        """
        return {}

    @classmethod
    def get_dbapi_mapped_exception(cls, exception: Exception) -> Exception:
        """
        Get a superset custom DBAPI exception from the driver specific exception.

        Override if the engine needs to perform extra changes to the exception, for
        example change the exception message or implement custom more complex logic

        :param exception: The driver specific exception
        :return: Superset custom DBAPI exception
        """
        new_exception = cls.get_dbapi_exception_mapping().get(type(exception))
        if not new_exception:
            return exception
        return new_exception(str(exception))

    @classmethod
    def get_allow_cost_estimate(cls, extra: Dict[str, Any]) -> bool:
        return False

    @classmethod
    def get_engine(
        cls,
        database: "Database",
        schema: Optional[str] = None,
        source: Optional[str] = None,
    ) -> Engine:
        user_name = utils.get_username()
        return database.get_sqla_engine(schema=schema,
                                        nullpool=True,
                                        user_name=user_name,
                                        source=source)

    @classmethod
    def get_timestamp_expr(
        cls,
        col: ColumnClause,
        pdf: Optional[str],
        time_grain: Optional[str],
        type_: Optional[str] = None,
    ) -> TimestampExpression:
        """
        Construct a TimestampExpression to be used in a SQLAlchemy query.

        :param col: Target column for the TimestampExpression
        :param pdf: date format (seconds or milliseconds)
        :param time_grain: time grain, e.g. P1Y for 1 year
        :param type_: the source column type
        :return: TimestampExpression object
        """
        if time_grain:
            time_expr = cls.get_time_grain_expressions().get(time_grain)
            if not time_expr:
                raise NotImplementedError(
                    f"No grain spec for {time_grain} for database {cls.engine}"
                )
            if type_ and "{func}" in time_expr:
                date_trunc_function = cls._date_trunc_functions.get(type_)
                if date_trunc_function:
                    time_expr = time_expr.replace("{func}",
                                                  date_trunc_function)
            if type_ and "{type}" in time_expr:
                date_trunc_function = cls._date_trunc_functions.get(type_)
                if date_trunc_function:
                    time_expr = time_expr.replace("{type}", type_)
        else:
            time_expr = "{col}"

        # if epoch, translate to DATE using db specific conf
        if pdf == "epoch_s":
            time_expr = time_expr.replace("{col}", cls.epoch_to_dttm())
        elif pdf == "epoch_ms":
            time_expr = time_expr.replace("{col}", cls.epoch_ms_to_dttm())

        return TimestampExpression(time_expr, col, type_=DateTime)

    @classmethod
    def get_time_grains(cls) -> Tuple[TimeGrain, ...]:
        """
        Generate a tuple of supported time grains.

        :return: All time grains supported by the engine
        """

        ret_list = []
        time_grains = builtin_time_grains.copy()
        time_grains.update(config["TIME_GRAIN_ADDONS"])
        for duration, func in cls.get_time_grain_expressions().items():
            if duration in time_grains:
                name = time_grains[duration]
                ret_list.append(TimeGrain(name, _(name), func, duration))
        return tuple(ret_list)

    @classmethod
    def get_time_grain_expressions(cls) -> Dict[Optional[str], str]:
        """
        Return a dict of all supported time grains including any potential added grains
        but excluding any potentially disabled grains in the config file.

        :return: All time grain expressions supported by the engine
        """
        # TODO: use @memoize decorator or similar to avoid recomputation on every call
        time_grain_expressions = cls._time_grain_expressions.copy()
        grain_addon_expressions = config["TIME_GRAIN_ADDON_EXPRESSIONS"]
        time_grain_expressions.update(
            grain_addon_expressions.get(cls.engine, {}))
        denylist: List[str] = config["TIME_GRAIN_DENYLIST"]
        for key in denylist:
            time_grain_expressions.pop(key)
        return time_grain_expressions

    @classmethod
    def make_select_compatible(
            cls, groupby_exprs: Dict[str, ColumnElement],
            select_exprs: List[ColumnElement]) -> List[ColumnElement]:
        """
        Some databases will just return the group-by field into the select, but don't
        allow the group-by field to be put into the select list.

        :param groupby_exprs: mapping between column name and column object
        :param select_exprs: all columns in the select clause
        :return: columns to be included in the final select clause
        """
        return select_exprs

    @classmethod
    def fetch_data(cls,
                   cursor: Any,
                   limit: Optional[int] = None) -> List[Tuple[Any, ...]]:
        """

        :param cursor: Cursor instance
        :param limit: Maximum number of rows to be returned by the cursor
        :return: Result of query
        """
        if cls.arraysize:
            cursor.arraysize = cls.arraysize
        try:
            if cls.limit_method == LimitMethod.FETCH_MANY and limit:
                return cursor.fetchmany(limit)
            return cursor.fetchall()
        except Exception as ex:
            raise cls.get_dbapi_mapped_exception(ex)

    @classmethod
    def expand_data(
        cls, columns: List[Dict[Any, Any]], data: List[Dict[Any, Any]]
    ) -> Tuple[List[Dict[Any, Any]], List[Dict[Any, Any]], List[Dict[Any,
                                                                     Any]]]:
        """
        Some engines support expanding nested fields. See implementation in Presto
        spec for details.

        :param columns: columns selected in the query
        :param data: original data set
        :return: list of all columns(selected columns and their nested fields),
                 expanded data set, listed of nested fields
        """
        return columns, data, []

    @classmethod
    def alter_new_orm_column(cls, orm_col: "TableColumn") -> None:
        """Allow altering default column attributes when first detected/added

        For instance special column like `__time` for Druid can be
        set to is_dttm=True. Note that this only gets called when new
        columns are detected/created"""
        # TODO: Fix circular import caused by importing TableColumn

    @classmethod
    def epoch_to_dttm(cls) -> str:
        """
        SQL expression that converts epoch (seconds) to datetime that can be used in a
        query. The reference column should be denoted as `{col}` in the return
        expression, e.g. "FROM_UNIXTIME({col})"

        :return: SQL Expression
        """
        raise NotImplementedError()

    @classmethod
    def epoch_ms_to_dttm(cls) -> str:
        """
        SQL expression that converts epoch (milliseconds) to datetime that can be used
        in a query.

        :return: SQL Expression
        """
        return cls.epoch_to_dttm().replace("{col}", "({col}/1000)")

    @classmethod
    def get_datatype(cls, type_code: Any) -> Optional[str]:
        """
        Change column type code from cursor description to string representation.

        :param type_code: Type code from cursor description
        :return: String representation of type code
        """
        if isinstance(type_code, str) and type_code != "":
            return type_code.upper()
        return None

    @classmethod
    def normalize_indexes(
            cls, indexes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        Normalizes indexes for more consistency across db engines

        noop by default

        :param indexes: Raw indexes as returned by SQLAlchemy
        :return: cleaner, more aligned index definition
        """
        return indexes

    @classmethod
    def extra_table_metadata(cls, database: "Database", table_name: str,
                             schema_name: str) -> Dict[str, Any]:
        """
        Returns engine-specific table metadata

        :param database: Database instance
        :param table_name: Table name
        :param schema_name: Schema name
        :return: Engine-specific table metadata
        """
        # TODO: Fix circular import caused by importing Database
        return {}

    @classmethod
    def apply_limit_to_sql(cls, sql: str, limit: int,
                           database: "Database") -> str:
        """
        Alters the SQL statement to apply a LIMIT clause

        :param sql: SQL query
        :param limit: Maximum number of rows to be returned by the query
        :param database: Database instance
        :return: SQL query with limit clause
        """
        # TODO: Fix circular import caused by importing Database
        if cls.limit_method == LimitMethod.WRAP_SQL:
            sql = sql.strip("\t\n ;")
            qry = (select("*").select_from(
                TextAsFrom(text(sql), ["*"]).alias("inner_qry")).limit(limit))
            return database.compile_sqla_query(qry)

        if cls.limit_method == LimitMethod.FORCE_LIMIT:
            parsed_query = sql_parse.ParsedQuery(sql)
            sql = parsed_query.set_or_update_query_limit(limit)

        return sql

    @classmethod
    def get_limit_from_sql(cls, sql: str) -> Optional[int]:
        """
        Extract limit from SQL query

        :param sql: SQL query
        :return: Value of limit clause in query
        """
        parsed_query = sql_parse.ParsedQuery(sql)
        return parsed_query.limit

    @classmethod
    def set_or_update_query_limit(cls, sql: str, limit: int) -> str:
        """
        Create a query based on original query but with new limit clause

        :param sql: SQL query
        :param limit: New limit to insert/replace into query
        :return: Query with new limit
        """
        parsed_query = sql_parse.ParsedQuery(sql)
        return parsed_query.set_or_update_query_limit(limit)

    @staticmethod
    def csv_to_df(**kwargs: Any) -> pd.DataFrame:
        """Read csv into Pandas DataFrame
        :param kwargs: params to be passed to DataFrame.read_csv
        :return: Pandas DataFrame containing data from csv
        """
        kwargs["encoding"] = "utf-8"
        kwargs["iterator"] = True
        chunks = pd.read_csv(**kwargs)
        df = pd.concat(chunk for chunk in chunks)
        return df

    @classmethod
    def df_to_sql(cls, df: pd.DataFrame, **kwargs: Any) -> None:
        """Upload data from a Pandas DataFrame to a database. For
        regular engines this calls the DataFrame.to_sql() method. Can be
        overridden for engines that don't work well with to_sql(), e.g.
        BigQuery.
        :param df: Dataframe with data to be uploaded
        :param kwargs: kwargs to be passed to to_sql() method
        """
        df.to_sql(**kwargs)

    @classmethod
    def create_table_from_csv(  # pylint: disable=too-many-arguments
        cls,
        filename: str,
        table: Table,
        database: "Database",
        csv_to_df_kwargs: Dict[str, Any],
        df_to_sql_kwargs: Dict[str, Any],
    ) -> None:
        """
        Create table from contents of a csv. Note: this method does not create
        metadata for the table.
        """
        df = cls.csv_to_df(filepath_or_buffer=filename, **csv_to_df_kwargs)
        engine = cls.get_engine(database)
        if table.schema:
            # only add schema when it is preset and non empty
            df_to_sql_kwargs["schema"] = table.schema
        if engine.dialect.supports_multivalues_insert:
            df_to_sql_kwargs["method"] = "multi"
        cls.df_to_sql(df=df, con=engine, **df_to_sql_kwargs)

    @classmethod
    def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]:
        """
        Convert Python datetime object to a SQL expression

        :param target_type: The target type of expression
        :param dttm: The datetime object
        :return: The SQL expression
        """
        return None

    @classmethod
    def create_table_from_excel(  # pylint: disable=too-many-arguments
        cls,
        filename: str,
        table: Table,
        database: "Database",
        excel_to_df_kwargs: Dict[str, Any],
        df_to_sql_kwargs: Dict[str, Any],
    ) -> None:
        """
        Create table from contents of a excel. Note: this method does not create
        metadata for the table.
        """
        df = pd.read_excel(io=filename, **excel_to_df_kwargs)
        engine = cls.get_engine(database)
        if table.schema:
            # only add schema when it is preset and non empty
            df_to_sql_kwargs["schema"] = table.schema
        if engine.dialect.supports_multivalues_insert:
            df_to_sql_kwargs["method"] = "multi"
        cls.df_to_sql(df=df, con=engine, **df_to_sql_kwargs)

    @classmethod
    def get_all_datasource_names(
            cls, database: "Database",
            datasource_type: str) -> List[utils.DatasourceName]:
        """Returns a list of all tables or views in database.

        :param database: Database instance
        :param datasource_type: Datasource_type can be 'table' or 'view'
        :return: List of all datasources in database or schema
        """
        # TODO: Fix circular import caused by importing Database
        schemas = database.get_all_schema_names(
            cache=database.schema_cache_enabled,
            cache_timeout=database.schema_cache_timeout,
            force=True,
        )
        all_datasources: List[utils.DatasourceName] = []
        for schema in schemas:
            if datasource_type == "table":
                all_datasources += database.get_all_table_names_in_schema(
                    schema=schema,
                    force=True,
                    cache=database.table_cache_enabled,
                    cache_timeout=database.table_cache_timeout,
                )
            elif datasource_type == "view":
                all_datasources += database.get_all_view_names_in_schema(
                    schema=schema,
                    force=True,
                    cache=database.table_cache_enabled,
                    cache_timeout=database.table_cache_timeout,
                )
            else:
                raise Exception(
                    f"Unsupported datasource_type: {datasource_type}")
        return all_datasources

    @classmethod
    def handle_cursor(cls, cursor: Any, query: Query,
                      session: Session) -> None:
        """Handle a live cursor between the execute and fetchall calls

        The flow works without this method doing anything, but it allows
        for handling the cursor and updating progress information in the
        query object"""
        # TODO: Fix circular import error caused by importing sql_lab.Query

    @classmethod
    def extract_error_message(cls, ex: Exception) -> str:
        return f"{cls.engine} error: {cls._extract_error_message(ex)}"

    @classmethod
    def _extract_error_message(cls, ex: Exception) -> str:
        """Extract error message for queries"""
        return utils.error_msg_from_exception(ex)

    @classmethod
    def extract_errors(cls, ex: Exception) -> List[Dict[str, Any]]:
        return [
            dataclasses.asdict(
                SupersetError(
                    error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
                    message=cls._extract_error_message(ex),
                    level=ErrorLevel.ERROR,
                    extra={"engine_name": cls.engine_name},
                ))
        ]

    @classmethod
    def adjust_database_uri(cls, uri: URL,
                            selected_schema: Optional[str]) -> None:
        """
        Mutate the database component of the SQLAlchemy URI.

        The URI here represents the URI as entered when saving the database,
        ``selected_schema`` is the schema currently active presumably in
        the SQL Lab dropdown. Based on that, for some database engine,
        we can return a new altered URI that connects straight to the
        active schema, meaning the users won't have to prefix the object
        names by the schema name.

        Some databases engines have 2 level of namespacing: database and
        schema (postgres, oracle, mssql, ...)
        For those it's probably better to not alter the database
        component of the URI with the schema name, it won't work.

        Some database drivers like presto accept '{catalog}/{schema}' in
        the database component of the URL, that can be handled here.
        """

    @classmethod
    def patch(cls) -> None:
        """
        TODO: Improve docstring and refactor implementation in Hive
        """

    @classmethod
    def get_schema_names(cls, inspector: Inspector) -> List[str]:
        """
        Get all schemas from database

        :param inspector: SqlAlchemy inspector
        :return: All schemas in the database
        """
        return sorted(inspector.get_schema_names())

    @classmethod
    def get_table_names(cls, database: "Database", inspector: Inspector,
                        schema: Optional[str]) -> List[str]:
        """
        Get all tables from schema

        :param inspector: SqlAlchemy inspector
        :param schema: Schema to inspect. If omitted, uses default schema for database
        :return: All tables in schema
        """
        tables = inspector.get_table_names(schema)
        if schema and cls.try_remove_schema_from_table_name:
            tables = [re.sub(f"^{schema}\\.", "", table) for table in tables]
        return sorted(tables)

    @classmethod
    def get_view_names(cls, database: "Database", inspector: Inspector,
                       schema: Optional[str]) -> List[str]:
        """
        Get all views from schema

        :param inspector: SqlAlchemy inspector
        :param schema: Schema name. If omitted, uses default schema for database
        :return: All views in schema
        """
        views = inspector.get_view_names(schema)
        if schema and cls.try_remove_schema_from_table_name:
            views = [re.sub(f"^{schema}\\.", "", view) for view in views]
        return sorted(views)

    @classmethod
    def get_table_comment(cls, inspector: Inspector, table_name: str,
                          schema: Optional[str]) -> Optional[str]:
        """
        Get comment of table from a given schema and table

        :param inspector: SqlAlchemy Inspector instance
        :param table_name: Table name
        :param schema: Schema name. If omitted, uses default schema for database
        :return: comment of table
        """
        comment = None
        try:
            comment = inspector.get_table_comment(table_name, schema)
            comment = comment.get("text") if isinstance(comment,
                                                        dict) else None
        except NotImplementedError:
            # It's expected that some dialects don't implement the comment method
            pass
        except Exception as ex:  # pylint: disable=broad-except
            logger.error("Unexpected error while fetching table comment")
            logger.exception(ex)
        return comment

    @classmethod
    def get_columns(cls, inspector: Inspector, table_name: str,
                    schema: Optional[str]) -> List[Dict[str, Any]]:
        """
        Get all columns from a given schema and table

        :param inspector: SqlAlchemy Inspector instance
        :param table_name: Table name
        :param schema: Schema name. If omitted, uses default schema for database
        :return: All columns in table
        """
        return inspector.get_columns(table_name, schema)

    @classmethod
    def where_latest_partition(  # pylint: disable=too-many-arguments
        cls,
        table_name: str,
        schema: Optional[str],
        database: "Database",
        query: Select,
        columns: Optional[List[Dict[str, str]]] = None,
    ) -> Optional[Select]:
        """
        Add a where clause to a query to reference only the most recent partition

        :param table_name: Table name
        :param schema: Schema name
        :param database: Database instance
        :param query: SqlAlchemy query
        :param columns: List of TableColumns
        :return: SqlAlchemy query with additional where clause referencing latest
        partition
        """
        # TODO: Fix circular import caused by importing Database, TableColumn
        return None

    @classmethod
    def _get_fields(cls, cols: List[Dict[str, Any]]) -> List[Any]:
        return [column(c["name"]) for c in cols]

    @classmethod
    def select_star(  # pylint: disable=too-many-arguments,too-many-locals
        cls,
        database: "Database",
        table_name: str,
        engine: Engine,
        schema: Optional[str] = None,
        limit: int = 100,
        show_cols: bool = False,
        indent: bool = True,
        latest_partition: bool = True,
        cols: Optional[List[Dict[str, Any]]] = None,
    ) -> str:
        """
        Generate a "SELECT * from [schema.]table_name" query with appropriate limit.

        WARNING: expects only unquoted table and schema names.

        :param database: Database instance
        :param table_name: Table name, unquoted
        :param engine: SqlALchemy Engine instance
        :param schema: Schema, unquoted
        :param limit: limit to impose on query
        :param show_cols: Show columns in query; otherwise use "*"
        :param indent: Add indentation to query
        :param latest_partition: Only query latest partition
        :param cols: Columns to include in query
        :return: SQL query
        """
        fields: Union[str, List[Any]] = "*"
        cols = cols or []
        if (show_cols or latest_partition) and not cols:
            cols = database.get_columns(table_name, schema)

        if show_cols:
            fields = cls._get_fields(cols)
        quote = engine.dialect.identifier_preparer.quote
        if schema:
            full_table_name = quote(schema) + "." + quote(table_name)
        else:
            full_table_name = quote(table_name)

        qry = select(fields).select_from(text(full_table_name))

        if limit:
            qry = qry.limit(limit)
        if latest_partition:
            partition_query = cls.where_latest_partition(table_name,
                                                         schema,
                                                         database,
                                                         qry,
                                                         columns=cols)
            if partition_query is not None:
                qry = partition_query
        sql = database.compile_sqla_query(qry)
        if indent:
            sql = sqlparse.format(sql, reindent=True)
        return sql

    @classmethod
    def estimate_statement_cost(
        cls,
        statement: str,
        cursor: Any,
    ) -> Dict[str, Any]:
        """
        Generate a SQL query that estimates the cost of a given statement.

        :param statement: A single SQL statement
        :param cursor: Cursor instance
        :return: Dictionary with different costs
        """
        raise Exception("Database does not support cost estimation")

    @classmethod
    def query_cost_formatter(
            cls, raw_cost: List[Dict[str, Any]]) -> List[Dict[str, str]]:
        """
        Format cost estimate.

        :param raw_cost: Raw estimate from `estimate_query_cost`
        :return: Human readable cost estimate
        """
        raise Exception("Database does not support cost estimation")

    @classmethod
    def process_statement(cls, statement: str, database: "Database",
                          user_name: str) -> str:
        """
        Process a SQL statement by stripping and mutating it.

        :param statement: A single SQL statement
        :param database: Database instance
        :param username: Effective username
        :return: Dictionary with different costs
        """
        parsed_query = ParsedQuery(statement)
        sql = parsed_query.stripped()
        sql_query_mutator = config["SQL_QUERY_MUTATOR"]
        if sql_query_mutator:
            sql = sql_query_mutator(sql, user_name, security_manager, database)

        return sql

    @classmethod
    def estimate_query_cost(
            cls,
            database: "Database",
            schema: str,
            sql: str,
            source: Optional[str] = None) -> List[Dict[str, Any]]:
        """
        Estimate the cost of a multiple statement SQL query.

        :param database: Database instance
        :param schema: Database schema
        :param sql: SQL query with possibly multiple statements
        :param source: Source of the query (eg, "sql_lab")
        """
        extra = database.get_extra() or {}
        if not cls.get_allow_cost_estimate(extra):
            raise Exception("Database does not support cost estimation")

        user_name = g.user.username if g.user else None
        parsed_query = sql_parse.ParsedQuery(sql)
        statements = parsed_query.get_statements()

        engine = cls.get_engine(database, schema=schema, source=source)
        costs = []
        with closing(engine.raw_connection()) as conn:
            cursor = conn.cursor()
            for statement in statements:
                processed_statement = cls.process_statement(
                    statement, database, user_name)
                costs.append(
                    cls.estimate_statement_cost(processed_statement, cursor))
        return costs

    @classmethod
    def modify_url_for_impersonation(cls, url: URL, impersonate_user: bool,
                                     username: Optional[str]) -> None:
        """
        Modify the SQL Alchemy URL object with the user to impersonate if applicable.
        :param url: SQLAlchemy URL object
        :param impersonate_user: Flag indicating if impersonation is enabled
        :param username: Effective username
        """
        if impersonate_user and username is not None:
            url.username = username

    @classmethod
    def update_impersonation_config(
        cls,
        connect_args: Dict[str, Any],
        uri: str,
        username: Optional[str],
    ) -> None:
        """
        Update a configuration dictionary
        that can set the correct properties for impersonating users

        :param connect_args: config to be updated
        :param uri: URI
        :param impersonate_user: Flag indicating if impersonation is enabled
        :param username: Effective username
        :return: None
        """

    @classmethod
    def execute(cls, cursor: Any, query: str, **kwargs: Any) -> None:
        """
        Execute a SQL query

        :param cursor: Cursor instance
        :param query: Query to execute
        :param kwargs: kwargs to be passed to cursor.execute()
        :return:
        """
        if not cls.allows_sql_comments:
            query = sql_parse.strip_comments_from_sql(query)

        if cls.arraysize:
            cursor.arraysize = cls.arraysize
        try:
            cursor.execute(query)
        except Exception as ex:
            raise cls.get_dbapi_mapped_exception(ex)

    @classmethod
    def make_label_compatible(cls, label: str) -> Union[str, quoted_name]:
        """
        Conditionally mutate and/or quote a sqlalchemy expression label. If
        force_column_alias_quotes is set to True, return the label as a
        sqlalchemy.sql.elements.quoted_name object to ensure that the select query
        and query results have same case. Otherwise return the mutated label as a
        regular string. If maxmimum supported column name length is exceeded,
        generate a truncated label by calling truncate_label().

        :param label: expected expression label/alias
        :return: conditionally mutated label supported by the db engine
        """
        label_mutated = cls._mutate_label(label)
        if (cls.max_column_name_length
                and len(label_mutated) > cls.max_column_name_length):
            label_mutated = cls._truncate_label(label)
        if cls.force_column_alias_quotes:
            label_mutated = quoted_name(label_mutated, True)
        return label_mutated

    @classmethod
    def get_sqla_column_type(
        cls,
        column_type: Optional[str],
        column_type_mappings: Tuple[Tuple[Pattern[str],
                                          Union[TypeEngine,
                                                Callable[[Match[str]],
                                                         TypeEngine]],
                                          GenericDataType, ],
                                    ..., ] = column_type_mappings,
    ) -> Union[Tuple[TypeEngine, GenericDataType], None]:
        """
        Return a sqlalchemy native column type that corresponds to the column type
        defined in the data source (return None to use default type inferred by
        SQLAlchemy). Override `column_type_mappings` for specific needs
        (see MSSQL for example of NCHAR/NVARCHAR handling).

        :param column_type: Column type returned by inspector
        :return: SqlAlchemy column type
        """
        if not column_type:
            return None
        for regex, sqla_type, generic_type in column_type_mappings:
            match = regex.match(column_type)
            if match:
                if callable(sqla_type):
                    return sqla_type(match), generic_type
                return sqla_type, generic_type
        return None

    @staticmethod
    def _mutate_label(label: str) -> str:
        """
        Most engines support mixed case aliases that can include numbers
        and special characters, like commas, parentheses etc. For engines that
        have restrictions on what types of aliases are supported, this method
        can be overridden to ensure that labels conform to the engine's
        limitations. Mutated labels should be deterministic (input label A always
        yields output label X) and unique (input labels A and B don't yield the same
        output label X).

        :param label: Preferred expression label
        :return: Conditionally mutated label
        """
        return label

    @classmethod
    def _truncate_label(cls, label: str) -> str:
        """
        In the case that a label exceeds the max length supported by the engine,
        this method is used to construct a deterministic and unique label based on
        the original label. By default this returns an md5 hash of the original label,
        conditionally truncated if the length of the hash exceeds the max column length
        of the engine.

        :param label: Expected expression label
        :return: Truncated label
        """
        label = hashlib.md5(label.encode("utf-8")).hexdigest()
        # truncate hash if it exceeds max length
        if cls.max_column_name_length and len(
                label) > cls.max_column_name_length:
            label = label[:cls.max_column_name_length]
        return label

    @classmethod
    def column_datatype_to_string(cls, sqla_column_type: TypeEngine,
                                  dialect: Dialect) -> str:
        """
        Convert sqlalchemy column type to string representation.
        By default removes collation and character encoding info to avoid unnecessarily
        long datatypes.

        :param sqla_column_type: SqlAlchemy column type
        :param dialect: Sqlalchemy dialect
        :return: Compiled column type
        """
        sqla_column_type = sqla_column_type.copy()
        if hasattr(sqla_column_type, "collation"):
            sqla_column_type.collation = None
        if hasattr(sqla_column_type, "charset"):
            sqla_column_type.charset = None
        return sqla_column_type.compile(dialect=dialect).upper()

    @classmethod
    def get_function_names(cls, database: "Database") -> List[str]:
        """
        Get a list of function names that are able to be called on the database.
        Used for SQL Lab autocomplete.

        :param database: The database to get functions for
        :return: A list of function names useable in the database
        """
        return []

    @staticmethod
    def pyodbc_rows_to_tuples(data: List[Any]) -> List[Tuple[Any, ...]]:
        """
        Convert pyodbc.Row objects from `fetch_data` to tuples.

        :param data: List of tuples or pyodbc.Row objects
        :return: List of tuples
        """
        if data and type(data[0]).__name__ == "Row":
            data = [tuple(row) for row in data]
        return data

    @staticmethod
    def mutate_db_for_connection_test(database: "Database") -> None:
        """
        Some databases require passing additional parameters for validating database
        connections. This method makes it possible to mutate the database instance prior
        to testing if a connection is ok.

        :param database: instance to be mutated
        """
        return None

    @staticmethod
    def get_extra_params(database: "Database") -> Dict[str, Any]:
        """
        Some databases require adding elements to connection parameters,
        like passing certificates to `extra`. This can be done here.

        :param database: database instance from which to extract extras
        :raises CertificateException: If certificate is not valid/unparseable
        """
        extra: Dict[str, Any] = {}
        if database.extra:
            try:
                extra = json.loads(database.extra)
            except json.JSONDecodeError as ex:
                logger.error(ex)
                raise ex
        return extra

    @classmethod
    def is_readonly_query(cls, parsed_query: ParsedQuery) -> bool:
        """Pessimistic readonly, 100% sure statement won't mutate anything"""
        return (parsed_query.is_select() or parsed_query.is_explain()
                or parsed_query.is_show())

    @classmethod
    def get_column_spec(
        cls,
        native_type: Optional[str],
        source: utils.ColumnTypeSource = utils.ColumnTypeSource.GET_TABLE,
        column_type_mappings: Tuple[Tuple[Pattern[str],
                                          Union[TypeEngine,
                                                Callable[[Match[str]],
                                                         TypeEngine]],
                                          GenericDataType, ],
                                    ..., ] = column_type_mappings,
    ) -> Union[ColumnSpec, None]:
        """
        Converts native database type to sqlalchemy column type.
        :param native_type: Native database typee
        :param source: Type coming from the database table or cursor description
        :return: ColumnSpec object
        """
        column_type = None

        if (cls.get_sqla_column_type(native_type,
                                     column_type_mappings=column_type_mappings)
                is not None):
            column_type, generic_type = cls.get_sqla_column_type(  # type: ignore
                native_type,
                column_type_mappings=column_type_mappings)
            is_dttm = generic_type == GenericDataType.TEMPORAL

        if column_type:
            return ColumnSpec(sqla_type=column_type,
                              generic_type=generic_type,
                              is_dttm=is_dttm)

        return None
示例#22
0
 def mixed_in_column(cls):
     return Column(types.Integer(),
                   primary_key=cls.__name__.endswith('Primary'))
示例#23
0
class Order(Model):
    __tablename__ = 'orders'
    _id = Column(types.Integer(), primary_key=True)
    status = Column(OrderStatus.db_type(), default=OrderStatus.pending)
    side = Column(OrderSide.db_type(), default=OrderSide.buy)
示例#24
0
 def foreign_id(cls):
     return Column(types.Integer(),
                   ForeignKey(MixedInTablePrimary.mixed_in_column),
                   primary_key=cls.__name__.endswith('Primary'))
示例#25
0
class BaseAutoGen(object):
    _id = Column(types.Integer(), primary_key=True)
示例#26
0
 def local_primary_key(cls):
     return Column(types.Integer(), primary_key=True)
示例#27
0
class AC(Model):
    a_id = Column(types.Integer(), ForeignKey('a._id'), primary_key=True)
    c_id = Column(types.Integer(), ForeignKey('c._id'), primary_key=True)
    key = Column(types.String())

    c = orm.relationship('C', lazy=False)
示例#28
0
class GeoLite2CityBlocksIpv4(Base, ModelDictMixin):
    """GeoLite2 City Blocks database model

    References:
        * `GeoIP2 City and Country CSV Databases <https://dev.maxmind.com/geoip/geoip2/geoip2-city-country-csv-databases/>`_

    Args:
        id (str):
            * The primary key
        network (str):
            * This is the IPv4 network in CIDR format such as “2.21.92.0/29”
        geoname_id (int):
            * A unique identifier for the network's location as specified by
              GeoNames. This ID can be used to look up the location
              information in the Location file.
        registered_country_geoname_id (int):
            * The registered country is the country in which the ISP has
              registered the network. This column contains a unique
              identifier for the network's registered country as specified
              by GeoNames. This ID can be used to look up the location
              information in the Location file.
        represented_country_geoname_id (int):
            * The represented country is the country which is represented by
              users of the IP address. For instance, the country represented
              by an overseas military base. This column contains a unique
              identifier for the network's registered country as specified
              by GeoNames. This ID can be used to look up the location
              information in the Location file.
        is_anonymous_proxy (boolean):
            * Deprecated. Please see our GeoIP2 Anonymous IP database to
              determine whether the IP address is used by an anonymizing
              service.
        is_satellite_provider (boolean):
            * Deprecated. Please see our GeoIP2 Anonymous IP database.
        postal_code (str):
            * A postal code close to the user's location. We return the first
              3 characters for Canadian postal codes. We return the
              first 2-4 characters (outward code) for postal codes in the
              United Kingdom.
        latitude (float):
            * The approximate latitude of the postal code, city, subdivision
              or country associated with the IP address.
        longitude (float):
            * The approximate longitude of the postal code, city, subdivision
              or country associated with the IP address.
        accuracy_radius (int):
            * The approximate accuracy radius, in kilometers, around the
              latitude and longitude for the geographical entity
              (country, subdivision, city or postal code) associated with
              the IP address. We have a 67% confidence that the location of
              the end-user falls within the area defined by the accuracy
              radius and the latitude and longitude coordinates.

    """  # noqa
    __tablename__ = "geolite2_city_blocks_ipv4"

    id = Column(types.String(16),
                index=True,
                primary_key=True,
                default=generate_uuid)

    network = Column(
        types.String(18),
        nullable=False,
    )

    geoname_id = Column(types.Integer())

    registered_country_geoname_id = Column(types.Integer())

    represented_country_geoname_id = Column(types.Integer())

    _is_anonymous_proxy = Column(types.Boolean())

    _is_satellite_provider = Column(types.Boolean())

    postal_code = Column(types.String(9))

    _latitude = Column(types.Float())

    _longitude = Column(types.Float())

    accuracy_radius = Column(types.Integer())

    @hybrid_property
    def latitude(self):
        return self._latitude

    @latitude.setter
    def latitude(self, value):
        value = value or float()
        self._latitude = float(value)

    @hybrid_property
    def longitude(self):
        return self._longitude

    @longitude.setter
    def longitude(self, value):
        value = value or float()
        self._longitude = float(value)

    @hybrid_property
    def is_anonymous_proxy(self):
        return self._is_anonymous_proxy

    @is_anonymous_proxy.setter
    def is_anonymous_proxy(self, value):
        self._is_anonymous_proxy = bool(int(value))

    @hybrid_property
    def is_satellite_provider(self):
        return self._is_satellite_provider

    @is_satellite_provider.setter
    def is_satellite_provider(self, value):
        self._is_satellite_provider = bool(int(value))

    def __repr__(self):
        return 'GeoLite2CityBlocksIpv4(id={!r})'.format(self.id)
示例#29
0
class SearchOne(Model):
    _id = Column(types.Integer(), primary_key=True)
    string = Column(types.String())
示例#30
0
class Entry(EntryJsonSerializer, BaseMixin, VersionMinxin):
    __table_args__ = {'mysql_charset': 'utf8', 'mysql_engine': 'InnoDB'}
    TagClass = None

    category_id = Column(Integer, nullable=False, index=True, doc=u'分类ID')
    author_id = Column(Integer, nullable=False, index=True, doc=u'作者ID')
    published_id = Column(Integer,
                          nullable=False,
                          index=True,
                          default=0,
                          doc=u'发布人ID')

    entry_type = Column(ChoiceType(ENTRY_TYPE_CHOICES, types.Integer()),
                        nullable=False,
                        default=EntryType.article,
                        index=True,
                        doc=u'类型')

    title = Column(String(200), nullable=False, doc=u'标题')
    # content = Column(Text, doc=u'内容')

    body = db.Column(db.Text)
    body_html = db.Column(db.Text)

    summary = Column(String(200), doc=u'摘要')

    tag_id_list = Column(DenormalizedText, doc=u'标签ID列表')
    tag_list = Column(DenormalizedText, doc=u'标签文本列表')

    logo = Column(String(200), doc=u'图标地址')

    thumbnail_id_list = db.Column(DenormalizedText,
                                  nullable=True,
                                  default=set(),
                                  doc=u'缩略图ID列表')

    thumbs_width = Column(Integer, nullable=False, default=256, doc=u'缩略图宽度')
    thumbs_height = Column(Integer, nullable=False, default=256, doc=u'缩略图高度')

    source_title = Column(String(200), doc=u'来源标题')
    source_url = Column(String(200), doc=u'来源地址')

    source_type = Column(ChoiceType(ENTRY_SOURCE_TYPE_CHOICES,
                                    types.Integer()),
                         nullable=False,
                         default=EntrySourceType.original,
                         doc=u'来源类型:0-原创、1-翻译、2-转帖、3-专稿')

    slug = Column(String(200), unique=True, index=True, doc=u'固定地址')

    recommend = Column(ChoiceType(ENTRY_RECOMMEND_CHOICES, types.Integer()),
                       nullable=False,
                       default=EntryRecommend.general,
                       doc=u'推荐级别:0-默认(未推荐)、1-不错、2-良好、3-精华')

    comment_status = Column(ChoiceType(ENTRY_COMMENT_STATUS_CHOICES,
                                       types.Integer()),
                            nullable=False,
                            default=EntryCommentStatus.open,
                            doc=u'评论状态:0-允许、1-关闭')
    view_status = Column(ChoiceType(ENTRY_VIEW_STATUS_CHOICES,
                                    types.Integer()),
                         nullable=False,
                         default=EntryViewStatus.open,
                         doc=u'显示状态:0-公开、1-私有、2-仅作者可见、3-隐藏')
    entry_status = Column(ChoiceType(ENTRY_STATUS_CHOICES, types.Integer()),
                          nullable=False,
                          default=EntryStatus.draft,
                          doc=u'内容状态:0-草稿、1-待审、2-已删除、3-发布、4-已接受')

    be_modified = Column(Integer, nullable=False, default=0, doc=u'被别人修改了')

    num_favorites = Column(Integer, nullable=False, default=0, doc=u'收藏数')
    num_retweet = Column(Integer, nullable=False, default=0, doc=u'转发数')
    num_views = Column(Integer, nullable=False, default=0, doc=u'阅读数')
    num_comments = Column(Integer, nullable=False, default=0, doc=u'评论/回复数')

    num_uninterested = Column(Integer, nullable=False, default=0, doc=u'不感兴趣数')

    # 置顶周期、推首页周期、
    #文章排序:(置顶周期)		标题样式:
    on_top = Column(Integer, nullable=False, default=0, doc=u'是否置顶')
    on_top_period = Column(Integer,
                           nullable=True,
                           default=14,
                           doc=u'置顶周期: 缺省2周')
    on_portal = Column(Integer, nullable=False, default=0, doc=u'是否首页显示')
    on_portal_period = Column(Integer,
                              nullable=True,
                              default=14,
                              doc=u'首页显示周期: 缺省2周')

    created_ip = Column(Integer, nullable=False, doc=u'创建时的IP')

    upward_time = Column(DateTime, nullable=False, doc=u'贴子互动/变更时间')
    published_time = Column(DateTime, doc=u'发布时间')

    ranking = Column(Integer,
                     nullable=False,
                     default=0,
                     index=True,
                     doc=u'热门度、权重')

    # 最后回复ID
    last_comment_id = Column(Integer, doc=u'最后回复ID')

    # 文档文件ID列表
    document_id_list = Column(DenormalizedText, default='[]', doc=u'文档文件ID列表')

    # 普通文件ID列表
    general_id_list = Column(DenormalizedText, default='[]', doc=u'普通文件ID列表')

    # 图片文件ID列表
    picture_id_list = Column(DenormalizedText, default='[]', doc=u'图片文件ID列表')

    @property
    def last_comment(self):
        return Comment.get_by_id(self.last_comment_id)

    @property
    def hot_support_comment(self):
        return Comment.get_hot_support_comment(self.id)

    @property
    def author(self):
        return UserService.get_brief_by_id(self.author_id)

    @property
    def author_name(self):
        return UserService.get_brief_by_id(self.author_id).nickname

    @property
    def category(self):
        print 'self.category_id: ', self.category_id
        return Category.get_by_id(self.category_id)

    @property
    def category_name(self):
        return Category.get_by_id(self.category_id).category_name

    @property
    def tags(self):
        tag_list = []

        for _id in self.tag_id_list:
            # todo
            tag_list.append(self.TagClass.get_by_id(_id))
        return tag_list

    @property
    def permissions(self):
        if g.user:
            return {
                'can_edit': self.author.id == g.user.id
                or g.user.is_supervisor,
                'can_del': self.author.id == g.user.id or g.user.is_supervisor
            }
        else:
            return {'can_edit': 0, 'can_del': 0}

    def __unicode__(self):
        return self.id

    def __repr__(self):
        return self.id

    @classmethod
    def get_by_id(cls, id_):
        #global simple_cache
        #key = 'entry_%d' % id
        #print key
        #if key in simple_cache:
        #    query = loads(simple_cache[key], scoped_session=db.session)
        #else:
        # todo cache
        return cls.query.get(int(id_))
        #serialized = dumps(query)
        #simple_cache[key] =  serialized
        # return query

    @staticmethod
    def get_entries_total():
        _total = Entry.query.filter(
            and_(Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open)).count()
        _pages = int(ceil(_total / float(PER_PAGE)))

        return _total, _pages

    @staticmethod
    def get_latest_entries_by_type(entry_type, page, size):
        return Entry.query.filter(
            and_(Entry.entry_type == entry_type,
                 Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open)).order_by(
                     '%s %s' % ('id', Order.DESC)).limit(size).offset(
                         size * (page - 1))

    @staticmethod
    def get_all_entries():
        return Entry.query.filter(
            and_(Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open)).order_by(
                     '%s %s' % ('id', Order.DESC)).all()

    @staticmethod
    def get_latest_entries(page, size):
        return Entry.query.filter(
            and_(Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open)).order_by(
                     '%s %s' % ('id', Order.DESC)).limit(size).offset(
                         size * (page - 1))

    @staticmethod
    def get_by_category(category_id, page, size):
        return Entry.query.filter(
            and_(Entry.on_portal == True,
                 Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open,
                 Entry.category_id == category_id)).order_by(
                     'on_top DESC, %s %s' %
                     ('upward_time', Order.DESC)).limit(size).offset(
                         size * (page - 1))

    @staticmethod
    def get_by_entry_type(entry_type, page, size):
        return Entry.query.filter(
            and_(Entry.on_portal == True,
                 Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open,
                 Entry.entry_type == entry_type)).order_by(
                     'on_top DESC, %s %s' %
                     ('upward_time', Order.DESC)).limit(size).offset(
                         size * (page - 1))

    @staticmethod
    def get_latest_portal_entries(page, size):
        return Entry.query.filter(
            and_(Entry.on_portal == True,
                 Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open)).order_by(
                     'on_top DESC, %s %s' %
                     ('upward_time', Order.DESC)).limit(size).offset(
                         size * (page - 1))

    @staticmethod
    def get_hot_entries(page, size):
        return Entry.query.filter(
            and_(Entry.entry_status == EntryStatus.published,
                 Entry.view_status == EntryViewStatus.open)).order_by(
                     '%s %s' %
                     ('num_comments', Order.DESC)).limit(size).offset(
                         size * (page - 1))

    @staticmethod
    def get_page_by_tag(tag, query, sort, order, page):
        q = Entry.query.join(TagEntryRelation,
                             TagEntryRelation.entry_id == Entry.id).filter(
                                 TagEntryRelation.tag_id == tag.id)
        if q is None:
            abort(404)

        _total = q.count()
        _list = q.order_by('-entry.id').limit(PER_PAGE).offset(
            PER_PAGE * (page - 1)).all()
        #_list = db.session.query(Entry).from_statement("SELECT * FROM entry WHERE category_id =:category_id").params(category_id=category.id).all()

        _pages = int(ceil(_total / float(PER_PAGE)))

        return _total, _pages, _list

    @classmethod
    def get_page_by_category(cls, category, tag, query, sort, order, page):
        # /栏目/search?q=mysql&catalog=7
        # /栏目/list?show=reply
        # /search?q=[python]+mysql+using+sqlalchemy
        # 查询规则:
        #
        # 根据 category.current_level 决定从Entry的哪一个category_id查询,一个3级
        #      category1_id、category2_id、category3_id、

        #q = None
        q = cls.query.filter_by(category_id=category)
        #if tag:
        #    if category.current_level == 1:
        #        q = Entry.query.join(TagEntryRelation, TagEntryRelation.entry_id == Entry.id).filter(
        #            and_(Entry.category1_id == category.id, TagEntryRelation.tag_id == tag.id))
        #
        #    if category.current_level == 2:
        #        q = Entry.query.join(TagEntryRelation, TagEntryRelation.entry_id == Entry.id).filter(
        #            and_(Entry.category2_id == category.id, TagEntryRelation.tag_id == tag.id))
        #
        #    if category.current_level == 3:
        #        q = Entry.query.join(TagEntryRelation, TagEntryRelation.entry_id == Entry.id).filter(
        #            and_(Entry.category3_id == category.id, TagEntryRelation.tag_id == tag.id))
        #else:
        #if category.current_level == 1:
        #    q = Entry.query.filter_by(category1_id=category.id)
        #
        #if category.current_level == 2:
        #    q = Entry.query.filter_by(category2_id=category.id)
        #
        #if category.current_level == 3:
        #    q = Entry.query.filter_by(category3_id=category.id)

        if q is None:
            abort(404)

        _total = q.count()
        #print '123:%s %s' % (sort, order)
        _list = q.order_by('%s %s' % (sort, order)).limit(PER_PAGE).offset(
            PER_PAGE * (page - 1)).all()
        #_list = db.session.query(Entry).from_statement("SELECT * FROM entry WHERE category_id =:category_id").params(category_id=category.id).all()

        _pages = int(ceil(_total / float(PER_PAGE)))

        entry_list = []
        for e in _list:
            entry_list.append(e.to_dict())

        return _total, _pages, entry_list

    @classmethod
    def get_page_by_category_id(cls,
                                category,
                                sort,
                                order,
                                page,
                                page_size=20):
        # /栏目/search?q=mysql&catalog=7
        # /栏目/list?show=reply
        # /search?q=[python]+mysql+using+sqlalchemy
        # 查询规则:
        #
        q = cls.query.filter_by(category_id=category)

        if q is None:
            abort(404)

        _total = q.count()

        _list = q.order_by('%s %s' % (sort, order)).limit(page_size).offset(
            page_size * (page - 1)).all()

        _pages = int(ceil(_total / float(PER_PAGE)))

        entry_list = []
        for e in _list:
            entry_list.append(e.to_dict())

        return _total, _pages, entry_list

    @classmethod
    def get_page_by_category_and_entryType(cls, category, tag, query, sort,
                                           order, page, entryType):
        # /栏目/search?q=mysql&catalog=7
        # /栏目/list?show=reply
        # /search?q=[python]+mysql+using+sqlalchemy
        # 查询规则:
        #
        # 根据 category.current_level 决定从Entry的哪一个category_id查询,一个3级
        #      category1_id、category2_id、category3_id、

        q = None

        if tag:
            if category.current_level == 1:
                q = Entry.query.join(
                    TagEntryRelation,
                    TagEntryRelation.entry_id == Entry.id).filter(
                        and_(Entry.category1_id == category.id,
                             TagEntryRelation.tag_id == tag.id))

            if category.current_level == 2:
                q = Entry.query.join(
                    TagEntryRelation,
                    TagEntryRelation.entry_id == Entry.id).filter(
                        and_(Entry.category2_id == category.id,
                             TagEntryRelation.tag_id == tag.id))

            if category.current_level == 3:
                q = Entry.query.join(
                    TagEntryRelation,
                    TagEntryRelation.entry_id == Entry.id).filter(
                        and_(Entry.category3_id == category.id,
                             TagEntryRelation.tag_id == tag.id))
        else:
            if category.current_level == 1:
                q = Entry.query.filter_by(category1_id=category.id,
                                          entry_type=entryType)

            if category.current_level == 2:
                q = Entry.query.filter_by(category2_id=category.id,
                                          entry_type=entryType)

            if category.current_level == 3:
                q = Entry.query.filter_by(category3_id=category.id,
                                          entry_type=entryType)

        if q is None:
            abort(404)

        _total = q.count()
        #print '123:%s %s' % (sort, order)
        _list = q.order_by('on_top DESC, %s %s' %
                           (sort, order)).limit(PER_PAGE).offset(PER_PAGE *
                                                                 (page - 1))
        #_list = db.session.query(Entry).from_statement("SELECT * FROM entry WHERE category_id =:category_id").params(category_id=category.id).all()

        _pages = int(ceil(_total / float(PER_PAGE)))

        return _total, _pages, _list

    @staticmethod
    def get_page_by_entryType(sort, order, page, entryType):
        # 根据类型获取文章列表

        q = None
        q = Entry.query.filter_by(entry_type=entryType)

        if q is None:
            abort(404)
        print "entrytype============================================================================="
        print q.count()
        print "entrytype============================================================================="
        _total = q.count()
        _list = q.order_by('on_top DESC, %s %s' %
                           (sort, order)).limit(PER_PAGE).offset(PER_PAGE *
                                                                 (page - 1))

        _pages = int(ceil(_total / float(PER_PAGE)))

        return _total, _pages, _list

    @staticmethod
    def get_entry_list_by_tag_id(tag_id,
                                 page=1,
                                 page_size=PER_PAGE,
                                 sort=None,
                                 order=None):
        q = Entry.query.join(TagEntryRelation,
                             TagEntryRelation.entry_id == Entry.id).filter(
                                 TagEntryRelation.tag_id == tag_id)

        _total = q.count()
        _list = q.order_by('-entry.id').limit(PER_PAGE).offset(PER_PAGE *
                                                               (page - 1))
        #_list = db.session.query(Entry).from_statement("SELECT * FROM entry WHERE category_id =:category_id").params(category_id=category.id).all()
        _pages = int(ceil(_total / float(PER_PAGE)))
        return _total, _pages, _list

    @staticmethod
    def get_page_by_user(user_id, tag, entry_type, query, sort, order, page):
        q = None

        if entry_type:
            q = Entry.query.filter(
                and_(Entry.author_id == user_id,
                     Entry.entry_type == entry_type))
        else:
            q = Entry.query.filter(and_(Entry.author_id == user_id))

        if q is None:
            abort(404)

        _total = q.count()
        _list = q.order_by('-entry.id').limit(PER_PAGE).offset(PER_PAGE *
                                                               (page - 1))

        _pages = int(ceil(_total / float(PER_PAGE)))

        return _total, _pages, _list

    @staticmethod
    def add_or_update(category, entry, is_draft, is_auto_save_img=False):
        # 保存数据

        is_new = False

        if entry.id is None:
            # 是新建的数据
            is_new = True
            # todo wqq:如果是管理员权限才能允许表单递交author_id
            #if not g.user.is_supervisor:
            #    entry.author_id = g.user.id
            entry.author_id = 1
            entry.created_ip = get_remote_ip()
            # entry.created_time = sys_now()
            # entry.updated_time = entry.created_time
            entry.upward_time = sys_now()
            entry.category_id = category.id
            entry.entry_type = category.entry_type

        #if is_auto_save_img:
        #    # 是否自动保存图片
        #    entry.content = auto_save_img(entry.content, app.config['SITE_DOMAIN'], PHOTOS_RELATIVE_PATH)

        # 只有管理员可以设置是否推首页、置顶
        #if not g.user.is_supervisor:
        #    entry.on_top = 0

        # todo 先默认是推到首页的,以后考虑可以配置
        entry.on_portal = 1

        if is_draft:
            entry.entry_status = EntryStatus.draft
        else:
            # 低权限的文章要审核
            #if category.need_review and (not g.user.is_supervisor):
            #print '低权限的文章要审核:', app.config['SAFE_POST_START_TIME'], app.config['SAFE_POST_END_TIME'], check_in_rank(app.config['SAFE_POST_START_TIME'], app.config['SAFE_POST_END_TIME'])

            #if (not g.user.is_editor) and (
            #    not check_in_rank(app.config['SAFE_POST_START_TIME'], app.config['SAFE_POST_END_TIME'])):
            #    # 需要审核
            #    entry.entry_status = EntryStatus.pending
            #else:
            #    entry.entry_status = EntryStatus.published
            #    entry.published_id = g.user.id
            #
            #    if not entry.published_time:
            #        entry.published_time = sys_now()
            #
            #if gfw.check(entry.content) or gfw.check(entry.title):
            #    # 需要审核
            #    entry.entry_status = EntryStatus.pending
            entry.entry_status = EntryStatus.pending

        # 处理摘要
        if not entry.summary:
            # 自动产生摘要
            entry.summary = extract_summary(entry.content)

        # 开始处理tags
        old_tags_list = []

        if not is_new:
            # old_tags_list = json_decode(entry.tags)
            entry.updated_time = sys_now()

        new_tags_list = request.form.getlist('m_tags')

        #entry.tags = json_encode(new_tags_list)

        if is_new:
            db.session.add(entry)
        db.session.flush()

        if entry.id is None:
            print '出错了'
            db.session.rollback()
            return False

        # # 要删除的标签
        # del_tags_list = [val for val in old_tags_list if val not in new_tags_list]
        #
        # # 要添加的标签
        # add_tags_list = [val for val in new_tags_list if val not in old_tags_list]
        #
        # if del_tags_list:
        #     # 删除 tag_entry_relation (标签的文章关联)
        #     TagEntryRelationService.del_relation(entry.id, del_tags_list)
        #
        #     # 更新 tag_category_relation (标签的分类计数)
        #     TagCategoryRelationService.del_relation(category, del_tags_list)
        #
        # if add_tags_list:
        #     # 添加 tag_entry_relation (标签的文章关联)
        #     TagEntryRelationService.add_relation(entry.id, add_tags_list)
        #
        #     # 标签内容数 + 1
        #     TagService.inc_entry_count(add_tags_list)
        #
        #     # 更新 tag_category_relation (标签的分类关联、计数)
        #     TagCategoryRelationService.add_relation(category, add_tags_list)

        if not entry.slug:
            # 文章URL自动生成规则
            # 文章标题: {title_name}
            # 文章ID: {title_id}
            # 栏目名: {category_name}
            # 栏目固定地址: {category_slug}
            # 时间戳: {timestamp}
            # 时间: {time}
            # 日期: {date}

            entry.slug = category.entry_url_rule.replace('{title_name}', '%s' % entry.title) \
                .replace('{title_id}', '%d' % entry.id) \
                .replace('{category_name}', '%s' % category.category_name) \
                .replace('{category_slug}', category.slug) \
                .replace('{timestamp}', '%s' % str(int(time()))) \
                .replace('{time}', format_time_with_path(int(time()))) \
                .replace('{date}', format_date_with_path(int(time()))).replace('//', '/')

            if entry.slug[0] == '/':
                entry.slug = entry.slug[1:]

        db.session.commit()

        #print '保存成功了'
        return True

    @staticmethod
    def inc_num_comments(entry_id, num):
        entry = Entry.get_by_id(entry_id)
        entry.num_comments = Entry.__table__.c.num_comments + num
        entry.ranking = entry.num_views + (10 * entry.num_useful) + (10 * entry.num_favorites) + (
            10 * entry.num_retweet) \
                        + (5 * entry.num_oppositions) + (7 * entry.num_comments) + (5 * entry.num_useless) + (
                            7 * entry.num_supports)

        db.session.commit()
        app.config['content_updated_time'] = sys_now()

    @staticmethod
    def calc_ranking(entry, ext_num=0):
        entry.ranking = entry.num_views + (10 * entry.num_useful) + (10 * entry.num_favorites) \
                        + (10 * entry.num_retweet) + (5 * entry.num_oppositions) + (7 * entry.num_comments) \
                        + (-5 * entry.num_useless) + (7 * entry.num_thanks) + (-7 * entry.num_uninterested) + ext_num

    @staticmethod
    def inc_num_views(entry_id, num):
        entry = Entry.get_by_id(entry_id)
        entry.num_views = Entry.__table__.c.num_views + num
        Entry.calc_ranking(entry)

        db.session.commit()

    @staticmethod
    def favorites(user_id, entry_id, title, tags, description):
        # 收藏
        # 取出,还是客户端传人?
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_favorites:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_favorites = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)

        if not entry:
            return False

        favorites_id = FavoritesService.add_favorites(user_id, entry_id,
                                                      entry.author_id, title,
                                                      tags, description,
                                                      entry.entry_type)

        if not favorites_id:
            return False

        entry.num_favorites = Entry.__table__.c.num_favorites + 1

        Entry.calc_ranking(entry, 8)
        db.session.commit()

        return True

    @staticmethod
    def useful(entry_id, user_id):
        # 有用数
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_useful:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_useful = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_useful = Entry.__table__.c.num_useful + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True

    @staticmethod
    def useless(entry_id, user_id):
        # 无用数
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_useless:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_useless = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_useless = Entry.__table__.c.num_useless + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True

    @staticmethod
    def supports(entry_id, user_id):
        # 支持
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_supports:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_supports = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_supports = Entry.__table__.c.num_supports + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True

    @staticmethod
    def oppositions(entry_id, user_id):
        # 反对
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_oppositions:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_oppositions = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_oppositions = Entry.__table__.c.num_oppositions + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True

    @staticmethod
    def scores(entry_id, user_id, scores):
        # 评分
        entry = Entry.get_by_id(entry_id)
        entry.scores = (Entry.__table__.c.scores + scores) / 2
        Entry.calc_ranking(entry + 8)
        db.session.commit()
        return True

    @staticmethod
    def difficulty(entry_id, user_id, difficulty):
        # 难易度
        entry = Entry.get_by_id(entry_id)
        entry.difficulty = (Entry.__table__.c.difficulty + difficulty) / 2
        Entry.calc_ranking(entry + 8)
        db.session.commit()
        return True

    @staticmethod
    def on_portal(entry_id, user_id, enable):
        # 推首页
        entry = Entry.get_by_id(entry_id)
        entry.on_portal = enable
        db.session.commit()
        return True

    @staticmethod
    def on_top(entry_id, user_id, enable):
        # 置顶
        entry = Entry.get_by_id(entry_id)
        entry.on_top = enable
        db.session.commit()
        return True

    @staticmethod
    def publish(entry_id, user_id):
        # 审核后发布
        entry = Entry.get_by_id(entry_id)
        entry.entry_status = EntryStatus.published
        db.session.commit()
        return True

    @staticmethod
    def hide(entry_id, user_id):
        # 隐藏
        entry = Entry.get_by_id(entry_id)
        entry.view_status = EntryViewStatus.hide
        db.session.commit()
        return True

    @staticmethod
    def open(entry_id, user_id):
        # 打开文章
        entry = Entry.get_by_id(entry_id)
        entry.view_status = EntryViewStatus.open
        db.session.commit()
        return True

    @staticmethod
    def close_comment(entry_id, user_id):
        # 关闭评论
        entry = Entry.get_by_id(entry_id)
        entry.comment_status = EntryCommentStatusType.close
        db.session.commit()
        return True

    @staticmethod
    def open_comment(entry_id, user_id):
        # 打开评论
        entry = Entry.get_by_id(entry_id)
        entry.comment_status = EntryCommentStatusType.open
        db.session.commit()
        return True

    @staticmethod
    def retweet(entry_id, user_id):
        # 转发次数
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_retweet:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_retweet = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_retweet = Entry.__table__.c.num_retweet + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True

    @staticmethod
    def complain(entry_id, user_id):
        """
        投诉
        :param entry_id:
        :param user_id:
        :return:
        """
        #todo
        return True

    @staticmethod
    def get_weekly_entries(category):
        # 获取7天内的内容

        q = None

        if category.current_level == 1:
            q = Entry.query.filter(
                and_(Entry.category1_id == category.id,
                     Entry.published_time >= day_before_str(sys_now(), 7)))

        if category.current_level == 2:
            q = Entry.query.filter(
                and_(Entry.category2_id == category.id,
                     Entry.published_time >= day_before_str(sys_now(), 7)))

        if category.current_level == 3:
            q = Entry.query.filter(
                and_(Entry.category3_id == category.id,
                     Entry.published_time >= day_before_str(sys_now(), 7)))

        if q is None:
            return []

        _list = q.order_by('-entry.ranking').limit(PER_PAGE)

        return _list

    @staticmethod
    def get_monthly_entries(category):
        # 获取30天内的内容

        q = None

        if category.current_level == 1:
            q = Entry.query.filter(
                and_(Entry.category1_id == category.id,
                     Entry.published_time >= day_before_str(sys_now(), 30)))

        if category.current_level == 2:
            q = Entry.query.filter(
                and_(Entry.category2_id == category.id,
                     Entry.published_time >= day_before_str(sys_now(), 30)))

        if category.current_level == 3:
            q = Entry.query.filter(
                and_(Entry.category3_id == category.id,
                     Entry.published_time >= day_before_str(sys_now(), 30)))

        if q is None:
            return []

        _list = q.order_by('-entry.ranking').limit(PER_PAGE)

        return _list

    @staticmethod
    def get_related_entries(entry_type):
        # todo 获取相关的内容
        #query = {'entry_type': entry_type}
        #return self.get_page(condition=query, sort='_id', order=Order.DESC)
        return []

    @staticmethod
    def get_statistic_by_author_id(author_id):
        statistic = range(len(entry_type_str))
        for i in range(len(entry_type_str)):
            statistic[i] = Entry.query.filter(
                and_(Entry.author_id == author_id,
                     Entry.entry_type == i)).count()

        return statistic

    @staticmethod
    def delete(entry):
        # todo 超过一定时间的也不让删除?

        count_entry = Comment.count_by_entry_id(entry.id)
        if count_entry > 0:
            # 软删除
            pass
        else:
            db.session.delete(entry)

        # 删除相关评论等相关数据
        Comment.del_by_entry_id(entry.id)

        # 分类的文章数减少
        # 只支持3级分类
        if entry.category.current_level == 1:
            Category.dec_entry_count(entry.category1_id)

        if entry.category.current_level == 2:
            Category.dec_entry_count(entry.category1_id)
            Category.dec_entry_count(entry.category2_id)

        if entry.category.current_level == 3:
            Category.dec_entry_count(entry.category1_id)
            Category.dec_entry_count(entry.category2_id)
            Category.dec_entry_count(entry.category3_id)

        # 要删除的标签
        del_tags_list = json_decode(entry.tags)

        if del_tags_list:
            # 删除 tag_entry_relation (标签的文章关联)
            TagEntryRelationService.del_relation(entry.id, del_tags_list)
            TagService.dec_entry_count(del_tags_list)

            # 更新 tag_category_relation (标签的分类计数)
            TagCategoryRelationService.del_relation(entry.category,
                                                    del_tags_list)

        db.session.delete(entry)
        db.session.commit()

        return True

    @staticmethod
    def modify_last_comment(entry_id, comment_id):
        entry = Entry.get_by_id(entry_id)
        entry.last_comment_id = comment_id
        entry.upward_time = sys_now()

        db.session.commit()

    @staticmethod
    def thanks(entry_id, user_id):
        # 感谢
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_thanks:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_thanks = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_thanks = Entry.__table__.c.num_thanks + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True

    @staticmethod
    def uninterested(entry_id, user_id):
        # 不感兴趣
        interact = EntryUserInteractService.get_by_entry_and_user_id(
            entry_id, user_id)
        if interact and interact.has_uninterested:
            return True

        if not interact:
            interact = EntryUserInteract()
            interact.user_id = user_id
            interact.entry_id = entry_id

        interact.has_uninterested = 1

        EntryUserInteractService.add_or_update(interact)

        entry = Entry.get_by_id(entry_id)
        entry.num_uninterested = Entry.__table__.c.num_uninterested + 1
        Entry.calc_ranking(entry)
        db.session.commit()
        return True