Exemplo n.º 1
0
 def testDoubleConnect(self):
     cnn = umysql.Connection()
     cnn.connect(DB_HOST, DB_PORT, DB_USER, DB_PASSWD, DB_DB)
     time.sleep(11)
     cnn.close()
     time.sleep(1)
     cnn = umysql.Connection()
     cnn.connect(DB_HOST, DB_PORT, DB_USER, DB_PASSWD, DB_DB)
Exemplo n.º 2
0
    def testBigInt(self):
        #Tests the behaviour of insert/select with bigint/long.

        BIGNUM = 112233445566778899

        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("drop table if exists tblbigint")
        cnn.query(
            "create table tblbigint (test_id int(11) DEFAULT NULL, test_bigint bigint DEFAULT NULL, test_bigint2 bigint DEFAULT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1"
        )
        cnn.query(
            "insert into tblbigint (test_id, test_bigint, test_bigint2) values (%s, "
            + str(BIGNUM) + ", %s)", (1, BIGNUM))
        cnn.query(
            u"insert into tblbigint (test_id, test_bigint, test_bigint2) values (%s, "
            + str(BIGNUM) + ", %s)", (2, BIGNUM))

        # Make sure both our inserts where correct (ie, the big number was not truncated/modified on insert)
        rs = cnn.query(
            "select test_id from tblbigint where test_bigint = test_bigint2")
        result = rs.rows
        self.assertEquals([(1, ), (2, )], result)

        # Make sure select gets the right values (ie, the big number was not truncated/modified when retrieved)
        rs = cnn.query(
            "select test_id, test_bigint, test_bigint2 from tblbigint where test_bigint = test_bigint2"
        )
        result = rs.rows
        self.assertEquals([(1, BIGNUM, BIGNUM), (2, BIGNUM, BIGNUM)], result)
        cnn.close()
Exemplo n.º 3
0
    def testSelectUnicode(self):
        s = u'r\xc3\xa4ksm\xc3\xb6rg\xc3\xa5s'

        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("truncate tbltest")
        cnn.query("insert into tbltest (test_id, test_string) values (%s, %s)",
                  (1, 'piet'))
        cnn.query("insert into tbltest (test_id, test_string) values (%s, %s)",
                  (2, s))
        cnn.query(
            u"insert into tbltest (test_id, test_string) values (%s, %s)",
            (3, s))

        rs = cnn.query("select test_id, test_string from tbltest")

        result = rs.rows
        self.assertEquals([(1, u'piet'), (2, s), (3, s)], result)

        #test that we can still cleanly roundtrip a blob, (it should not be encoded if we pass
        #it as 'str' argument), eventhough we pass the qry itself as unicode
        blob = ''.join([chr(i) for i in range(256)])

        cnn.query(u"insert into tbltest (test_id, test_blob) values (%s, %s)",
                  (4, blob))
        rs = cnn.query("select test_blob from tbltest where test_id = %s",
                       (4, ))
        b2 = rs.rows[0][0]
        self.assertEquals(str, type(b2))
        self.assertEquals(256, len(b2))
        self.assertEquals(blob, b2)
        cnn.close()
