-
Notifications
You must be signed in to change notification settings - Fork 0
/
employee.bal
90 lines (76 loc) · 2.97 KB
/
employee.bal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import ballerina/sql;
import ballerina/log;
type Employee record {|
readonly int emp_id;
string name;
decimal salary;
Position position;
string[] projects;
|};
type Project record {|
readonly string project_id;
string project_name;
Employee manager;
|};
enum Position {
SE = "Software Engineer",
PM = "Project Manager",
TL = "Tech Lead"
}
const string PROJECT_ID_PREFIX = "project_";
configurable table<Employee> key(emp_id) & readonly employees = ?;
function addEmployee(Employee employee) returns int?|error {
sql:ParameterizedQuery query = `INSERT INTO employee (emp_id, name, salary, position)
VALUES (${employee.emp_id},${employee.name}, ${employee.salary},${employee.position})`;
sql:ExecutionResult result = check dbClient->execute(query);
return result.affectedRowCount;
}
function analyseProject(Employee employee) returns error? {
if (employee.position == PM) {
int project_ID = 1;
foreach string project_name in employee.projects {
Project project = {
project_id: PROJECT_ID_PREFIX + project_ID.toString(),
project_name: project_name,
manager: employee
};
validateQueryResult(check addProject(project));
project_ID += 1;
}
}
}
function addProject(Project project) returns int?|error {
sql:ParameterizedQuery query = `INSERT INTO project (project_id, project_name, project_manager_id)
VALUES (${project.project_id}, ${project.project_name}, ${project.manager.emp_id})`;
sql:ExecutionResult result = check dbClient->execute(query);
return result.affectedRowCount;
}
function addProjectTeam() returns error? {
foreach Employee employee in employees {
foreach string project in employee.projects {
sql:ParameterizedQuery selectQuery = `SELECT project.project_id FROM project
WHERE (project.project_name = ${project})`;
stream<record {}, error> resultStream = dbClient->query(selectQuery);
record {|
record {} value;
|}|error? result = resultStream.next();
if (result is record {|
record {} value;
|}) {
anydata project_id = result.value["project_id"];
sql:ParameterizedQuery query = `INSERT INTO project_team (project_id,emp_id)
VALUES (${<string>project_id}, ${employee.emp_id})`;
sql:ExecutionResult queryResult = check dbClient->execute(query);
validateQueryResult(queryResult.affectedRowCount);
} else if (result is error) {
log:printError("Next operation on the stream failed!", result, {});
}
check resultStream.close();
}
}
}
function validateQueryResult(int? rowCount) {
if ((rowCount is int && <int>rowCount <= 0) || !(rowCount is int)) {
log:printError("Failed to execute query");
}
}