Exemplo n.º 1
0
    def test_default_connection_thread_local(self):
        """
        Ensure that the default connection (i.e. djangocg.db.connection) is
        different for each thread.
        Refs #17258.
        """
        connections_set = set()
        connection.cursor()
        connections_set.add(connection.connection)

        def runner():
            from djangocg.db import connection

            connection.cursor()
            connections_set.add(connection.connection)

        for x in range(2):
            t = threading.Thread(target=runner)
            t.start()
            t.join()
        self.assertEqual(len(connections_set), 3)
        # Finish by closing the connections opened by the other threads (the
        # connection opened in the main thread will automatically be closed on
        # teardown).
        for conn in connections_set:
            if conn != connection.connection:
                conn.close()
Exemplo n.º 2
0
 def test_loaddata_error_message(self):
     """
     Verifies that loading a fixture which contains an invalid object
     outputs an error message which contains the pk of the object
     that triggered the error.
     """
     # MySQL needs a little prodding to reject invalid data.
     # This won't affect other tests because the database connection
     # is closed at the end of each test.
     if connection.vendor == "mysql":
         connection.cursor().execute("SET sql_mode = 'TRADITIONAL'")
     with self.assertRaisesRegexp(IntegrityError, "Could not load fixtures.Article\(pk=1\): .*$"):
         management.call_command("loaddata", "invalid.json", verbosity=0, commit=False)
Exemplo n.º 3
0
    def test_signal(self):
        data = {}

        def receiver(sender, connection, **kwargs):
            data["connection"] = connection

        connection_created.connect(receiver)
        connection.close()
        cursor = connection.cursor()
        self.assertTrue(data["connection"].connection is connection.connection)

        connection_created.disconnect(receiver)
        data.clear()
        cursor = connection.cursor()
        self.assertTrue(data == {})
Exemplo n.º 4
0
 def test_django_table_names(self):
     cursor = connection.cursor()
     cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
     tl = connection.introspection.django_table_names()
     cursor.execute("DROP TABLE django_ixn_test_table;")
     self.assertTrue('django_ixn_testcase_table' not in tl,
                  "django_table_names() returned a non-Django table")
Exemplo n.º 5
0
 def test_cursor_var(self):
     # If the backend is Oracle, test that we can pass cursor variables
     # as query parameters.
     cursor = connection.cursor()
     var = cursor.var(backend.Database.STRING)
     cursor.execute("BEGIN %s := 'X'; END; ", [var])
     self.assertEqual(var.getvalue(), "X")
Exemplo n.º 6
0
 def test_get_table_description_nullable(self):
     cursor = connection.cursor()
     desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
     self.assertEqual(
         [r[6] for r in desc],
         [False, False, False, False, True]
     )
Exemplo n.º 7
0
 def test_parameter_escaping(self):
     # 13648: '%s' escaping support for sqlite3
     cursor = connection.cursor()
     response = cursor.execute("select strftime('%%s', date('now'))").fetchall()[0][0]
     self.assertNotEqual(response, None)
     # response should be an non-zero integer
     self.assertTrue(int(response))
Exemplo n.º 8
0
 def create_squares_with_executemany(self, args):
     cursor = connection.cursor()
     opts = models.Square._meta
     tbl = connection.introspection.table_name_converter(opts.db_table)
     f1 = connection.ops.quote_name(opts.get_field("root").column)
     f2 = connection.ops.quote_name(opts.get_field("square").column)
     query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (tbl, f1, f2)
     cursor.executemany(query, args)
Exemplo n.º 9
0
 def test_get_indexes_multicol(self):
     """
     Test that multicolumn indexes are not included in the introspection
     results.
     """
     cursor = connection.cursor()
     indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
     self.assertNotIn('first_name', indexes)
     self.assertIn('id', indexes)