Exemplo n.º 4
0
    def testUtf8mb4(self):
        utf8mb4chr = u'\U0001f603'

        # We expected we can insert utf8mb4 character, than fetch it back
        cnn = umysql.Connection()
        cnn.connect (DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("drop table if exists tblutf8mb4")
        cnn.query("create table tblutf8mb4 (test_text TEXT DEFAULT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4")

        cnn.query("insert into tblutf8mb4 (test_text) values ('" + utf8mb4chr + "')")
        cnn.query("set names utf8mb4")
        cnn.query("insert into tblutf8mb4 (test_text) values ('" + utf8mb4chr + "')")

        rs = cnn.query("select test_text from tblutf8mb4;")
        result = rs.rows
        self.assertNotEquals(result[0][0], utf8mb4chr)
        self.assertEquals(result[1][0], utf8mb4chr)

        cnn.query("set names utf8")
        rs = cnn.query("select test_text from tblutf8mb4;")
        result = rs.rows
        self.assertNotEquals(result[1][0], utf8mb4chr)

        cnn.close()
Exemplo n.º 5
0
    def testDateTime(self):
        # Tests the behaviour of insert/select with mysql/DATETIME <-> python/datetime.datetime

        d_date = datetime.datetime(2010, 02, 11, 13, 37, 42)
        d_string = "2010-02-11 13:37:42"

        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("drop table if exists tbldate")
        cnn.query(
            "create table tbldate (test_id int(11) DEFAULT NULL, test_date datetime DEFAULT NULL, test_date2 datetime DEFAULT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1"
        )

        cnn.query(
            "insert into tbldate (test_id, test_date, test_date2) values (%s, '"
            + d_string + "', %s)", (1, d_date))

        # Make sure our insert was correct
        rs = cnn.query(
            "select test_id from tbldate where test_date = test_date2")
        result = rs.rows
        self.assertEquals([(1, )], result)

        # Make sure select gets the right value back
        rs = cnn.query(
            "select test_id, test_date, test_date2 from tbldate where test_date = test_date2"
        )
        result = rs.rows
        self.assertEquals([(1, d_date, d_date)], result)
        cnn.close()
Exemplo n.º 6
0
    def testMySQLDBAPI(self):

        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("truncate tbltest")

        for i in range(10):
            cnn.query(
                "insert into tbltest (test_id, test_string) values (%d, 'test%d')"
                % (i, i))

        rs = cnn.query("select test_id, test_string from tbltest")

        self.assertEquals((0, 'test0'), rs.rows[0])

        #check that fetchall gets the remainder
        self.assertEquals([(1, 'test1'), (2, 'test2'), (3, 'test3'),
                           (4, 'test4'), (5, 'test5'), (6, 'test6'),
                           (7, 'test7'), (8, 'test8'), (9, 'test9')],
                          rs.rows[1:])

        #another query on the same cursor should work
        rs = cnn.query("select test_id, test_string from tbltest")

        #fetch some but not all
        self.assertEquals((0, 'test0'), rs.rows[0])
        self.assertEquals((1, 'test1'), rs.rows[1])
        self.assertEquals((2, 'test2'), rs.rows[2])

        #this should not work, cursor was closed
        cnn.close()
Exemplo n.º 7
0
    def testTextCharsets(self):
        aumlaut_unicode = u"\u00e4"
        aumlaut_utf8 = "\xc3\xa4"
        aumlaut_latin1 = "\xe4"

        cnn = umysql.Connection()
        cnn.connect (DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("drop table if exists tblutf")
        cnn.query("create table tblutf (test_mode TEXT DEFAULT NULL, test_utf TEXT DEFAULT NULL, test_latin1 TEXT) ENGINE=MyISAM DEFAULT CHARSET=utf8")

        # We insert the same character using two different encodings
        cnn.query("set names utf8")
        cnn.query("insert into tblutf (test_mode, test_utf, test_latin1) values ('utf8', _utf8'" + aumlaut_utf8 + "', _latin1'" + aumlaut_latin1 + "')")
        
        cnn.query("set names latin1")
        cnn.query("insert into tblutf (test_mode, test_utf, test_latin1) values ('latin1', _utf8'" + aumlaut_utf8 + "', _latin1'" + aumlaut_latin1 + "')")

        # We expect the driver to always give us unicode strings back
        expected = [(u"utf8", aumlaut_unicode, aumlaut_unicode), (u"latin1", aumlaut_unicode, aumlaut_unicode)]

        # Fetch and test with different charsets
        for charset in ("latin1", "utf8", "cp1250"):
            cnn.query("set names " + charset)
            rs = cnn.query("select test_mode, test_utf, test_latin1 from tblutf")
            result = rs.rows
            self.assertEquals(result, expected)

        cnn.close()
Exemplo n.º 8
0
    def testLargePackets(self):
        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)
        cnn.query("truncate tbltest")

        c = 16 * 1024

        blob = '0123456789'
        while 1:
            cnn.query(
                "insert into tbltest (test_id, test_blob) values (%d, '%s')" %
                (len(blob), blob))
            if len(blob) > (c * 2): break
            blob = blob * 2

        rs = cnn.query("select test_id, test_blob from tbltest")
        for row in rs.rows:
            self.assertEquals(row[0], len(row[1]))
            #self.assertEquals(blob[:row[0]], row[1])

        #reread, second time, oversize packet is already present
        rs = cnn.query("select test_id, test_blob from tbltest")
        for row in rs.rows:
            self.assertEquals(row[0], len(row[1]))
            self.assertEquals(blob[:row[0]], row[1])

        cnn.close()
Exemplo n.º 9
0
    def testMySQLClient(self):
        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        rs = cnn.query("select 1")
        self.assertEqual([(1, )], rs.rows)
        cnn.close()
Exemplo n.º 10
0
    def testConnectWithWrongDB(self):
        cnn = umysql.Connection()

        try:
            cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, "DBNOTFOUND")
        except umysql.SQLError, e:
            # 1049 = ER_BAD_DB_ERROR
            self.assertEquals(e[0], 1049)
