Passed
Push — develop ( 67792d...edb739 )
by Antony
34s
created

build.migrate.create_tables()   A

Complexity

Conditions 4

Size

Total Lines 56
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 56
rs 9.0544
c 0
b 0
f 0
cc 4
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import os
2
import psycopg2
3
from config import dbconfig, filename, section
4
5
6
7
def create_tables():
8
    """create tables in postgresql database"""
9
    commands = (
10
        """
11
        DROP TABLE IF EXISTS tb_users;
12
        CREATE TABLE tb_users(
13
            user_id SERIAL PRIMARY KEY,
14
            username VARCHAR(100) UNIQUE NOT NULL,
15
            firstname VARCHAR(50) NOT NULL,
16
            lastname VARCHAR(50) NOT NULL,
17
            password VARCHAR(255) NOT NULL,
18
            role BOOL DEFAULT 'false',
19
            created_on TIMESTAMP NOT NULL,
20
            last_login TIMESTAMP
21
        )
22
        """
23
        ,
24
        """
25
        DROP TABLE IF EXISTS tb_request;
26
        CREATE TABLE tb_request(
27
            request_id SERIAL PRIMARY KEY,
28
            requestor INTEGER NOT NULL,
29
            type VARCHAR(50) NOT NULL,
30
            status VARCHAR(50) NOT NULL,
31
            description TEXT,
32
            created_on TIMESTAMP NOT NULL,
33
            FOREIGN KEY (requestor) REFERENCES tb_users(user_id)
34
        )
35
        """
36
    )
37
38
    conn = None
39
    try:
40
        params = dbconfig(filename, section)
41
        conn = psycopg2.connect(**params)
42
43
        #create cursor
44
        cur = conn.cursor()
45
        
46
        #execute statement
47
        for command in commands:
48
            cur.execute(command)
49
50
        cur.close()
51
52
        #commit the changes
53
        conn.commit()
54
        print("Tables Created Succesfully")
55
56
    except (Exception, psycopg2.DatabaseError) as error:
57
        print(error)
58
    finally:
59
        if conn is not None:
60
            conn.close()
61
    
62
    return "Tables user, request and admin created succesfully"
63
        
64
65
if __name__ == '__main__':
66
    create_tables()