Exemplo n.º 10
0
 def test_order_of_nls_parameters(self):
     # an 'almost right' datetime should work with configured
     # NLS parameters as per #18465.
     c = connection.cursor()
     query = "select 1 from dual where '1936-12-29 00:00' < sysdate"
     # Test that the query succeeds without errors - pre #18465 this
     # wasn't the case.
     c.execute(query)
     self.assertEqual(c.fetchone()[0], 1)
Exemplo n.º 11
0
 def test_bad_parameter_count(self):
     "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)"
     cursor = connection.cursor()
     query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
         connection.introspection.table_name_converter("backends_square"),
         connection.ops.quote_name("root"),
         connection.ops.quote_name("square"),
     )
     self.assertRaises(Exception, cursor.executemany, query, [(1, 2, 3)])
     self.assertRaises(Exception, cursor.executemany, query, [(1,)])
Exemplo n.º 12
0
    def test_django_table_names_retval_type(self):
        # Ticket #15216
        cursor = connection.cursor()
        cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')

        tl = connection.introspection.django_table_names(only_existing=True)
        self.assertIs(type(tl), list)

        tl = connection.introspection.django_table_names(only_existing=False)
        self.assertIs(type(tl), list)
Exemplo n.º 13
0
    def test_get_relations(self):
        cursor = connection.cursor()
        relations = connection.introspection.get_relations(cursor, Article._meta.db_table)

        # Older versions of MySQL don't have the chops to report on this stuff,
        # so just skip it if no relations come back. If they do, though, we
        # should test that the response is correct.
        if relations:
            # That's {field_index: (field_index_other_table, other_table)}
            self.assertEqual(relations, {3: (0, Reporter._meta.db_table)})
Exemplo n.º 14
0
 def reuse_cursor_ref():
     """
     Fetch a cursor, perform an query, rollback to close the transaction,
     then write a record (in a new transaction) using the same cursor object
     (reference). All this under commit_on_success, so the second insert should
     be committed.
     """
     cursor = connection.cursor()
     cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
     transaction.rollback()
     cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
Exemplo n.º 15
0
 def test_long_string(self):
     # If the backend is Oracle, test that we can save a text longer
     # than 4000 chars and read it properly
     c = connection.cursor()
     c.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
     long_str = "".join([six.text_type(x) for x in xrange(4000)])
     c.execute("INSERT INTO ltext VALUES (%s)", [long_str])
     c.execute("SELECT text FROM ltext")
     row = c.fetchone()
     self.assertEqual(long_str, row[0].read())
     c.execute("DROP TABLE ltext")
Exemplo n.º 16
0
 def test_get_table_description_types(self):
     cursor = connection.cursor()
     desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
     self.assertEqual(
         [datatype(r[1], r) for r in desc],
         ['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
     )
     # Check also length of CharFields
     self.assertEqual(
         [r[3] for r in desc if datatype(r[1], r) == 'CharField'],
         [30, 30, 75]
     )
Exemplo n.º 17
0
    def test_sequence_name_length_limits_flush(self):
        """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901"""
        # A full flush is expensive to the full test, so we dig into the
        # internals to generate the likely offending SQL and run it manually

        # Some convenience aliases
        VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
        VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
        tables = [VLM._meta.db_table, VLM_m2m._meta.db_table]
        sequences = [{"column": VLM._meta.pk.column, "table": VLM._meta.db_table}]
        cursor = connection.cursor()
        for statement in connection.ops.sql_flush(no_style(), tables, sequences):
            cursor.execute(statement)
Exemplo n.º 18
0
 def test_bad_sql(self):
     """
     Regression for #11900: If a block wrapped by commit_on_success
     writes a transaction that can't be committed, that transaction should
     be rolled back. The bug is only visible using the psycopg2 backend,
     though the fix is generally a good idea.
     """
     with self.assertRaises(IntegrityError):
         with transaction.commit_on_success():
             cursor = connection.cursor()
             cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');")
             transaction.set_dirty()
     transaction.rollback()
Exemplo n.º 19
0
    def test_generic_relation(self):
        "Sequence names are correct when resetting generic relations (Ref #13941)"
        # Create an object with a manually specified PK
        models.Post.objects.create(id=10, name="1st post", text="hello world")

        # Reset the sequences for the database
        cursor = connection.cursor()
        commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [models.Post])
        for sql in commands:
            cursor.execute(sql)

        # If we create a new object now, it should have a PK greater
        # than the PK we specified manually.
        obj = models.Post.objects.create(name="New post", text="goodbye world")
        self.assertTrue(obj.pk > 10)