Exemplo n.º 11
0
def mysql(response):
    c = umysql.Connection()
    c.connect("127.0.0.1", 3306, "root", "mysql", "mysql")
    rs = c.query("SELECT Host FROM user WHERE User = '******'")
    response["mysql"] = []
    for h in rs.rows:
        response["mysql"].append(h[0])
    c.close()
Exemplo n.º 12
0
 def __init__(self, host, port, user, pwd, db=''):
     self.host = host
     self.port = port
     self.user = user
     self.pwd = pwd
     self.db = db
     self.cn = umysql.Connection()
     self.connect()
Exemplo n.º 13
0
    def testConnectWithWrongDB(self):
        cnn = umysql.Connection()

        try:
            cnn.connect (DB_HOST, 3306, DB_USER, DB_PASSWD, "DBNOTFOUND")
        except umysql.SQLError, e:
            # 1044 = "Access denfied for user to database"
            self.assertEquals(e[0], 1044)
Exemplo n.º 14
0
    def testConnectAutoCommitOff(self):
        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, "", False)

        rs = cnn.query("select 1")

        self.assertEqual([(1, )], rs.rows)
        cnn.close()
Exemplo n.º 15
0
 def __init__(self, *args, **kwargs):
     if 'cursorclass' not in kwargs:
         kwargs['cursorclass'] = Cursor
     if 'conv' not in kwargs:
         kwargs['conv'] = decoders
     if 'charset' not in kwargs:
         kwargs['charset'] = 'utf8'
     self._umysql_conn = umysql.Connection()
     super(Connection, self).__init__(*args, **kwargs)
Exemplo n.º 16
0
    def testConnectFails(self):
        cnn = umysql.Connection()

        try:
            cnn.connect(DB_HOST, 31337, DB_USER, DB_PASSWD, DB_DB)
            assert False, "Expected exception"
        except (socket.error):
            pass
        cnn.close()
Exemplo n.º 17
0
def mysql_exec(response):
    db = umysql.Connection()
    db.connect("127.0.0.1", 3306, "root", "mysql", "mysql")
    rs = db.query("SELECT Host FROM user WHERE User = '******' LIMIT 1")
    res = []
    for h in rs.rows:
        res.append(h[0])
    db.close()
    return res
Exemplo n.º 18
0
    def testConnectDNSFails(self):
        cnn = umysql.Connection()

        try:
            cnn.connect("thisplaceisnowere", 31337, DB_USER, DB_PASSWD, DB_DB)
            assert False, "Expected exception"
        except (socket.error):
            pass
        cnn.close()
Exemplo n.º 19
0
 def testConnectTwice(self):
     cnn = umysql.Connection()
     cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)
     try:
         cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)
         assert False, "Expected exception"
     except:
         pass
     pass
     cnn.close()
