Skip to content

Campaigns Table

campaigns/campaigns.py

CampaignsDB

CampaignsDB(dburi='localhost/tm_admin')

Bases: DBSupport

Parameters:

Name Type Description Default
dburi str

The URI string for the database connection

'localhost/tm_admin'

Returns:

Type Description
UsersDB

An instance of this class

Source code in tm_admin/campaigns/campaigns.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def __init__(self,
             dburi: str = "localhost/tm_admin",
            ):
    """
    A class to access the campaigns table.

    Args:
        dburi (str): The URI string for the database connection

    Returns:
        (UsersDB): An instance of this class
    """
    self.pg = None
    self.profile = UsersTable()
    self.types = dir(tm_admin.types_tm)
    super().__init__('campaigns')

mergeOrganizations async

mergeOrganizations(inpg)

A method to merge the contents of the TM campaign_organizations into the campaigns table as an array.

Parameters:

Name Type Description Default
inpg PostgresClient

The input database

required
Source code in tm_admin/campaigns/campaigns.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
async def mergeOrganizations(self,
                    inpg: PostgresClient,
                    ):
    """
    A method to merge the contents of the TM campaign_organizations into
    the campaigns table as an array.

    Args:
        inpg (PostgresClient): The input database
    """
    # FIXME: this is a weird table, and only has 4 entries, none of which appear
    # to be in the other tables, so nothing updates.
    table = 'campaign_organisations'
    sql = f"SELECT * FROM {table} ORDER BY campaign_id"
    # print(sql)
    result = await inpg.execute(sql)

    data = dict()
    pbar = tqdm.tqdm(result)
    for record in result:
        sql = f" UPDATE campaigns SET organizations = organizations||{record['organisation_id']} WHERE id={record['campaign_id']};"
        # print(sql)
        await self.pg.execute(sql)

mergeProjects async

mergeProjects(inpg)

A method to merge the contents of the TM campaign_projects into the campaigns table as an array.

Parameters:

Name Type Description Default
inpg PostgresClient

The input database

required
Source code in tm_admin/campaigns/campaigns.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
async def mergeProjects(self,
                    inpg: PostgresClient,
                    ):
    """
    A method to merge the contents of the TM campaign_projects into
    the campaigns table as an array.

    Args:
        inpg (PostgresClient): The input database
    """
    table = 'campaign_projects'
    sql = f"SELECT * FROM {table} ORDER BY campaign_id"
    # print(sql)
    result = await inpg.execute(sql)

    index = 0
    data = dict()
    pbar = tqdm.tqdm(result)

    for record in pbar:
        sql = f" UPDATE campaigns SET projects = projects||{record['project_id']} WHERE id={record['campaign_id']};"
        # print(sql)
        await self.pg.execute(sql)

main async

main()

This main function lets this class be run standalone by a bash script.

Source code in tm_admin/campaigns/campaigns.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
async def main():
    """This main function lets this class be run standalone by a bash script."""
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", nargs="?", const="0", help="verbose output")
    parser.add_argument("-i", "--inuri", default='localhost/tm4',
                            help="Input database URI")
    parser.add_argument("-o", "--outuri", default='localhost/tm_admin',
                            help="Output database URI")
    # parser.add_argument("-r", "--reset", help="Reset Sequences")
    args = parser.parse_args()

    # if len(argv) <= 1:
    #     parser.print_help()
    #     quit()

    # if verbose, dump to the terminal.
    log_level = os.getenv("LOG_LEVEL", default="INFO")
    if args.verbose is not None:
        log_level = logging.DEBUG

    logging.basicConfig(
        level=log_level,
        format=("%(asctime)s.%(msecs)03d [%(levelname)s] " "%(name)s | %(funcName)s:%(lineno)d | %(message)s"),
        datefmt="%y-%m-%d %H:%M:%S",
        stream=sys.stdout,
    )

    inpg = PostgresClient()
    await inpg.connect(args.inuri)

    camp = camp = CampaignsDB(args.inuri)
    await camp.connect(args.outuri)

    await camp.mergeProjects(inpg)
    await camp.mergeOrganizations(inpg)

options: show_source: false heading_level: 3

campaigns/campaigns_class.py

options: show_source: false heading_level: 3

campaigns/api.py

CampaignsAPI

CampaignsAPI()

Bases: PGSupport

Returns:

Type Description
CampaignsAPI

An instance of this class

