Esempio n. 1
0
 def test_select_with_greater_equal_item_id(self):
     '''Test select with condtion: itemid >= 20'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     condition = "itemid >= 20"
     R1 = Table.select(R, condition)
     for row in R1.table:
         self.assertGreaterEqual(row['itemid'], 20)
Esempio n. 2
0
 def test_select_with_not_equal_item_id(self):
     '''Test select with condtion: itemid != 14'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     condition = "itemid != 14"
     R1 = Table.select(R, condition)
     for row in R1.table:
         self.assertNotEqual(row['itemid'], 14)
Esempio n. 3
0
    def __init__(self, applicationWindow):
        """
		@type applicationWindow: MainApplicationWindow
		"""
        self.applicationWindow = applicationWindow
        self.tableTab = applicationWindow.mainWindow.tableTab
        self.table = Table("", None)
        # Set this to True when programmatically manipulating the columns table
        # to prevent GUI events from causing sync issues with our columns
        self.lockCellChanges = False

        self.previousState = None

        mainWindow = applicationWindow.mainWindow
        mainWindow.addColumnButton.clicked.connect(self.addNewRow)
        mainWindow.removeColumnButton.clicked.connect(
            self.removeCurrentColumnRow)
        mainWindow.moveColumnDownButton.clicked.connect(
            self.moveCurrentColumnDown)
        mainWindow.moveColumnUpButton.clicked.connect(self.moveCurrentColumnUp)
        mainWindow.discardTableButton.clicked.connect(self.discardChanges)
        mainWindow.saveTableButton.clicked.connect(self.saveChanges)
        mainWindow.tableName.textEdited.connect(self.nameEdited)
        mainWindow.tableInfoTable.itemSelectionChanged.connect(
            self.selectedColumnChanged)
Esempio n. 4
0
 def test_select_with_equal_pricerange(self):
     '''Test select with condtion: pricerange = 'moderate'
     '''
     R = Table.inputfromfile('test_csv/sales1.csv')
     condition = "pricerange = 'moderate'"
     R1 = Table.select(R, condition)
     for row in R1.table:
         self.assertEquals(row['pricerange'], 'moderate')
Esempio n. 5
0
 def test_join_with_same_customerid(self):
     """Test join wtih condition: R.customerid = S.C"""
     R = Table.inputfromfile('test_csv/sales1.csv')
     S = Table.inputfromfile('test_csv/sales2.csv')
     R1 = Table.join(R, S, 'R', 'S', 'R.customerid=S.C')
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertIsNotNone(row['R_customerid'], row['S_C'])
         self.assertEqual(row['R_customerid'], row['S_C'])
Esempio n. 6
0
 def test_select_with_multiple_condition(self):
     '''Test select with condtion: itemid >= 20 and pricerange == 'moderate'
     '''
     R = Table.inputfromfile('test_csv/sales1.csv')
     condition = "(itemid >= 20) and (pricerange == 'moderate')"
     R1 = Table.select(R, condition)
     for row in R1.table:
         self.assertGreaterEqual(row['itemid'], 20)
         self.assertEquals(row['pricerange'], 'moderate')
Esempio n. 7
0
 def test_join_with_greater(self):
     '''Test join wtih condition: R.qty > S.Q'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     S = Table.inputfromfile('test_csv/sales2.csv')
     R1 = Table.join(R, S, 'R', 'S', 'R.qty >S.Q')
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertIsNotNone(row['R_qty'], row['S_Q'])
         self.assertGreater(row['R_qty'], row['S_Q'])
Esempio n. 8
0
 def test_sort_with_single_column_Nan(self):
     """Test table with: sort(R, pricerange)"""
     R = Table.inputfromfile('test_csv/sales1.csv')
     R = Table.sort(R, ['pricerange'])
     self.assertIsNotNone(R.table)
     cur = R.table[0]['pricerange']
     for row in R.table:
         self.assertGreaterEqual(row['pricerange'], cur)
         cur = row['pricerange']
Esempio n. 9
0
 def test_join_with_same_princerage(self):
     '''Test join wtih condition: R.pricerange = S.P'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     S = Table.inputfromfile('test_csv/sales2.csv')
     R1 = Table.join(R, S, 'R', 'S', 'R.pricerange = S.P')
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertIsNotNone(row['R_pricerange'], row['S_P'])
         self.assertEqual(row['R_pricerange'], row['S_P'])