Exemplo n.º 20
0
    def testAutoInc(self):

        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("truncate tblautoincint")

        cnn.query("ALTER TABLE tblautoincint AUTO_INCREMENT = 100")
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincint (test_string) values (%s)", ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(100, lastrowid)
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincint (test_string) values (%s)", ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(101, lastrowid)

        cnn.query("ALTER TABLE tblautoincint AUTO_INCREMENT = 4294967294")
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincint (test_string) values (%s)", ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(4294967294, lastrowid)
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincint (test_string) values (%s)", ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(4294967295, lastrowid)

        cnn.query("truncate tblautoincbigint")

        cnn.query("ALTER TABLE tblautoincbigint AUTO_INCREMENT = 100")
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincbigint (test_string) values (%s)",
            ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(100, lastrowid)
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincbigint (test_string) values (%s)",
            ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(101, lastrowid)

        cnn.query(
            "ALTER TABLE tblautoincbigint AUTO_INCREMENT = 18446744073709551614"
        )
        rowcount, lastrowid = cnn.query(
            "insert into tblautoincbigint (test_string) values (%s)",
            ('piet', ))
        self.assertEqual(1, rowcount)
        self.assertEqual(18446744073709551614, lastrowid)
        #this fails on mysql, but that is a mysql problem
        #cur.execute("insert into tblautoincbigint (test_string) values (%s)", ('piet',))
        #self.assertEqual(1, cur.rowcount)
        #self.assertEqual(18446744073709551615, cur.lastrowid)

        cnn.close()
Exemplo n.º 21
0
 def __init__(self,
              host,
              user,
              passwd,
              db,
              port=3306,
              autocommit=True,
              charset='utf8'):
     self.args = (host, port, user, passwd, db, autocommit, charset)
     self.conn = umysql.Connection()
     self.conn.connect(*self.args)
Exemplo n.º 22
0
 def reconnect(self, delay):
     while True:
         self.conn.close()
         self.conn = umysql.Connection()
         try:
             print 'Trying reconnect..'
             self.conn.connect(*self.args)
             print 'Reconneced.'
             break
         except:
             print sys.exc_info()
         gevent.sleep(delay)
Exemplo n.º 23
0
    def testConnectCloseQuery(self):
        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)
        self.assertEquals(True, cnn.is_connected())
        cnn.close()
        self.assertEquals(False, cnn.is_connected())

        try:
            cnn.query("SELECT 1")
            assert False, "Expected exception"
        except (RuntimeError):
            pass
        cnn.close()
Exemplo n.º 24
0
    def testPercentEscaping(self):
        cnn = umysql.Connection()
        cnn.connect (DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)
        rs = cnn.query("SELECT * FROM `tblautoincint` WHERE `test_id` LIKE '%%10%%'")
        self.assertEquals([(100, u'piet'), (101, u'piet')], rs.rows)

        rs = cnn.query("SELECT * FROM `tblautoincint` WHERE `test_id` LIKE '%%%s%%'", [10])
        self.assertEquals([(100, u'piet'), (101, u'piet')], rs.rows)

        # SqlAlchemy query style
        rs = cnn.query("SELECT * FROM `tblautoincint` WHERE `test_id` LIKE concat(concat('%%', %s), '%%')", [10])
        self.assertEquals([(100, u'piet'), (101, 'piet')], rs.rows)

        cnn.close()
Exemplo n.º 25
0
 def reconnect(self):
     """Closes the existing database connection and re-opens it."""
     print 'reconnecting MySQL ...'
     self.close()
     self._db = umysql.Connection()
     self._db.connect(
         self._db_args['host'],
         self._db_args['port'],
         self._db_args['user'],
         self._db_args['password'],
         self._db_args['db'],
         self._db_args['autocommit'],
         self._db_args['charset'],
     )
Exemplo n.º 26
0
        def wrapper(*args, **kwargs):
            mysqlconn = umysql.Connection()
            mysqlconn.settimeout(5)
            mysqlconn.connect(_conf.host, _conf.port, _conf.user, _conf.passwd,
                              _conf.db, True, 'utf8')
            try:
                rs = mysqlconn.query(sql, {})
            except umysql.Error as e:
                on_sql_error(e)

            data = handle_sql_result(rs)
            kwargs["data"] = data
            result = fn(*args, **kwargs)
            mysqlconn.close()
            return result
