-
Notifications
You must be signed in to change notification settings - Fork 1
/
statement.h
71 lines (63 loc) · 1.92 KB
/
statement.h
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
#include "types.h"
#include "cursor.h"
#ifndef STATEMENT_H
#define STATEMENT_H
/**
* The parsing result of a SQL statement sentence is stored in statement_t.
* These `execute_xxx` functions are equal to the "Vitrual Machine" in sqlite.
* SQL Statement:
* - insert id username email
* - select
* - update id username email
**/
execute_result_t execute_insert(statement_t *statement, table_t *table)
{
row_t *row_to_insert = &(statement->row_to_insert);
uint32_t key_to_insert = row_to_insert->id;
cursor_t *cursor = table_find(table, key_to_insert);
void *node = get_page(table->pager, cursor->page_num);
uint32_t num_cells = *leaf_node_num_cells(node);
if (cursor->cell_num < num_cells)
{
uint32_t key_at_index = *leaf_node_key(node, cursor->cell_num);
// printf("[execute insert] key_at_index = %d\n", key_at_index);
if (key_at_index == key_to_insert)
{
free(cursor);
return EXECUTE_DUPLICATE_KEY;
}
}
leaf_node_insert(cursor, row_to_insert->id, row_to_insert);
free(cursor);
return EXECUTE_SUCCESS;
}
execute_result_t execute_select(statement_t *statement, table_t *table)
{
cursor_t *cursor = table_start(table);
row_t row;
while (!(cursor->end_of_table))
{
deserialize_row(cursor_value(cursor), &row);
print_row(&row);
cursor_advance(cursor);
}
free(cursor);
return EXECUTE_SUCCESS;
}
execute_result_t execute_update(statement_t *statement, table_t *table)
{
uint32_t key_to_update = statement->row_to_insert.id;
cursor_t *cursor = table_find(table, key_to_update);
void *row = cursor_value(cursor);
row_t temp;
deserialize_row(row, &temp);
if (temp.id != statement->row_to_insert.id)
{
free(cursor);
return EXECUTE_NO_SUCH_KEY;
}
serialize_row(&(statement->row_to_insert), row);
free(cursor);
return EXECUTE_SUCCESS;
}
#endif