Esempio n. 10
0
 def test_join_with_multiple_condtion(self):
     '''Test join wtih condition: (R.qty >= S.Q) and (R.pricerange = S.P)'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     S = Table.inputfromfile('test_csv/sales2.csv')
     R1 = Table.join(R, S, 'R', 'S', '(R.qty >= S.Q) and (R.pricerange = S.P)')
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertIsNotNone(row['R_qty'], row['S_Q'])
         self.assertGreaterEqual(row['R_qty'], row['S_Q'])
         self.assertIsNotNone(row['R_pricerange'], row['S_P'])
         self.assertEqual(row['R_pricerange'], row['S_P'])
Esempio n. 11
0
 def test_sum_with_sales_1_and_column_saleid(self):
     '''Test sum with: sum(saleid)'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     R1 = Table.sum(R, 'saleid')
     self.assertIsNotNone(R1.table)
     sum = 0
     for row in R.table:
         sum = sum + row['saleid']
     for row in R1.table:
         self.assertIsNotNone(row['sum(saleid)'])
         self.assertEqual(row['sum(saleid)'], sum)
Esempio n. 12
0
 def test_hash(self):
     """Test building hash index on column: saleid"""
     self.R = Table.inputfromfile('test_csv/sales1.csv')
     Table.Hash(self.R, 'saleid')
     self.assertIsNotNone(self.R.index)
     self.assertIsNotNone(self.R.index['saleid'])
     test_index = self.R.index['saleid']
     self.assertEqual([0], test_index[36])
     self.assertEqual([1], test_index[784])
     self.assertEqual([2], test_index[801])
     self.assertEqual([3], test_index[905])
Esempio n. 13
0
 def test_avg_with_sales_1_and_column_saleid(self):
     '''Test avg with: avg(saleid)'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     R1 = Table.avg(R, 'saleid')
     self.assertIsNotNone(R1.table)
     sum = 0
     for row in R.table:
         sum = sum + row['saleid']
     avg = sum / len(R.table)
     for row in R1.table:
         self.assertIsNotNone(row['avg(saleid)'])
         self.assertEqual(row['avg(saleid)'], avg)
Esempio n. 14
0
 def test_Btree_with_pricerange(self):
     """Test building Btree index on column: pricerange"""
     R = Table.inputfromfile('test_csv/sales1.csv')
     Table.Btree(R, 'pricerange')
     self.assertIsNotNone(R.index)
     self.assertIsNotNone(R.index['pricerange'])
     test_index = R.index['pricerange']
     self.assertEqual([0, 1], test_index.get('moderate'))
     self.assertEqual([2, 3, 5, 6, 7, 10, 11], test_index.get('outrageous'))
     self.assertEqual([4], test_index.get('supercheap'))
     self.assertEqual([9], test_index.get('cheap'))
     self.assertEqual([8], test_index.get('expensive'))
Esempio n. 15
0
 def test_join_column_name(self):
     '''Test join wtih the output column name'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     S = Table.inputfromfile('test_csv/sales2.csv')
     R1 = Table.join(R, S, 'R1', 'S1', 'True')
     self.assertIsNotNone(R1.table)
     keyset = R1.table[0].keys()
     for key in R.table[0].keys():
         new_key = 'R1_{}'.format(key)
         self.assertTrue(new_key in keyset)
     for key in S.table[0].keys():
         new_key = 'S1_{}'.format(key)
         self.assertTrue(new_key in keyset)
Esempio n. 16
0
 def test_project_with_sales_1_and_column_saleid_itemid(self):
     '''Test projection with two columns'''
     R = Table.inputfromfile('test_csv/sales1.csv')
     R1 = Table.projection(R, ['saleid', 'itemid'])
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertIsNotNone(row['saleid'])
         self.assertIsNotNone(row['itemid'])
         self.assertRaises(KeyError, lambda: row['customerid'])
         self.assertRaises(KeyError, lambda: row['storeid'])
         self.assertRaises(KeyError, lambda: row['time'])
         self.assertRaises(KeyError, lambda: row['qty'])
         self.assertRaises(KeyError, lambda: row['pricerange'])