Source code in tm_admin/campaigns/api.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def __init__(self):
    """
    Create a class to handle the backend API calls, so the code can be shared
    between test cases and the actual code.

    Returns:
        (CampaignsAPI): An instance of this class
    """
    # self.allowed_roles = [
    #     Teamrole.TEAM_MAPPER,
    #     Teamrole.TEAM_VALIDATOR,
    #     Teamrole.TEAM_MANAGER,
    # ]
    # self.messagesdb = MessagesDB()
    # self.usersdb = UsersDB()
    # self.teamsdb = TeamsDB()
    super().__init__("campaigns")

initialize async

initialize(inuri)

Connect to all tables for API endpoints that require accessing multiple tables.

Parameters:

Name Type Description Default
inuri str

The URI for the TM Admin output database

required
Source code in tm_admin/campaigns/api.py
76
77
78
79
80
81
82
83
84
85
86
87
async def initialize(self,
                  inuri: str,
                  ):
    """
    Connect to all tables for API endpoints that require
    accessing multiple tables.

    Args:
        inuri (str): The URI for the TM Admin output database
    """
    await self.connect(inuri)
    await self.getTypes("campaigns")

getByID async

getByID(campaign_id)

Get all the information for an campaign using it's ID

Parameters:

Name Type Description Default
campaign_id int

The campaign to get the data for

required

Returns:

Type Description
dict

the campaign information

Source code in tm_admin/campaigns/api.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
async def getByID(self,
                 campaign_id: int,
                ):
    """
    Get all the information for an campaign using it's ID

    Args:
        campaign_id (int): The campaign to get the data for

    Returns:
        (dict): the campaign information
    """
    # log.debug(f"--- getByID() ---")
    sql = f"SELECT * FROM campaigns WHERE id={campaign_id}"
    results = await self.execute(sql)
    return results

getByName async

getByName(name)

Get all the information for a campaign using the name

Parameters:

Name Type Description Default
name str

The campaign to get the data for

required

Returns:

Type Description
dict

the campaign information

Source code in tm_admin/campaigns/api.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
async def getByName(self,
                    name: str,
                    ):
    """
    Get all the information for a campaign using the name

    Args:
        name (str): The campaign to get the data for

    Returns:
        (dict): the campaign information
    """
    # log.debug(f"--- getByName() ---")
    sql = f"SELECT * FROM campaigns WHERE name='{name}'"
    results = await self.execute(sql)
    return results

create async

create(campaign)

Create a campaign and add it to the database.

Parameters:

Name Type Description Default
campaign CampaignsTable

The team data

required

Returns:

Type Description
bool

Whether the campaign got created

Source code in tm_admin/campaigns/api.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
async def create(self,
                 campaign: CampaignsTable,
                 ):
    """
    Create a campaign and add it to the database.

    Args:
        campaign (CampaignsTable): The team data

    Returns:
        (bool): Whether the campaign got created
    """
    # log.warning(f"create(): unimplemented!")
    result = await self.insertRecords([campaign])

    # The ID of the record that just got inserted is returned
    if result:
        return True

    return False

update async

update(campaign)

Update a campaign that is already in the database.

Parameters:

Name Type Description Default
campaign CampaignsTable

The campaign data

required

Returns:

Type Description
bool

Whether the campaign got updated

Source code in tm_admin/campaigns/api.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
async def update(self,
                 campaign: CampaignsTable,
                 ):
    """
    Update a campaign that is already in the database.

    Args:
        campaign (CampaignsTable): The campaign data

    Returns:
        (bool): Whether the campaign got updated
    """
    log.warning(f"update(): unimplemented!")

    return False

main async

main()

This main function lets this class be run standalone by a bash script.

Source code in tm_admin/campaigns/api.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
async def main():
    """This main function lets this class be run standalone by a bash script."""
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", nargs="?", const="0", help="verbose output")
    parser.add_argument("-u", "--uri", default='localhost/tm_admin', help="Database URI")

    args = parser.parse_args()

    # if verbose, dump to the terminal.
    log_level = os.getenv("LOG_LEVEL", default="INFO")
    if args.verbose is not None:
        log_level = logging.DEBUG

    logging.basicConfig(
        level=log_level,
        format=("%(asctime)s.%(msecs)03d [%(levelname)s] " "%(name)s | %(funcName)s:%(lineno)d | %(message)s"),
        datefmt="%y-%m-%d %H:%M:%S",
        stream=sys.stdout,
    )

options: show_source: false heading_level: 3


Last update: March 6, 2024