Exemplo n.º 27
0
 def testUnsignedInt(self):
     cnn = umysql.Connection()
     cnn.connect(DB_HOST, DB_PORT, DB_USER, DB_PASSWD, DB_DB)
     cnn.query('DROP TABLE IF EXISTS tblunsignedint')
     cnn.query('''CREATE TABLE tblunsignedint(
         `big` BIGINT UNSIGNED NOT NULL,
         `int` INT UNSIGNED NOT NULL,
         `medium` MEDIUMINT UNSIGNED NOT NULL,
         `short` SMALLINT UNSIGNED NOT NULL,
         `tiny` TINYINT UNSIGNED NOT NULL
     )''')
     values1 = (
         0xffffffffffffffffL,
         0xffffffff,
         0xffffff,
         0xffff,
         0xff,
     )
     values2 = (
         0x8000000000000000L,
         0x80000000,
         0x800000,
         0x8000,
         0x80,
     )
     values3 = (
         0x8fedcba098765432L,
         0x8fedcba0,
         0x8fedcb,
         0x8fed,
         0x8f,
     )
     rc, rid = cnn.query(
         'INSERT INTO `tblunsignedint` VALUES(%s, %s, %s, %s, %s)', values1)
     self.assertEqual(rc, 1)
     rc, rid = cnn.query(
         'INSERT INTO `tblunsignedint` VALUES(%s, %s, %s, %s, %s)', values2)
     self.assertEqual(rc, 1)
     rc, rid = cnn.query(
         'INSERT INTO `tblunsignedint` VALUES(%s, %s, %s, %s, %s)', values3)
     self.assertEqual(rc, 1)
     rs = cnn.query('SELECT * FROM `tblunsignedint`')
     self.assertEquals([
         values1,
         values2,
         values3,
     ], rs.rows)
     cnn.close()
    def con(self):
        if self.db is not None:
            self.db.close()

        db = sql.Connection()

        server = self.getParams.findParam('addr').getValue()
        port = int(self.getParams.findParam('port').getValue())
        user = self.getParams.findParam('user').getValue()
        password = self.getParams.findParam('password').getValue()
        database = self.getParams.findParam('database').getValue()

        #Connection
        db.connect(server, port, user, password, database)

        self.db = db
Exemplo n.º 29
0
    def testTimestamp(self):
        ts = datetime.datetime(2013, 4, 26, 9, 53, 48)
        ts_val = ts.strftime("%Y-%m-%d %H:%M:%S")
        drop = 'drop table if exists tbltimestamp'
        create = 'create table tbltimestamp (idx int not null, ts timestamp)'
        insert = 'insert into tbltimestamp (idx, ts) values (%s, %s)'
        select = 'select idx, ts from tbltimestamp where idx = %s'
        idx = 1

        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)
        cnn.query(drop)
        cnn.query(create)
        cnn.query(insert, (idx, ts_val,))
        result = cnn.query(select, (idx,))
        self.assertEqual(result.rows[0], (idx, ts))
Exemplo n.º 30
0
    def testEscapeArgs(self):
        cnn = umysql.Connection()
        cnn.connect(DB_HOST, 3306, DB_USER, DB_PASSWD, DB_DB)

        cnn.query("truncate tbltest")

        cnn.query("insert into tbltest (test_id, test_string) values (%s, %s)",
                  (1, 'piet'))
        cnn.query("insert into tbltest (test_id, test_string) values (%s, %s)",
                  (2, 'klaas'))
        cnn.query("insert into tbltest (test_id, test_string) values (%s, %s)",
                  (3, "pi'et"))

        #classic sql injection, would return all rows if no proper escaping is done
        rs = cnn.query(
            "select test_id, test_string from tbltest where test_string = %s",
            ("piet' OR 'a' = 'a", ))
        self.assertEquals([], rs.rows)  #assert no rows are found

        #but we should still be able to find the piet with the apostrophe in its name
        rs = cnn.query(
            "select test_id, test_string from tbltest where test_string = %s",
            ("pi'et", ))
        self.assertEquals([(3, "pi'et")], rs.rows)

        #also we should be able to insert and retrieve blob/string with all possible bytes transparently
        chars = ''.join([chr(i) for i in range(256)])

        cnn.query(
            "insert into tbltest (test_id, test_string, test_blob) values (%s, %s, %s)",
            (4, chars[:80], chars))
        #cnn.query("insert into tbltest (test_id, test_blob) values (%s, %s)", (4, chars))

        rs = cnn.query(
            "select test_blob, test_string from tbltest where test_id = %s",
            (4, ))
        #self.assertEquals([(chars, chars)], cur.fetchall())
        b, s = rs.rows[0]

        #test blob
        self.assertEquals(256, len(b))
        self.assertEquals(chars, b)

        self.assertEquals(80, len(s))
        self.assertEquals(chars[:80], s)

        cnn.close()