Esempio n. 17
0
 def test_sort_with_mulitple_columns(self):
     """Test table with: sort(R, salesid, storeid)"""
     R = Table.inputfromfile('test_csv/sales1.csv')
     R = Table.sort(R, ['saleid', 'storeid'])
     self.assertIsNotNone(R.table)
     saleid = R.table[0]['saleid']
     storeid = R.table[0]['storeid']
     for row in R.table:
         self.assertGreaterEqual(row['saleid'], saleid)
         if (row['saleid'] == saleid):
             self.assertGreaterEqual(row['storeid'], storeid)
         saleid = row['saleid']
         storeid = row['storeid']
 def test_select_with_equal_id(self):
     '''Test select with condtion: saleid = 36'''
     R = Table.inputfromfile('sales1')
     condition = 'saleid = 36'
     R1 = Table.select(R,condition)
     self.assertIsNotNone(R1.table[0])
     self.assertEqual(R1.table[0]['saleid'],36)
     self.assertEqual(R1.table[0]['itemid'],14)
     self.assertEqual(R1.table[0]['customerid'],2)
     self.assertEqual(R1.table[0]['storeid'],38)
     self.assertEqual(R1.table[0]['time'],49)
     self.assertEqual(R1.table[0]['qty'],15)
     self.assertEqual(R1.table[0]['pricerange'],'moderate')
     self.assertEqual(len(R1.table),1)
Esempio n. 19
0
 def test_concate(self):
     """Test table with: concat(R,R)"""
     R = Table.inputfromfile('test_csv/sales1.csv')
     R1 = Table.concat(R, R)
     self.assertIsNotNone(R1.table)
     index_R1 = 0
     index_R = 0
     while index_R1 < len(R1.table):
         if index_R < len(R.table):
             self.assertEqual(R1.table[index_R1], R.table[index_R])
             index_R = index_R + 1
             index_R1 = index_R1 + 1
         else:
             index_R = 0
Esempio n. 20
0
def db_test():
    print 'create database with capacity 100000 test is started..\n'
    open(os.getcwd() + '/storage/student.txt', 'wb').close()
    open(os.getcwd() + '/times.txt', 'wb').close()
    db = Table(filename=os.getcwd() + '/storage/student.txt',
               type=student,
               index_attrs=['name'],
               key_sizes=[26])
    # studs = get_shuffled_dataset()

    print('loading dataset')
    studs = get_shuffled_million()
    i = 0
    for stud in studs[:10000]:
        with Profiler() as p:
            db.put(stud.get_key(), stud)
            i += 1
            if i % 50 == 0:
                print('#', i)
    db.b_index()
    for index in db.index_attrs:
        tree = db.trees[index]
    # print(db.get('581200', 1))
    # print(db.trees['name']['Matthew Cervantes'])
    db.save()
Esempio n. 21
0
 def test_select_with_equal_id(self):
     '''Test select with condtion: saleid = 36'''
     self.R = Table.inputfromfile('test_csv/sales1.csv')
     condition = 'saleid = 36'
     self.R1 = Table.select(self.R, condition)
     self.assertIsNotNone(self.R1.table[0])
     expected = {
         'saleid': 36,
         'itemid': 14,
         'customerid': 2,
         'storeid': 38,
         'time': 49,
         'qty': 15,
         'pricerange': 'moderate'
     }
     self.assertEqual(self.R1.table[0], expected)
     self.assertEqual(len(self.R1.table), 1)
Esempio n. 22
0
 def test_join_with_index(self):
     """
     Test Join operation with index
     """
     R = Table.inputfromfile('test_csv/real_sales1.csv')
     S = Table.inputfromfile('test_csv/real_sales1.csv')
     start = time.time()
     R1 = Table.join(R, S, 'R', 'S', 'R.pricerange = S.pricerange')
     end = time.time()
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertEqual(row['R_pricerange'], row['S_pricerange'])
     without_index = end - start
     Table.Hash(R, 'pricerange')
     Table.Hash(S, 'pricerange')
     start = time.time()
     R1 = Table.join(R, S, 'R', 'S', 'R.pricerange = S.pricerange')
     end = time.time()
     with_index = end - start
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertEqual(row['R_pricerange'], row['S_pricerange'])
     self.assertLess(with_index, without_index*0.9)
     start = time.time()
     R1 = Table.join(R, S, 'R', 'S', 'S.pricerange = R.pricerange')
     end = time.time()
     with_index = end - start
     self.assertIsNotNone(R1.table)
     for row in R1.table:
         self.assertEqual(row['R_pricerange'], row['S_pricerange'])
     self.assertLess(with_index, without_index*0.9)
Esempio n. 23
0
def db_load_test():
    print 'load test is started..\n'
    db = Table(type=student, from_dump=True)
    # print student(db.get('581200', 1)).attrs
    print 'test get student with id = 581200..\n'
    print(student(to_parse=db.get('581200', 1)))
    print 'test neighbours of Matthew Cervantes..\n'
    nbrs = db.neighbours('name', 'Matthew Cervantes', 10)
    for nbr in nbrs:
        print nbr.attrs
    print 'test update Matthew Cervantes to Kamil..\n'
    print(student(to_parse=db.get('581200', 1)).attrs)
    db.update('581200', 1, {'name': 'Kamil'})
    print(student(to_parse=db.get('581200', 1)).attrs)
    print 'test remove Kamil by his id..\n'
    db.remove('581200', 1)
    if db.get('581200', 1) == None:
        print('Kamil is removed!')
Esempio n. 24
0
 def test_select_with_index_btree(self):
     """Test select with btree index on column pricerage"""
     R = Table.inputfromfile('test_csv/real_sales1.csv')
     condition = "pricerange = 'cheap'"
     start = time.time()
     for i in range(10):
         R1 = Table.select(R, condition)
     end = time.time()
     without_index = end - start
     Table.Btree(R, 'pricerange')
     start = time.time()
     for i in range(10):
         R1 = Table.select(R, condition)
     end = time.time()
     with_index = end - start
     for row in R1.table:
         self.assertEqual(row['pricerange'], 'cheap')
     self.assertLess(with_index, without_index / 5)
Esempio n. 25
0
 def test_countgroup(self):
     """
     Test countgroup
     """
     R = Table.inputfromfile('test_csv/real_sales1.csv')
     expect = Table.inputfromfile('test_csv/count_saleid_groupby_pricerange.csv')
     R1 = Table.countgroup(R, ['pricerange'])
     expect = Table.sort(expect, ['pricerange'])
     R1 = Table.sort(R1, ['pricerange'])
     self.assertEqual(len(R1.table), len(expect.table))
     for i in range(len(R1.table)):
         self.assertEqual(R1.table[i], expect.table[i])
     R = Table.inputfromfile('test_csv/real_sales1.csv')
     expect = Table.inputfromfile('test_csv/count_saleid_groupby_pricerange_customerid.csv')
     R1 = Table.countgroup(R, ['pricerange', 'customerid'])
     expect = Table.sort(expect, ['pricerange', 'customerid'])
     R1 = Table.sort(R1, ['pricerange', 'customerid'])
     self.assertEqual(len(R1.table), len(expect.table))
     for i in range(len(R1.table)):
         self.assertEqual(R1.table[i], expect.table[i])
Esempio n. 26
0
 def test_avggroup(self):
     """
     Test avggroup
     """
     R = Table.inputfromfile('test_csv/real_sales1.csv')
     expect = Table.inputfromfile('test_csv/avg_qty_groupby_princerange.csv')
     R1 = Table.avggroup(R, ['qty', 'pricerange'])
     expect = Table.sort(expect, ['pricerange'])
     R1 = Table.sort(R1, ['pricerange'])
     self.assertEqual(len(R1.table), len(expect.table))
     for i in range(len(R1.table)):
         self.assertAlmostEqual(R1.table[i]['avg(qty)'], expect.table[i]['avg(qty)'], places=4)
     R = Table.inputfromfile('test_csv/real_sales1.csv')
     expect = Table.inputfromfile('test_csv/avg_qty_groupby_customerid_princerange.csv')
     R1 = Table.avggroup(R, ['qty', 'pricerange', 'customerid'])
     expect = Table.sort(expect, ['pricerange', 'customerid'])
     R1 = Table.sort(R1, ['pricerange', 'customerid'])
     self.assertEqual(len(R1.table), len(expect.table))
     for i in range(len(R1.table)):
         self.assertAlmostEqual(R1.table[i]['avg(qty)'], expect.table[i]['avg(qty)'], places=4)
Esempio n. 27
0
def db_pair_test():
    print 'create database with capacity 100000 test is started..\n'
    open(os.getcwd() + '/storage/student.txt', 'wb').close()
    db = Table(filename=os.getcwd() + '/storage/student.txt',
               type=student,
               index_attrs=['name'],
               key_sizes=[26])
    # studs = get_shuffled_dataset()

    print('loading dataset')
    pairs = []
    size = 1000
    for i in range(size):
        p = pair(id=i, id1=i, id2=i)
        pairs.append(p)
    i = 0
    for p in pairs:
        with Profiler() as p:
            db.put(p.get_key(), p)
            i += 1
            if i % 50 == 0:
                print('#', i)
    # print(db.get('581200', 1))
    # print(db.trees['name']['Matthew Cervantes'])
    db.save()
Esempio n. 28
0
def db_pair_test():
    print 'create database with capacity 100000 test is started..\n'
    open(os.getcwd() + '/storage/student.txt', 'wb').close()
    db = Table(filename=os.getcwd() + '/storage/student.txt', type=student, index_attrs=['name'], key_sizes=[26])
    # studs = get_shuffled_dataset()

    print('loading dataset')
    pairs = []
    size = 1000
    for i in range(size):
        p = pair(id = i, id1 = i, id2 = i)
        pairs.append(p)
    i = 0
    for p in pairs:
        with Profiler() as p:
            db.put(p.get_key(), p)
            i += 1
            if i % 50 == 0:
                print('#', i)
    # print(db.get('581200', 1))
    # print(db.trees['name']['Matthew Cervantes'])
    db.save()
Esempio n. 29
0
def cursor_test():
    from database.cursor import cursor

    db = Table(type=student, from_dump=True)
    c = cursor(db=db, filename=db.filename)
    # c = select_cursor(db=db,filename=db.filename, on_field='name', greater_than=None, less_than="B")
    # c = project_cursor(db=db,filename=db.filename, fields=['name', 'email'], ordered_on='name')
    c = select_cursor(filename=db.filename,
                      on_field='name',
                      greater_than='G',
                      less_than='K',
                      on_cursor=c)
    while c.has_next():
        print c.next()
Esempio n. 30
0
 def test_inputfile_sales2(self):
     """Test inputfile: import sales2.csv"""
     self.S = Table.inputfromfile('test_csv/sales2.csv')
     self.assertIsNotNone(self.S.table)
     self.assertIsNotNone(self.S.table[0]['saleid'])
     self.assertIsNotNone(self.S.table[0]['I'])
     self.assertIsNotNone(self.S.table[0]['C'])
     self.assertIsNotNone(self.S.table[0]['S'])
     self.assertIsNotNone(self.S.table[0]['T'])
     self.assertIsNotNone(self.S.table[0]['Q'])
     self.assertIsNotNone(self.S.table[0]['P'])
     self.assertEqual(self.S.table[0]['saleid'], 3506)
     self.assertEqual(self.S.table[0]['I'], 13517)
     self.assertEqual(self.S.table[0]['C'], 16566)
     self.assertEqual(self.S.table[0]['S'], 45)
     self.assertEqual(self.S.table[0]['T'], 73)
     self.assertEqual(self.S.table[0]['Q'], 19)
     self.assertEqual(self.S.table[0]['P'], 'expensive')
     self.assertEqual(len(self.S.table), 10)
Esempio n. 31
0
 def test_inputfile_sales1(self):
     """Test inputfile: import sales1.csv"""
     self.R = Table.inputfromfile('test_csv/sales1.csv')
     self.assertIsNotNone(self.R.table)
     self.assertIsNotNone(self.R.table[0]['saleid'])
     self.assertIsNotNone(self.R.table[0]['itemid'])
     self.assertIsNotNone(self.R.table[0]['customerid'])
     self.assertIsNotNone(self.R.table[0]['storeid'])
     self.assertIsNotNone(self.R.table[0]['time'])
     self.assertIsNotNone(self.R.table[0]['qty'])
     self.assertIsNotNone(self.R.table[0]['pricerange'])
     self.assertEqual(self.R.table[0]['saleid'], 36)
     self.assertEqual(self.R.table[0]['itemid'], 14)
     self.assertEqual(self.R.table[0]['customerid'], 2)
     self.assertEqual(self.R.table[0]['storeid'], 38)
     self.assertEqual(self.R.table[0]['time'], 49)
     self.assertEqual(self.R.table[0]['qty'], 15)
     self.assertEqual(self.R.table[0]['pricerange'], 'moderate')
     self.assertEqual(len(self.R.table), 12)
Esempio n. 32
0
	def __init__(self, applicationWindow):
		"""
		@type applicationWindow: MainApplicationWindow
		"""
		self.applicationWindow = applicationWindow
		self.tableTab = applicationWindow.mainWindow.tableTab
		self.table = Table("", None)
		# Set this to True when programmatically manipulating the columns table
		# to prevent GUI events from causing sync issues with our columns
		self.lockCellChanges = False

		self.previousState = None

		mainWindow = applicationWindow.mainWindow
		mainWindow.addColumnButton.clicked.connect(self.addNewRow)
		mainWindow.removeColumnButton.clicked.connect(self.removeCurrentColumnRow)
		mainWindow.moveColumnDownButton.clicked.connect(self.moveCurrentColumnDown)
		mainWindow.moveColumnUpButton.clicked.connect(self.moveCurrentColumnUp)
		mainWindow.discardTableButton.clicked.connect(self.discardChanges)
		mainWindow.saveTableButton.clicked.connect(self.saveChanges)
		mainWindow.tableName.textEdited.connect(self.nameEdited)
		mainWindow.tableInfoTable.itemSelectionChanged.connect(self.selectedColumnChanged)
Esempio n. 33
0
def load_author_names():
    conn = psycopg2.connect(
        "dbname='citadel' user='******' host='localhost' password=''")
    cur = conn.cursor()
    cur.execute("select * from author_names")
    rows = cur.fetchall()
    print("\nShow me the databases:\n")
    from relations.edges import edge
    open(os.getcwd() + '/storage/edge.txt', 'wb').close()
    db = Table(filename=os.getcwd() + '/storage/author_names.txt',
               type=edge,
               index_attrs=['name'],
               key_sizes=[26])
    i = 1
    for row in rows:
        el = author_name(id=row[0], name=row[1])
        db.put(el.get_key(), el)
        i += 1
        if i % 1000 == 0:
            print("i=", i)
    print("storing records is done, b_index started..")
    db.b_index()
    db.save()
    print("database created and saved")
Esempio n. 34
0
def db_test():
    print 'create database with capacity 100000 test is started..\n'
    open(os.getcwd() + '/storage/student.txt', 'wb').close()
    open(os.getcwd() + '/times.txt', 'wb').close()
    db = Table(filename=os.getcwd() + '/storage/student.txt', type=student, index_attrs=['name'], key_sizes=[26])
    # studs = get_shuffled_dataset()

    print('loading dataset')
    studs = get_shuffled_million()
    i = 0
    for stud in studs[:10000]:
        with Profiler() as p:
            db.put(stud.get_key(), stud)
            i += 1
            if i % 50 == 0:
                print('#', i)
    db.b_index()
    for index in db.index_attrs:
        tree = db.trees[index]
    # print(db.get('581200', 1))
    # print(db.trees['name']['Matthew Cervantes'])
    db.save()
 def __init__(self):
     """
     Constructor
     """
     Table.__init__(self)
