• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

georgia-tech-db / eva / cf748690-046a-4f45-983b-b5ca63416eda

pending completion
cf748690-046a-4f45-983b-b5ca63416eda

Pull #582

circle-ci

jarulraj
checkpoint
Pull Request #582: server: asyncio refactoring

150 of 150 new or added lines in 7 files covered. (100.0%)

7887 of 8618 relevant lines covered (91.52%)

0.92 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.31
/eva/catalog/models/base_model.py
1
# coding=utf-8
2
# Copyright 2018-2022 EVA
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
from sqlalchemy import Column, Integer
1✔
16
from sqlalchemy.exc import SQLAlchemyError
1✔
17
from sqlalchemy.ext.declarative import declarative_base
1✔
18
from sqlalchemy_utils import create_database, database_exists, drop_database
1✔
19

20
from eva.catalog.sql_config import SQLConfig
1✔
21
from eva.utils.logging_manager import logger
1✔
22

23
db_session = SQLConfig().session
1✔
24

25

26
class CustomModel:
1✔
27
    """This overrides the default `_declarative_constructor` constructor.
28

29
    It skips the attributes that are not present for the model, thus if a
30
    dict is passed with some unknown attributes for the model on creation,
31
    it won't complain for `unkwnown field`s.
32
    Declares and int `_row_id` field for all tables
33
    """
34

35
    query = db_session.query_property()
1✔
36
    _row_id = Column("_row_id", Integer, primary_key=True)
1✔
37

38
    def __init__(self, **kwargs):
1✔
39
        cls_ = type(self)
1✔
40
        for k in kwargs:
1✔
41
            if hasattr(cls_, k):
×
42
                setattr(self, k, kwargs[k])
×
43
            else:
44
                continue
×
45

46
    def save(self):
1✔
47
        """Add and commit
48

49
        Returns: saved object
50

51
        """
52
        try:
1✔
53
            db_session.add(self)
1✔
54
            self._commit()
1✔
55
        except Exception as e:
×
56
            db_session.rollback()
×
57
            logger.error("Object already exists in database")
×
58
            raise e
×
59
        return self
1✔
60

61
    def update(self, **kwargs):
1✔
62
        """Update and commit
63

64
        Args:
65
            **kwargs: attributes to update
66

67
        Returns: updated object
68

69
        """
70
        try:
1✔
71
            for attr, value in kwargs.items():
1✔
72
                if hasattr(self, attr):
1✔
73
                    setattr(self, attr, value)
1✔
74
            return self.save()
1✔
75
        except Exception as e:
×
76
            db_session.rollback()
×
77
            logger.error("Failed to update the database object")
×
78
            raise e
×
79

80
    def delete(self):
1✔
81
        """Delete and commit"""
82
        try:
1✔
83
            db_session.delete(self)
1✔
84
            self._commit()
1✔
85
        except Exception:
×
86
            db_session.rollback()
×
87
            logger.error("Object couldn't be deleted")
×
88
            raise Exception
×
89

90
    def _commit(self):
1✔
91
        """Try to commit. If an error is raised, the session is rollbacked."""
92
        try:
1✔
93
            db_session.commit()
1✔
94
        except SQLAlchemyError:
×
95
            db_session.rollback()
×
96
            logger.error("Exception occurred while committing to database.")
×
97
            raise Exception("Exception occurred while committing to database.")
×
98

99

100
# Custom Base Model to be inherited by all models
101
BaseModel = declarative_base(cls=CustomModel, constructor=None, bind=SQLConfig().engine)
1✔
102

103

104
def init_db():
1✔
105
    """Create database if doesn't exist and create all tables."""
106
    engine = SQLConfig().engine
1✔
107
    if not database_exists(engine.url):
1✔
108
        logger.info("Database does not exist, creating database.")
1✔
109
        create_database(engine.url)
1✔
110
        logger.info("Creating tables")
1✔
111
        BaseModel.metadata.create_all()
1✔
112

113

114
def drop_db():
1✔
115
    """Drop all of the record from tables and the tables themselves. Drop the
116
    database as well."""
117
    engine = SQLConfig().engine
1✔
118
    if database_exists(engine.url):
1✔
119
        db_session.commit()
1✔
120
        BaseModel.metadata.drop_all()
1✔
121
        drop_database(engine.url)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc