예제 #1
0
 def test_custom_test_name(self):
     # A regular test db name is set.
     test_name = 'hodor'
     test_connection = get_connection_copy()
     test_connection.settings_dict['TEST'] = {'NAME': test_name}
     signature = BaseDatabaseCreation(test_connection).test_db_signature()
     self.assertEqual(signature[3], test_name)
예제 #2
0
 def test_custom_test_name_with_test_prefix(self):
     # A test db name prefixed with TEST_DATABASE_PREFIX is set.
     test_name = TEST_DATABASE_PREFIX + 'hodor'
     test_connection = get_connection_copy()
     test_connection.settings_dict['TEST'] = {'NAME': test_name}
     signature = BaseDatabaseCreation(test_connection).test_db_signature()
     self.assertEqual(signature[3], test_name)
예제 #3
0
 def test_mark_expected_failures_and_skips(self):
     test_connection = get_connection_copy()
     creation = BaseDatabaseCreation(test_connection)
     creation.connection.features.django_test_expected_failures = {
         'backends.base.test_creation.expected_failure_test_function',
     }
     creation.connection.features.django_test_skips = {
         'skip test class': {
             'backends.base.test_creation.SkipTestClass',
         },
         'skip test function': {
             'backends.base.test_creation.skip_test_function',
         },
     }
     creation.mark_expected_failures_and_skips()
     self.assertIs(
         expected_failure_test_function.__unittest_expecting_failure__,
         True,
     )
     self.assertIs(SkipTestClass.__unittest_skip__, True)
     self.assertEqual(
         SkipTestClass.__unittest_skip_why__,
         'skip test class',
     )
     self.assertIs(skip_test_function.__unittest_skip__, True)
     self.assertEqual(
         skip_test_function.__unittest_skip_why__,
         'skip test function',
     )
예제 #4
0
    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

        options = self.settings_dict.get('OPTIONS', None)

        if options:
            self.encoding = options.get('encoding', 'utf-8')

            # make lookup operators to be collation-sensitive if needed
            self.collation = options.get('collation', None)
            if self.collation:
                self.operators = dict(self.__class__.operators)
                ops = {}
                for op in self.operators:
                    sql = self.operators[op]
                    if sql.startswith('LIKE '):
                        ops[op] = '%s COLLATE %s' % (sql, self.collation)
                self.operators.update(ops)

        self.test_create = self.settings_dict.get('TEST_CREATE', True)

        self.features = DatabaseFeatures(self)
        self.ops = DatabaseOperations(self)
        self.introspection = DatabaseIntrospection(self)
        self.validation = BaseDatabaseValidation(self)
        self.creation = BaseDatabaseCreation(self)

        self.connection = None
예제 #5
0
 def test_default_name(self):
     # A test db name isn't set.
     prod_name = 'hodor'
     test_connection = get_connection_copy()
     test_connection.settings_dict['NAME'] = prod_name
     test_connection.settings_dict['TEST'] = {'NAME': None}
     signature = BaseDatabaseCreation(test_connection).test_db_signature()
     self.assertEqual(signature[3], TEST_DATABASE_PREFIX + prod_name)
예제 #6
0
    def test_monkey_patch_test_db(self, mock_method):
        monkey_patch_test_db()

        creation = BaseDatabaseCreation(None)
        creation.create_test_db()
        creation.destroy_test_db('foo_db')

        mock_method.assert_called_once_with(None)
예제 #7
0
 def _digest(self, *args):
     """
     Use django.db.backends.creation.BaseDatabaseCreation._digest
     to create index name in Django style. An evil hack :(
     """
     if not hasattr(self, '_django_db_creation'):
         self._django_db_creation = BaseDatabaseCreation(self._get_connection())
     return self._django_db_creation._digest(*args)
예제 #8
0
def create_table(model):
    u'''创建 model 所需的表'''
    from django.db import connection  # 获取数据库连接
    from django.core.management.color import no_style  # Style是用来输出语句时着色的,没什么用
    from django.db.backends.base.creation import BaseDatabaseCreation  # 这个类就是用来生成SQL语句的。
    c = BaseDatabaseCreation(connection)
    create_sql = c.sql_create_model(model(), no_style())[0][0]  # 生成建表的SQL语句
    #print create_sql
    cursor = connection.cursor()
    cursor.execute(create_sql)  # 执行SQL
예제 #9
0
파일: sites.py 프로젝트: elyshow/Aron-ETL
    def createTable(toTable, db, app_label = '', fields = None):
        """
        :param toTable:  表名
        :param db: 数据库名
        :param app_label: model所属app
        :param fields: [{field:字段名,cnname:字段注释,length:字段长度},{}]
        :return:
        """
        getAllToTableField = FieldTable.objects.filter(tableenglish=toTable)
        toTable = toTable.upper()
        class Meta:
           # print(app_label)
            #db_table = toTable
            pass
            #db_tablespace =
        if app_label:
            setattr(Meta, 'app_label', app_label)
            setattr(Meta, 'db_table', toTable+ '_' + app_label)
            # setattr(Meta, 'db_tablespace', app_label)
        else:
            print('app_label is not exits')
            return

        attr = {'__module__' : app_label + '.models', 'Meta': Meta}
        for num in range(len(getAllToTableField)):
            #if getAllToTableField[num].isPreKey == 1:
              #  attr[getAllToTableField[num].fieldenglish] = models.CharField(max_length=getAllToTableField[num].fieldlength,
               #                                                             primary_key=True, verbose_name = getAllToTableField[num].cnname)
                #attr['primary'] = (getAllToTableField[num].identifier)
            #else:
            if getAllToTableField[num].showtype == 'string' or getAllToTableField[num].showtype == 'date' or \
                            getAllToTableField[num].showtype == 'datetime':
                attr[getAllToTableField[num].fieldenglish] = models.CharField(
                    max_length=getAllToTableField[num].fieldlength, blank=True, null=True, verbose_name = getAllToTableField[num].fieldchinese)
            elif getAllToTableField[num].showtype == 'numeric':
                attr[getAllToTableField[num].fieldenglish] = models.IntegerField(blank=True, null=True, verbose_name = getAllToTableField[num].fieldchinese)
            elif getAllToTableField[num].showtype == 'binary':
                attr[getAllToTableField[num].fieldenglish] = models.BinaryField(blank=True, null=True, verbose_name = getAllToTableField[num].fieldchinese)
        if not fields is None:
            fields = json.loads(fields)
            for i in range(len(fields)):
                attr[fields[i]['field']] = models.CharField(max_length= fields[i]['length'] , blank= True, null= True, verbose_name= fields[i]['cnname'])
        classModel = type(toTable, (models.Model, ), attr)
        #classObject = type(classModel)
        from django.db import connections
        from django.db.backends.base.creation import BaseDatabaseCreation
        from django.core.management.color import no_style
        creation = BaseDatabaseCreation(connections[db])
        # print(creation)
        create_sql = creation.sql_create_model(classModel, no_style())[0]
        # print(create_sql)
        return classModel, create_sql
예제 #10
0
파일: django_db.py 프로젝트: wayxin/text
def create_table(model, connection=connection, transaction=transaction):
    '''
    @summary: 创建 model 所对应的表
    @param {django.db.models.Model} model: 生成表的 model 类
    @param connection: 数据库连接(有传则使用传来的,没有则用默认的,便于使用事务)
    @param transaction: 数据库连接的事务(有传则使用传来的,没有则用默认的)
    @raise : 执行有异常时抛出 RuntimeError 异常
    @return {string}: 建表语句
    '''
    c = BaseDatabaseCreation(connection)
    create_sql = c.sql_create_model(model(), no_style())[0][0]  # 生成建表的SQL语句
    execute_sql(create_sql, connection=connection,
                transaction=transaction)  # 执行SQL
    return create_sql
예제 #11
0
def create_table(model, connection=connection, transaction=transaction):
    """
    创建 model 所对应的表
    :param {django.db.models.Model} model: 生成表的 model 类
    :param connection: 数据库连接(有传则使用传来的,没有则用默认的,便于使用事务)
    :param transaction: 数据库连接的事务(有传则使用传来的,没有则用默认的)
    @raise : 执行有异常时抛出 RuntimeError 异常
    :return {string}: 建表语句
    """
    c = BaseDatabaseCreation(connection)
    create_sql = c.sql_create_model(model(), no_style())[0][0]  # 生成建表的SQL语句
    try:
        execute_sql(create_sql, connection=connection,
                    transaction=transaction)  # 执行SQL
    except:
        pass  # 可能表已存在
    return create_sql