Esempio n. 36
0
class TableTab:
	def __init__(self, applicationWindow):
		"""
		@type applicationWindow: MainApplicationWindow
		"""
		self.applicationWindow = applicationWindow
		self.tableTab = applicationWindow.mainWindow.tableTab
		self.table = Table("", None)
		# Set this to True when programmatically manipulating the columns table
		# to prevent GUI events from causing sync issues with our columns
		self.lockCellChanges = False

		self.previousState = None

		mainWindow = applicationWindow.mainWindow
		mainWindow.addColumnButton.clicked.connect(self.addNewRow)
		mainWindow.removeColumnButton.clicked.connect(self.removeCurrentColumnRow)
		mainWindow.moveColumnDownButton.clicked.connect(self.moveCurrentColumnDown)
		mainWindow.moveColumnUpButton.clicked.connect(self.moveCurrentColumnUp)
		mainWindow.discardTableButton.clicked.connect(self.discardChanges)
		mainWindow.saveTableButton.clicked.connect(self.saveChanges)
		mainWindow.tableName.textEdited.connect(self.nameEdited)
		mainWindow.tableInfoTable.itemSelectionChanged.connect(self.selectedColumnChanged)

	def createTableAction(self):
		applicationWindow = self.applicationWindow
		mainWindow = applicationWindow.mainWindow

		applicationWindow.showTableTab()
		machineTabs = mainWindow.twMachineTabs
		tableTab = mainWindow.tableTab

		machineTabs.setTabText(machineTabs.indexOf(tableTab), 'Table: [Untitled]')
		machineTabs.setCurrentWidget(tableTab)

		self.previousState = {
			'table_name': '',
			'columns': None
		}

	def addNewRow(self):
		self.addColumnRow()

	def addColumnRow(self, column=None):
		self.lockCellChanges = True
		applicationWindow = self.applicationWindow
		columnsTable = applicationWindow.mainWindow.tableInfoTable
		columnsTable.cellChanged.connect(self.columnItemChanged)

		tableInfoTable = self.applicationWindow.mainWindow.tableInfoTable

		if column is None:
			column = Column()

		row = TableInfoRow(tableInfoTable, column)
		tableInfoTable.addRow(row)

		self.lockCellChanges = False
		self.checkSaveDiscardState()

	def removeCurrentColumnRow(self):
		tableInfoTable = self.applicationWindow.mainWindow.tableInfoTable
		tableInfoTable.removeRow(tableInfoTable.currentRow())
		self.checkSaveDiscardState()

	def moveCurrentColumnUp(self):
		row = self.applicationWindow.mainWindow.tableInfoTable.selectedIndexes()[0].row()
		self.moveRowTo(row, row - 1)

	def moveCurrentColumnDown(self):
		row = self.applicationWindow.mainWindow.tableInfoTable.selectedIndexes()[0].row()
		self.moveRowTo(row, row + 1)

	def dataTypesSizeHint(self):
		return QSize(300, 400)

	def discardChanges(self):
		print 'discard changes!'

	def saveChanges(self):
		print self.table.getCreateTable()
		self.applicationWindow.currentServer.execute(self.table.getCreateTable())

	def moveRowTo(self, source, destination):
		self.lockCellChanges = True
		columnsTable = self.applicationWindow.mainWindow.tableInfoTable
		columns = self.table.columns

		moveColumn = columns.pop(source)
		if source > destination:
			columns.insert(destination, moveColumn)
			source += 1
		else:
			columns.insert(destination, moveColumn)
			destination += 1

		columnsTable.insertRow(destination)

		for i in [0, 1, 3, 7, 8, 10]:
			newItem = columnsTable.item(source, i)
			if newItem is not None:
				newItem = newItem.clone()
				columnsTable.setItem(destination, i, newItem)

		for i in [2, 4, 5, 6, 9, 11]:
			newWidget = columnsTable.cellWidget(source, i)
			columnsTable.setCellWidget(destination, i, newWidget)

		columnsTable.setCurrentCell(destination, 0)
		columnsTable.removeRow(source)

		for i in xrange(columnsTable.rowCount()):
			columnsTable.item(i, 0).setText(str(i + 1))

		self.lockCellChanges = False
		self.checkMoveColumnButtonState()

	def checkSaveDiscardState(self):
		mainWindow = self.applicationWindow.mainWindow
		tableName = mainWindow.tableName.text()
		columnCount = mainWindow.tableInfoTable.rowCount()
		if tableName != '' and columnCount > 0:
			mainWindow.saveTableButton.setEnabled(True)
		else:
			mainWindow.saveTableButton.setEnabled(False)

		showDiscardButton = False
		previousState = self.previousState
		if previousState is not None:
			for key in previousState:
				if key == 'table_name':
					if tableName != previousState['table_name']:
						showDiscardButton = True
						break
				elif key == 'columns':
					if previousState['columns'] is None and columnCount > 0:
						showDiscardButton = True
						break

			mainWindow.discardTableButton.setEnabled(showDiscardButton)

	def dataTypeChanged(self, dataType):
		columnsTable = self.applicationWindow.mainWindow.tableInfoTable
		dataType = columnsTable.cellWidget(0, 2).itemText(dataType)

		for i in xrange(columnsTable.rowCount()):
			if self.table.columns[i].dataType != columnsTable.cellWidget(i, 2).currentText():
				self.table.columns[i].dataType = dataType
				break

	def columnItemChanged(self, row, column):
		# This if allows us to avoid change events triggered from initially
		# populating the row in the GUI
		if self.lockCellChanges is False:
			columnsTable = self.applicationWindow.mainWindow.tableInfoTable
			tableColumn = self.table.columns[row]

			text = columnsTable.item(row, column).text()
			if column == 1:
				tableColumn.name = text
			elif column == 3:
				tableColumn.setLength(text)
			elif column == 7:
				tableColumn.setDefault(text)
			elif column == 8:
				tableColumn.comment = text
			elif column == 10:
				tableColumn.setExpression(text)

	def unsignedStateChanged(self, state):
		columnsTable = self.applicationWindow.mainWindow.tableInfoTable

		for i in xrange(columnsTable.rowCount()):
			if self.table.columns[i].unsigned != columnsTable.cellWidget(i, 4).isChecked():
				self.table.columns[i].unsigned = state

	def nullStateChanged(self, state):
		columnsTable = self.applicationWindow.mainWindow.tableInfoTable

		for i in xrange(columnsTable.rowCount()):
			if self.table.columns[i].allowsNull != columnsTable.cellWidget(i, 5).isChecked():
				self.table.columns[i].allowsNull = state

	def zerofillStateChanged(self, state):
		columnsTable = self.applicationWindow.mainWindow.tableInfoTable

		for i in xrange(columnsTable.rowCount()):
			if self.table.columns[i].zerofill != columnsTable.cellWidget(i, 6).isChecked():
				self.table.columns[i].zerofill = state

	def selectedColumnChanged(self):
		self.checkMoveColumnButtonState()

	def checkMoveColumnButtonState(self):
		mainWindow = self.applicationWindow.mainWindow
		columnsTable = self.applicationWindow.mainWindow.tableInfoTable
		row = columnsTable.selectedIndexes()[0].row() + 1

		totalRows = columnsTable.rowCount()
		if totalRows < 2:
			mainWindow.moveColumnUpButton.setEnabled(False)
			mainWindow.moveColumnDownButton.setEnabled(False)
		else:
			if row < totalRows:
				mainWindow.moveColumnDownButton.setEnabled(True)
			else:
				mainWindow.moveColumnDownButton.setEnabled(False)

			if row > 1:
				mainWindow.moveColumnUpButton.setEnabled(True)
			else:
				mainWindow.moveColumnUpButton.setEnabled(False)

	def nameEdited(self):
		self.table.name = self.applicationWindow.mainWindow.tableName.text()
		self.checkSaveDiscardState()

	def resetColumn(self, index):
		column = self.table.columns[index]

		columnsTable = self.applicationWindow.mainWindow.tableInfoTable
		dataTypes = columnsTable.cellWidget(index, 2)
		unsignedCheckbox = columnsTable.cellWidget(index, 4)
		allowsNullCheckbox = columnsTable.cellWidget(index, 5)

		columnsTable.setItem(index, 1, QTableWidgetItem(column.name))
		dataTypes.setCurrentIndex(dataTypes.findText(column.dataType.upper()))
		if column.length is not None:
			columnsTable.setItem(index, 3, QTableWidgetItem(column.length))
		if column.unsigned:
			unsignedCheckbox.setChecked(True)
		if column.allowsNull is False:
			allowsNullCheckbox.setChecked(False)

	def populateDefaultCollationField(self, server):
		"""
		@type server: DatabaseServer
		@type defaultCollation: str
		"""
		field = self.applicationWindow.mainWindow.tableOptionsDefaultCollation
		collations = server.getCollations()
		for collation in collations:
			field.addItem(collation['Collation'])

	def setCurrentTable(self, table):
		"""
		@type table: Table
		"""
		self.table = table

		table.refresh()
		applicationWindow = self.applicationWindow
		applicationWindow.showTableTab()
		mainWindow = applicationWindow.mainWindow
		tableTab = mainWindow.tableTab

		twMachineTabs = mainWindow.twMachineTabs
		twMachineTabs.setTabText(twMachineTabs.indexOf(tableTab), "Table: %s" % table.name)
		twMachineTabs.setCurrentWidget(tableTab)

		self.updateUI()

	def updateUI(self):
		table = self.table

		mainWindow = self.applicationWindow.mainWindow

		mainWindow.tableName.setText(table.name)
		mainWindow.tableComment.setPlainText(table.comment)

		for i in range(0, mainWindow.tableInfoTable.rowCount()):
			mainWindow.tableInfoTable.removeRow(0)

		for column in table.columns:
			self.addColumnRow(column)

		self.setAutoincrementValue(table.autoincrement)
		self.setDefaultCollationValue(table.defaultCollation)

		indexTree = self.applicationWindow.mainWindow.indexes
		for i in range(indexTree.topLevelItemCount()):
			indexTree.takeTopLevelItem(0)

		for index in table.indexes:
			self.addIndex(index)

		mainWindow.txtCreateCode.setPlainText(QString(str(table)))


	def setDefaultCollationValue(self, collation):
		field = self.applicationWindow.mainWindow.tableOptionsDefaultCollation
		field.setCurrentIndex(field.findText(collation))

	def setAutoincrementValue(self, autoincrement):
		if autoincrement is None:
			autoincrement = ''

		self.applicationWindow.mainWindow.tableOptionsAutoIncrement.setText(autoincrement)

	def addIndex(self, index):
		indexTree = self.applicationWindow.mainWindow.indexes

		if index.type == 'PRIMARY':
			name = 'PRIMARY KEY'
		else:
			name = index.name

		indexItem = QTreeWidgetItem()
		indexItem.setIcon(0, QIcon('../resources/icons/key.png'))
		indexItem.setText(0, name)
		indexItem.setText(1, index.type)

		for column in index.columns:
			columnItem = QTreeWidgetItem()
			columnItem.setIcon(0, QIcon('../resources/icons/bullet_black.png'))
			columnItem.setText(0, column.name)
			indexItem.addChild(columnItem)

		indexTree.addTopLevelItem(indexItem)