Exemplo n.º 20
0
 def test_unicode_fetches(self):
     # 6254: fetchone, fetchmany, fetchall return strings as unicode objects
     qn = connection.ops.quote_name
     models.Person(first_name="John", last_name="Doe").save()
     models.Person(first_name="Jane", last_name="Doe").save()
     models.Person(first_name="Mary", last_name="Agnelline").save()
     models.Person(first_name="Peter", last_name="Parker").save()
     models.Person(first_name="Clark", last_name="Kent").save()
     opts2 = models.Person._meta
     f3, f4 = opts2.get_field("first_name"), opts2.get_field("last_name")
     query2 = "SELECT %s, %s FROM %s ORDER BY %s" % (
         qn(f3.column),
         qn(f4.column),
         connection.introspection.table_name_converter(opts2.db_table),
         qn(f3.column),
     )
     cursor = connection.cursor()
     cursor.execute(query2)
     self.assertEqual(cursor.fetchone(), ("Clark", "Kent"))
     self.assertEqual(list(cursor.fetchmany(2)), [("Jane", "Doe"), ("John", "Doe")])
     self.assertEqual(list(cursor.fetchall()), [("Mary", "Agnelline"), ("Peter", "Parker")])
Exemplo n.º 21
0
 def test_postgresql_real_type(self):
     cursor = connection.cursor()
     cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
     desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
     cursor.execute('DROP TABLE django_ixn_real_test_table;')
     self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
Exemplo n.º 22
0
 def test_client_encoding(self):
     # If the backend is Oracle, test that the client encoding is set
     # correctly.  This was broken under Cygwin prior to r14781.
     connection.cursor()  # Ensure the connection is initialized.
     self.assertEqual(connection.connection.encoding, "UTF-8")
     self.assertEqual(connection.connection.nencoding, "UTF-8")
Exemplo n.º 23
0
        def runner():
            from djangocg.db import connection

            connection.cursor()
            connections_set.add(connection.connection)
Exemplo n.º 24
0
 def test_get_key_columns(self):
     cursor = connection.cursor()
     key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
     self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
Exemplo n.º 25
0
 def test_get_primary_key_column(self):
     cursor = connection.cursor()
     primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
     self.assertEqual(primary_key_column, 'id')
Exemplo n.º 26
0
 def test_duplicate_table_error(self):
     """ Test that creating an existing table returns a DatabaseError """
     cursor = connection.cursor()
     query = "CREATE TABLE %s (id INTEGER);" % models.Article._meta.db_table
     with self.assertRaises(DatabaseError):
         cursor.execute(query)
Exemplo n.º 27
0
 def test_get_indexes(self):
     cursor = connection.cursor()
     indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
     self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
Exemplo n.º 28
0
 def test_get_table_description_names(self):
     cursor = connection.cursor()
     desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
     self.assertEqual([r[0] for r in desc],
                      [f.column for f in Reporter._meta.fields])
Exemplo n.º 29
0
 def raw_sql():
     "Write a record using raw sql under a commit_on_success decorator"
     cursor = connection.cursor()
     cursor.execute("INSERT into transactions_regress_mod (id,fld) values (17,18)")
Exemplo n.º 30
0
 def test_dbms_session(self):
     # If the backend is Oracle, test that we can call a standard
     # stored procedure through our cursor wrapper.
     convert_unicode = backend.convert_unicode
     cursor = connection.cursor()
     cursor.callproc(convert_unicode("DBMS_SESSION.SET_IDENTIFIER"), [convert_unicode("_django_testing!")])