Compare commits
67 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
cff85332c7 | |
|
|
53c537a0ae | |
|
|
981e4a8f2e | |
|
|
59d9dfe333 | |
|
|
bd8af1fe46 | |
|
|
cee58fd2c2 | |
|
|
255240899c | |
|
|
cbc2e94653 | |
|
|
819accf25a | |
|
|
dfb3849780 | |
|
|
74fa63df6e | |
|
|
f0a0f5fcc5 | |
|
|
76815dc009 | |
|
|
1a882a9ee6 | |
|
|
7758348b68 | |
|
|
b074601139 | |
|
|
19ece33f53 | |
|
|
5d826c856b | |
|
|
e807068a8f | |
|
|
23f16eba7c | |
|
|
5bc56fc02f | |
|
|
5a196e8096 | |
|
|
6b0ccf6f62 | |
|
|
3a54c74459 | |
|
|
7576ca6e07 | |
|
|
09c55212e6 | |
|
|
f455fe3ac1 | |
|
|
04af05a859 | |
|
|
93ace67b06 | |
|
|
2a46b8bdd8 | |
|
|
dfc44d4a42 | |
|
|
3900e88c53 | |
|
|
41d9fcfd26 | |
|
|
8f4aea4f0b | |
|
|
e970fb92dc | |
|
|
1fbc036907 | |
|
|
4387e8852a | |
|
|
42b6cbb501 | |
|
|
c5547abf8e | |
|
|
8269dc065f | |
|
|
705c19c73d | |
|
|
95d9400d77 | |
|
|
0f06c8238c | |
|
|
49c1d030a9 | |
|
|
7a55bdb7cc | |
|
|
4c7cc4c269 | |
|
|
800ed82ca3 | |
|
|
81f221828d | |
|
|
541ddd61a6 | |
|
|
70773c8f53 | |
|
|
928b0c8fbb | |
|
|
22d9b9fe98 | |
|
|
5514a55bfa | |
|
|
94ef8aa0e3 | |
|
|
73189d9112 | |
|
|
ccb26b2152 | |
|
|
c1cda703b1 | |
|
|
01dd50c007 | |
|
|
4f76c8b27a | |
|
|
f0c4025a52 | |
|
|
e91972e82f | |
|
|
379ed252f3 | |
|
|
605b5b00f0 | |
|
|
915b2800cd | |
|
|
a8e2cf0915 | |
|
|
f12abf70f9 | |
|
|
c70b28b19f |
|
|
@ -1,6 +1,7 @@
|
|||
#!/bin/bash
|
||||
#######################################################################
|
||||
# Copyright (c): 2020-2021, Huawei Tech. Co., Ltd.
|
||||
|
||||
# descript: Compile and pack MPPDB
|
||||
# Return 0 means OK.
|
||||
# Return 1 means failed.
|
||||
|
|
|
|||
|
|
@ -13,317 +13,292 @@
|
|||
*
|
||||
* -------------------------------------------------------------------------
|
||||
*/
|
||||
#include "postgres.h"
|
||||
#include "postgres.h"
|
||||
#include "knl/knl_variable.h"
|
||||
|
||||
#include "lib/dllist.h"
|
||||
#include "miscadmin.h"
|
||||
|
||||
Dllist* DLNewList(void)
|
||||
{
|
||||
Dllist* l = NULL;
|
||||
Dllist* DLNewList(void) {
|
||||
Dllist* l = NULL; // list pointer
|
||||
|
||||
l = (Dllist*)palloc(sizeof(Dllist));
|
||||
l = (Dllist*)palloc(sizeof(Dllist)); // allocate memory
|
||||
|
||||
l->dll_head = NULL;
|
||||
l->dll_tail = NULL;
|
||||
l->dll_len = 0;
|
||||
l->dll_head = NULL; // init head pointer
|
||||
l->dll_tail = NULL; // init tail pointer
|
||||
l->dll_len = 0; // init length
|
||||
|
||||
return l;
|
||||
}
|
||||
|
||||
void DLInitList(Dllist* list)
|
||||
{
|
||||
list->dll_head = NULL;
|
||||
list->dll_tail = NULL;
|
||||
list->dll_len = 0;
|
||||
void DLInitList(Dllist* list) {
|
||||
list->dll_head = NULL; // init head pointer
|
||||
list->dll_tail = NULL; // init tail pointer
|
||||
list->dll_len = 0; // init length
|
||||
}
|
||||
|
||||
/*
|
||||
* free up a list and all the nodes in it --- but *not* whatever the nodes
|
||||
* might point to!
|
||||
*/
|
||||
void DLFreeList(Dllist* list)
|
||||
{
|
||||
Dlelem* curr = NULL;
|
||||
void DLFreeList(Dllist* list) {
|
||||
Dlelem* curr = NULL; // current pointer
|
||||
|
||||
while ((curr = DLRemHead(list)) != NULL)
|
||||
while ((curr = DLRemHead(list)) != NULL) // remove head from list
|
||||
pfree(curr);
|
||||
|
||||
pfree(list);
|
||||
pfree(list); // free list
|
||||
}
|
||||
|
||||
Dlelem* DLNewElem(void* val)
|
||||
{
|
||||
Dlelem* e = NULL;
|
||||
Dlelem* DLNewElem(void* val) {
|
||||
Dlelem* e = NULL; // element pointer
|
||||
|
||||
e = (Dlelem*)palloc(sizeof(Dlelem));
|
||||
e = (Dlelem*)palloc(sizeof(Dlelem)); // allocate memory
|
||||
|
||||
e->dle_next = NULL;
|
||||
e->dle_prev = NULL;
|
||||
e->dle_val = val;
|
||||
e->dle_list = NULL;
|
||||
e->dle_next = NULL; // init next pointer
|
||||
e->dle_prev = NULL; // init prev pointer
|
||||
e->dle_val = val; // init value
|
||||
e->dle_list = NULL; // init list
|
||||
return e;
|
||||
}
|
||||
|
||||
void DLInitElem(Dlelem* e, void* val)
|
||||
{
|
||||
e->dle_next = NULL;
|
||||
e->dle_prev = NULL;
|
||||
e->dle_val = val;
|
||||
e->dle_list = NULL;
|
||||
void DLInitElem(Dlelem* e, void* val) {
|
||||
e->dle_next = NULL; // init next pointer
|
||||
e->dle_prev = NULL; // init prev pointer
|
||||
e->dle_val = val; // init value
|
||||
e->dle_list = NULL; // init list
|
||||
}
|
||||
|
||||
void DLFreeElem(Dlelem* e)
|
||||
{
|
||||
pfree(e);
|
||||
void DLFreeElem(Dlelem* e) {
|
||||
pfree(e); // free element
|
||||
}
|
||||
|
||||
void DLRemove(Dlelem* e)
|
||||
{
|
||||
Dllist* l = e->dle_list;
|
||||
void DLRemove(Dlelem* e) {
|
||||
Dllist* l = e->dle_list; // list pointer
|
||||
|
||||
if (e->dle_prev)
|
||||
if (e->dle_prev) // if e has prev element
|
||||
e->dle_prev->dle_next = e->dle_next;
|
||||
else {
|
||||
/* must be the head element */
|
||||
Assert(e == l->dll_head);
|
||||
l->dll_head = e->dle_next;
|
||||
l->dll_head = e->dle_next; // set head pointer
|
||||
}
|
||||
if (e->dle_next)
|
||||
e->dle_next->dle_prev = e->dle_prev;
|
||||
else {
|
||||
/* must be the tail element */
|
||||
Assert(e == l->dll_tail);
|
||||
l->dll_tail = e->dle_prev;
|
||||
l->dll_tail = e->dle_prev; // set tail pointer
|
||||
}
|
||||
if (l != NULL) {
|
||||
l->dll_len--;
|
||||
l->dll_len--; // decrease length
|
||||
}
|
||||
|
||||
e->dle_next = NULL;
|
||||
e->dle_next = NULL; // reset pointer
|
||||
e->dle_prev = NULL;
|
||||
e->dle_list = NULL;
|
||||
}
|
||||
|
||||
void DLAddHead(Dllist* l, Dlelem* e)
|
||||
{
|
||||
e->dle_list = l;
|
||||
void DLAddHead(Dllist* l, Dlelem* e) {
|
||||
e->dle_list = l; // set list pointer
|
||||
|
||||
if (l->dll_head)
|
||||
l->dll_head->dle_prev = e;
|
||||
e->dle_next = l->dll_head;
|
||||
e->dle_prev = NULL;
|
||||
l->dll_head = e;
|
||||
if (l->dll_head) // if list is not empty
|
||||
l->dll_head->dle_prev = e; // set prev pointer
|
||||
e->dle_next = l->dll_head; // set next pointer
|
||||
e->dle_prev = NULL; // set prev pointer
|
||||
l->dll_head = e; // set head pointer
|
||||
|
||||
if (l->dll_tail == NULL) /* if this is first element added */
|
||||
l->dll_tail = e;
|
||||
l->dll_len++;
|
||||
l->dll_tail = e; // set tail pointer
|
||||
l->dll_len++; // increase length
|
||||
}
|
||||
|
||||
void DLAddTail(Dllist* l, Dlelem* e)
|
||||
{
|
||||
e->dle_list = l;
|
||||
void DLAddTail(Dllist* l, Dlelem* e) {
|
||||
e->dle_list = l; // set list pointer
|
||||
|
||||
if (l->dll_tail)
|
||||
l->dll_tail->dle_next = e;
|
||||
e->dle_prev = l->dll_tail;
|
||||
e->dle_next = NULL;
|
||||
l->dll_tail = e;
|
||||
if (l->dll_tail) // if list is not empty
|
||||
l->dll_tail->dle_next = e; // set next pointer
|
||||
e->dle_prev = l->dll_tail; // set prev pointer
|
||||
e->dle_next = NULL; // set next pointer
|
||||
l->dll_tail = e; // set tail pointer
|
||||
|
||||
if (l->dll_head == NULL) /* if this is first element added */
|
||||
l->dll_head = e;
|
||||
l->dll_len++;
|
||||
l->dll_len++; // increase length
|
||||
}
|
||||
|
||||
Dlelem* DLRemHead(Dllist* l)
|
||||
{
|
||||
Dlelem* DLRemHead(Dllist* l) {
|
||||
/* remove and return the head */
|
||||
Dlelem* result = l->dll_head;
|
||||
|
||||
if (result == NULL)
|
||||
if (result == NULL) /* if list is empty */
|
||||
return result;
|
||||
|
||||
if (result->dle_next)
|
||||
result->dle_next->dle_prev = NULL;
|
||||
if (result->dle_next) // if head has next element
|
||||
result->dle_next->dle_prev = NULL; // set prev pointer
|
||||
|
||||
l->dll_head = result->dle_next;
|
||||
l->dll_head = result->dle_next; // set head pointer
|
||||
|
||||
if (result == l->dll_tail) /* if the head is also the tail */
|
||||
l->dll_tail = NULL;
|
||||
|
||||
l->dll_len--;
|
||||
result->dle_next = NULL;
|
||||
l->dll_len--; // decrease length
|
||||
result->dle_next = NULL; // reset pointer
|
||||
result->dle_list = NULL;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Dlelem* DLRemTail(Dllist* l)
|
||||
{
|
||||
Dlelem* DLRemTail(Dllist* l) {
|
||||
/* remove and return the tail */
|
||||
Dlelem* result = l->dll_tail;
|
||||
|
||||
if (result == NULL)
|
||||
if (result == NULL) /* if list is empty */
|
||||
return result;
|
||||
|
||||
if (result->dle_prev)
|
||||
result->dle_prev->dle_next = NULL;
|
||||
if (result->dle_prev) // if tail has prev element
|
||||
result->dle_prev->dle_next = NULL; // set the previous poninter's next pointer
|
||||
|
||||
l->dll_tail = result->dle_prev;
|
||||
l->dll_tail = result->dle_prev; // set tail pointer
|
||||
|
||||
if (result == l->dll_head) /* if the tail is also the head */
|
||||
l->dll_head = NULL;
|
||||
l->dll_head = NULL; // set head pointer
|
||||
|
||||
l->dll_len--;
|
||||
result->dle_prev = NULL;
|
||||
l->dll_len--; // decrease length
|
||||
result->dle_prev = NULL; // reset pointer
|
||||
result->dle_list = NULL;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Same as DLRemove followed by DLAddHead, but faster */
|
||||
void DLMoveToFront(Dlelem* e)
|
||||
{
|
||||
Dllist* l = e->dle_list;
|
||||
void DLMoveToFront(Dlelem* e) {
|
||||
Dllist* l = e->dle_list; // list pointer
|
||||
|
||||
if (l->dll_head == e)
|
||||
return; /* Fast path if already at front */
|
||||
|
||||
Assert(e->dle_prev != NULL); /* since it's not the head */
|
||||
e->dle_prev->dle_next = e->dle_next;
|
||||
e->dle_prev->dle_next = e->dle_next; // set next pointer
|
||||
|
||||
if (e->dle_next)
|
||||
e->dle_next->dle_prev = e->dle_prev;
|
||||
if (e->dle_next) // if e has next element
|
||||
e->dle_next->dle_prev = e->dle_prev; // set prev pointer
|
||||
else {
|
||||
/* must be the tail element */
|
||||
Assert(e == l->dll_tail);
|
||||
l->dll_tail = e->dle_prev;
|
||||
l->dll_tail = e->dle_prev; // set tail pointer
|
||||
}
|
||||
|
||||
l->dll_head->dle_prev = e;
|
||||
e->dle_next = l->dll_head;
|
||||
e->dle_prev = NULL;
|
||||
l->dll_head = e;
|
||||
l->dll_head->dle_prev = e; // set prev pointer
|
||||
e->dle_next = l->dll_head; // set next pointer
|
||||
e->dle_prev = NULL; // set prev pointer
|
||||
l->dll_head = e; // set head pointer
|
||||
/* We need not check dll_tail, since there must have been > 1 entry */
|
||||
}
|
||||
|
||||
/*
|
||||
* double-linked list length
|
||||
*/
|
||||
uint64 DLListLength(Dllist* list)
|
||||
{
|
||||
Dlelem* cur = list->dll_head;
|
||||
uint64 length = 0;
|
||||
uint64 DLListLength(Dllist* list) {
|
||||
Dlelem* cur = list->dll_head; // current pointer
|
||||
uint64 length = 0; // init length
|
||||
|
||||
while (cur != NULL) {
|
||||
length++;
|
||||
cur = cur->dle_next;
|
||||
while (cur != NULL) { // traverse list
|
||||
length++; // increase length
|
||||
cur = cur->dle_next; // get next pointer
|
||||
}
|
||||
Assert(length == list->dll_len);
|
||||
return length;
|
||||
Assert(length == list->dll_len); // check length
|
||||
return length; // return length
|
||||
}
|
||||
|
||||
DllistWithLock::DllistWithLock()
|
||||
{
|
||||
DLInitList(&m_list);
|
||||
SpinLockInit(&m_lock);
|
||||
DllistWithLock::DllistWithLock() {
|
||||
DLInitList(&m_list); // init list
|
||||
SpinLockInit(&m_lock); // init lock
|
||||
}
|
||||
|
||||
DllistWithLock::~DllistWithLock()
|
||||
{
|
||||
SpinLockFree(&m_lock);
|
||||
DllistWithLock::~DllistWithLock() {
|
||||
SpinLockFree(&m_lock); // free lock
|
||||
}
|
||||
|
||||
bool DllistWithLock::RemoveConfirm(Dlelem* e)
|
||||
{
|
||||
bool found = false;
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
if (e->dle_list == &m_list) {
|
||||
bool DllistWithLock::RemoveConfirm(Dlelem* e) {
|
||||
bool found = false; // found flag
|
||||
START_CRIT_SECTION(); // start critical section,avoid interrupt
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
if (e->dle_list == &m_list) { // if e is in list
|
||||
found = true;
|
||||
DLRemove(e);
|
||||
DLRemove(e); // remove e from list
|
||||
}
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
return found;
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
return found; // return found flag
|
||||
}
|
||||
|
||||
void DllistWithLock::AddHead(Dlelem* e)
|
||||
{
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
if (e->dle_list == NULL) {
|
||||
DLAddHead(&m_list, e);
|
||||
void DllistWithLock::AddHead(Dlelem* e) {
|
||||
START_CRIT_SECTION(); // start critical section
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
if (e->dle_list == NULL) { // if e is not in list
|
||||
DLAddHead(&m_list, e); // add e to list
|
||||
}
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
}
|
||||
|
||||
void DllistWithLock::AddTail(Dlelem* e)
|
||||
{
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
if (e->dle_list == NULL) {
|
||||
DLAddTail(&m_list, e);
|
||||
void DllistWithLock::AddTail(Dlelem* e) {
|
||||
START_CRIT_SECTION(); // start critical section
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
if (e->dle_list == NULL) { // if e is not in list
|
||||
DLAddTail(&m_list, e); // add e to list
|
||||
}
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
}
|
||||
|
||||
Dlelem* DllistWithLock::RemoveHead()
|
||||
{
|
||||
Dlelem* head = NULL;
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
head = DLRemHead(&m_list);
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
return head;
|
||||
Dlelem* DllistWithLock::RemoveHead() {
|
||||
Dlelem* head = NULL; // head pointer
|
||||
START_CRIT_SECTION(); // start critical section
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
head = DLRemHead(&m_list); // remove head from list
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
return head; // return head pointer
|
||||
}
|
||||
|
||||
Dlelem* DllistWithLock::RemoveTail()
|
||||
{
|
||||
Dlelem* head = NULL;
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
head = DLRemTail(&m_list);
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
return head;
|
||||
Dlelem* DllistWithLock::RemoveTail() {
|
||||
Dlelem* head = NULL; // head pointer
|
||||
START_CRIT_SECTION(); // start critical section
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
head = DLRemTail(&m_list); // remove tail from list
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
return head; // return head pointer
|
||||
}
|
||||
|
||||
bool DllistWithLock::IsEmpty()
|
||||
{
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
bool ret = DLIsNIL(&m_list);
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
return ret;
|
||||
bool DllistWithLock::IsEmpty() {
|
||||
START_CRIT_SECTION(); // start critical section
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
bool ret = DLIsNIL(&m_list); // judge whether list is empty
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
return ret; // return result
|
||||
}
|
||||
|
||||
Dlelem* DllistWithLock::GetHead()
|
||||
{
|
||||
Dlelem* head = NULL;
|
||||
head = m_list.dll_head;
|
||||
return head;
|
||||
Dlelem* DllistWithLock::GetHead() {
|
||||
Dlelem* head = NULL; // head pointer
|
||||
head = m_list.dll_head; // get head pointer
|
||||
return head; // return head pointer
|
||||
}
|
||||
|
||||
void DllistWithLock::GetLock()
|
||||
{
|
||||
START_CRIT_SECTION();
|
||||
SpinLockAcquire(&(m_lock));
|
||||
void DllistWithLock::GetLock() {
|
||||
START_CRIT_SECTION(); // start critical section
|
||||
SpinLockAcquire(&(m_lock)); // get lock
|
||||
}
|
||||
|
||||
Dlelem* DllistWithLock::RemoveHeadNoLock()
|
||||
{
|
||||
Dlelem* head = DLRemHead(&m_list);
|
||||
return head;
|
||||
Dlelem* DllistWithLock::RemoveHeadNoLock() {
|
||||
Dlelem* head = DLRemHead(&m_list); // remove head from list
|
||||
return head; // return head pointer
|
||||
}
|
||||
|
||||
void DllistWithLock::ReleaseLock()
|
||||
{
|
||||
SpinLockRelease(&(m_lock));
|
||||
END_CRIT_SECTION();
|
||||
void DllistWithLock::ReleaseLock() {
|
||||
SpinLockRelease(&(m_lock)); // release lock
|
||||
END_CRIT_SECTION(); // end critical section
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,8 +21,33 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*In artificial intelligence, it is not so easy to accurately and easily identify and output the image/voice
|
||||
we expect to output in the face of a large number of data/materials input by users. Therefore, the algorithm
|
||||
is particularly important. The algorithm is what we call a model.
|
||||
|
||||
Of course, in addition to the core recognition engine, the content of the algorithm also includes various
|
||||
configuration parameters, such as bit rate, sampling rate, timbre, tone, pitch, audio, cadence, dialect, noise
|
||||
and other messy parameters. In a mature recognition engine, the core content generally does not change
|
||||
frequently. In order to achieve the goal of "successful recognition", we can only adjust the configuration
|
||||
parameters. For different inputs, we will configure different parameter values, and finally take a group of
|
||||
parameter values with balanced parties and high recognition rate in the result statistics. This group of
|
||||
parameter values is the result we get after training. This is the training process, also called model training.
|
||||
|
||||
So:
|
||||
Model = algorithm
|
||||
Training = the process of finding out the optimal configuration parameters by using big data to
|
||||
achieve the goal of high recognition rate.
|
||||
Results = Determine the parameter configuration and achieve high recognition rate.
|
||||
*/
|
||||
|
||||
#include "db4ai/db4ai_api.h"
|
||||
|
||||
/*Function: model_ Fit
|
||||
Formal parameters: (const char * name, AlgorithmML algorithm, const Hyperparameter * hyperparameters, int nhyperp,
|
||||
Oid * typid, bool * typbyval, int16 * typlen, int ncolumns, callback_ Ml_ Fetch fetch,
|
||||
Callback_ Ml_ Rescan rescan, void * callback_ Data)
|
||||
Return value: Model*
|
||||
model training*/
|
||||
Model *model_fit(const char *name, AlgorithmML algorithm, const Hyperparameter *hyperparameters, int nhyperp,
|
||||
Oid *typid, bool *typbyval, int16 *typlen, int ncolumns, callback_ml_fetch fetch,
|
||||
callback_ml_rescan rescan, void *callback_data)
|
||||
|
|
@ -100,6 +125,10 @@ ModelPredictor model_prepare_predict(const Model* model)
|
|||
pred->predictor = pred->palgo->prepare_predict(pred->palgo, &model->data, model->return_type);
|
||||
return (ModelPredictor)pred;
|
||||
}
|
||||
/*Function: model_ Predict
|
||||
Formal parameters: (ModelPredictor predictor, Datum * values, bool * isnull, Oid * typid, int num_columns)
|
||||
Return value: Datum
|
||||
model prediction*/
|
||||
|
||||
Datum model_predict(ModelPredictor predictor, Datum *values, bool *isnull, Oid *typid, int num_columns)
|
||||
{
|
||||
|
|
@ -107,11 +136,18 @@ Datum model_predict(ModelPredictor predictor, Datum *values, bool *isnull, Oid *
|
|||
return pred->palgo->predict(pred->palgo, pred->predictor, values, isnull, typid, num_columns);
|
||||
}
|
||||
|
||||
/*Function: model_ Store
|
||||
Parameter: (const Model * model)
|
||||
Return value: None
|
||||
Model Storage*/
|
||||
void model_store(const Model *model)
|
||||
{
|
||||
store_model(model);
|
||||
}
|
||||
|
||||
/*Function: model_ Load
|
||||
Formal parameter: (const char * modelname)
|
||||
Return value: Model*
|
||||
Model loading*/
|
||||
const Model *model_load(const char *model_name)
|
||||
{
|
||||
return get_model(model_name, false);
|
||||
|
|
|
|||
|
|
@ -37,6 +37,13 @@ IDENTIFICATION
|
|||
#endif
|
||||
|
||||
|
||||
/*Euclidean distance: the distance between two points,
|
||||
that is, the distance we usually calculate.
|
||||
Manhattan distance: the sum of absolute
|
||||
wheelbase of two points in the standard coordinate system.
|
||||
Chebyshev distance: the maximum value of the
|
||||
numerical difference of each coordinate.*/
|
||||
|
||||
/*
|
||||
* L1 distance (Manhattan)
|
||||
* We sum using cascaded summation
|
||||
|
|
@ -44,6 +51,14 @@ IDENTIFICATION
|
|||
* are not available or for the the case that the dimension is not a multiple
|
||||
* of the width of the registers
|
||||
*/
|
||||
|
||||
/*Vectorization refers to using an array instead of a scalar
|
||||
to manipulate each element in the array.*/
|
||||
|
||||
/*Function: l1_ Non_ Vectorized
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Calculate Manhattan distance without vectorization processing*/
|
||||
static force_inline double l1_non_vectorized(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
double term = 0.;
|
||||
|
|
@ -73,6 +88,11 @@ static force_inline double l1_non_vectorized(double const * p, double const * q,
|
|||
* This version is vectorized using SSE or NEON and is used in case only 128-bit
|
||||
* vectorized instructions are available
|
||||
*/
|
||||
|
||||
/*Function: l1_ 128
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Calculate Manhattan distance without vectorization processing*/
|
||||
static double l1_128(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
if (unlikely(dimension == 0))
|
||||
|
|
@ -179,6 +199,11 @@ static double l1_128(double const * p, double const * q, uint32_t const dimensio
|
|||
* are not available or for the the case that the dimension is not a multiple
|
||||
* of the width of the registers
|
||||
*/
|
||||
|
||||
/*Function: l2_ Squared_ Non_ Vectorized
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Calculating Euclidean Distance Without Vectorization*/
|
||||
static force_inline double l2_squared_non_vectorized(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
double subtraction = 0.;
|
||||
|
|
@ -212,6 +237,11 @@ static force_inline double l2_squared_non_vectorized(double const * p, double co
|
|||
* This version is vectorized using SSE or NEON and is used in case only 128-bit
|
||||
* vectorized instructions are available
|
||||
*/
|
||||
|
||||
/*Function: l2_ Squared_128
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Vectorization processing for calculating Euclidean distance*/
|
||||
static double l2_squared_128(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
if (unlikely(dimension == 0))
|
||||
|
|
@ -307,6 +337,12 @@ static double l2_squared_128(double const * p, double const * q, uint32_t const
|
|||
|
||||
#endif
|
||||
|
||||
/*
|
||||
Function: linf_ Non_ Vectorized
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Calculating Chebyshev Distance through Non Vectorization Processing
|
||||
*/
|
||||
/*
|
||||
* L infinity distance (Chebyshev)
|
||||
* This version is unvectorized and is used in case vectorized instructions
|
||||
|
|
@ -336,6 +372,13 @@ static force_inline double linf_non_vectorized(double const * p, double const *
|
|||
}
|
||||
|
||||
#if (defined(__x86_64__) && defined(__SSE3__)) || (defined(__aarch64__) && defined(__ARM_NEON))
|
||||
/*
|
||||
Function: linf_ one hundred and twenty-eight
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Vectorization processing for calculating Chebyshev distance
|
||||
*/
|
||||
|
||||
/*
|
||||
* L infinity distance (Chebyshev)
|
||||
* This version is vectorized using SSE or NEON and is used in case only 128-bit
|
||||
|
|
@ -420,6 +463,11 @@ static double linf_128(double const * p, double const * q, uint32_t const dimens
|
|||
|
||||
#endif
|
||||
|
||||
/*Function: l1
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Automatic vectorization processing for calculating Manhattan distance*/
|
||||
|
||||
/*
|
||||
* L1 distance (Manhattan)
|
||||
* This is the main function. It will be automatically vectorized
|
||||
|
|
@ -446,6 +494,11 @@ double l1(double const * p, double const * q, uint32_t const dimension)
|
|||
* This is the main function. It will be automatically vectorized
|
||||
* if possible
|
||||
*/
|
||||
|
||||
/*Function: l2_ Squared
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Automatic vectorization processing for calculating Euclidean distance*/
|
||||
double l2_squared(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
if (unlikely(dimension == 0))
|
||||
|
|
@ -467,6 +520,11 @@ double l2_squared(double const * p, double const * q, uint32_t const dimension)
|
|||
* This is the main function. It will be automatically vectorized
|
||||
* if possible
|
||||
*/
|
||||
|
||||
/*Function: l2_ Squared
|
||||
Formal parameters: (double const * p, double const * q, uint32_t const dimension)
|
||||
Return value: double
|
||||
Automatic vectorization processing for calculating Euclidean distance*/
|
||||
double l2(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
if (unlikely(dimension == 0))
|
||||
|
|
@ -488,6 +546,12 @@ double l2(double const * p, double const * q, uint32_t const dimension)
|
|||
* This is the main function. It will be automatically vectorized
|
||||
* if possible
|
||||
*/
|
||||
|
||||
/*Function: linf
|
||||
Parameter: (double const * p, double const * q, uint32 _ t const dimension)
|
||||
Return value: double
|
||||
|
||||
Calculation of Chebyshev distance by automatic vectorization processing*/
|
||||
double linf(double const * p, double const * q, uint32_t const dimension)
|
||||
{
|
||||
if (unlikely(dimension == 0))
|
||||
|
|
|
|||
|
|
@ -22,6 +22,12 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*Gradient Descent is a commonly used optimization algorithm, which is used to solve
|
||||
the minimum value of the objective function. It is an iterative algorithm. In each iteration,
|
||||
the gradient (or approximate gradient) of the objective function is calculated, and then the
|
||||
parameters are updated along the negative gradient direction until the minimum value that
|
||||
meets the conditions is reached.*/
|
||||
|
||||
#include "postgres.h"
|
||||
#include "executor/executor.h"
|
||||
#include "utils/builtins.h"
|
||||
|
|
|
|||
|
|
@ -21,6 +21,15 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*Linear regression is a regression analysis that uses the least square function called linear
|
||||
regression equation to model the relationship between one or more independent variables and dependent
|
||||
variables. Its expression form is y = w'x+e, where e is the normal distribution with the average value of 0.
|
||||
In regression analysis, only one independent variable and one dependent variable are included, and the
|
||||
relationship between them can be approximately expressed by a straight line. This regression analysis is
|
||||
called unary linear regression analysis. If regression analysis includes two or more independent variables,
|
||||
and there is a linear relationship between dependent variables and independent variables, it is called
|
||||
multivariate linear regression analysis.*/
|
||||
|
||||
#include "db4ai/gd.h"
|
||||
|
||||
static void linear_reg_gradients(GradientsConfig *cfg)
|
||||
|
|
|
|||
|
|
@ -21,6 +21,10 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*Logistic regression, also known as logistic regression analysis, is mainly used in epidemiology.
|
||||
The common situation is to explore the risk factors of a disease and predict the probability
|
||||
of a disease according to the risk factors.*/
|
||||
|
||||
#include "db4ai/gd.h"
|
||||
|
||||
static void logreg_gradients(GradientsConfig *cfg)
|
||||
|
|
|
|||
|
|
@ -22,6 +22,14 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*Principal component analysis is a mathematical transformation method,
|
||||
which transforms a given set of related variables into another set of unrelated
|
||||
variables through linear transformation, and these new variables are arranged
|
||||
in the order of decreasing variance. In mathematical transformation, the total
|
||||
variance of variables is kept constant, so that the first variable has the largest
|
||||
variance, which is called first principal component, and the second variable has
|
||||
the second largest variance and is not related to the first variable, which is called
|
||||
the second principal component. By analogy, I variables have I principal components.*/
|
||||
#include "db4ai/gd.h"
|
||||
#include "db4ai/db4ai_cpu.h"
|
||||
#include "db4ai/fp_ops.h"
|
||||
|
|
|
|||
|
|
@ -23,6 +23,10 @@
|
|||
|
||||
#include "db4ai/gd.h"
|
||||
#include "db4ai/kernel.h"
|
||||
/*Support vector machine (SVM), because of its English name, is generally referred to as SVM. Generally speaking,
|
||||
it is a two-class classification model. Its basic model is defined as a linear classifier with the largest interval in the
|
||||
feature space, and its learning strategy is to maximize the interval, which can eventually be transformed into the
|
||||
solution of a convex quadratic programming problem.*/
|
||||
|
||||
static void svmc_gradients(GradientsConfig *cfg)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -21,6 +21,16 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*In the direction of DB4AI, the database can avoid the problem of data handling
|
||||
when users perform AI calculation by integrating AI capabilities. Different from other
|
||||
DB4AI frameworks, the native framework of openGauss open source is to complete
|
||||
the AI calculation in the database by adding AI operators.*/
|
||||
|
||||
/*In the context of machine learning, superparameters are parameters whose values are
|
||||
set before the learning process begins, rather than parameter data obtained through training.
|
||||
Usually, it is necessary to optimize the hyperparameters and choose a set of optimal hyperparameters
|
||||
for the learning machine to improve the learning performance and effect.*/
|
||||
|
||||
#include "db4ai/hyperparameter_validation.h"
|
||||
|
||||
#include "db4ai/aifuncs.h"
|
||||
|
|
@ -28,6 +38,8 @@
|
|||
#include "nodes/plannodes.h"
|
||||
#include "db4ai/db4ai_api.h"
|
||||
|
||||
//Used to add, delete, check and modify the value of the superparameter.
|
||||
//
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
|
@ -37,13 +49,22 @@
|
|||
is_supervised \
|
||||
}
|
||||
|
||||
|
||||
/*Function: get_ Hyperparameter_ Definitions
|
||||
Parameter: (AlgorithmML algorithm, int32_t * result_size)
|
||||
Return: HyperparameterDefinition*
|
||||
Enter the algorithm and number of result digits to return the definition of hyperparameters for this model.*/
|
||||
|
||||
const HyperparameterDefinition* get_hyperparameter_definitions(AlgorithmML algorithm, int32_t *result_size)
|
||||
{
|
||||
AlgorithmAPI* api = get_algorithm_api(algorithm);
|
||||
return api->get_hyperparameters_definitions(api, result_size);
|
||||
}
|
||||
|
||||
/*Function: get_ Algorithm_ Configuration
|
||||
Parameter: AlgorithmML algorithm
|
||||
Return: AlgorithmConfiguration*
|
||||
Determine if the algorithm exists.*/
|
||||
|
||||
AlgorithmConfiguration *get_algorithm_configuration(AlgorithmML algorithm)
|
||||
{
|
||||
switch (algorithm) {
|
||||
|
|
@ -55,6 +76,16 @@ AlgorithmConfiguration *get_algorithm_configuration(AlgorithmML algorithm)
|
|||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
Function: find_hyperparameter_definition
|
||||
|
||||
Parameter:(const HyperparameterDefinition definitions[],
|
||||
int32_t definitions_size,
|
||||
const char *hyperparameter_name)
|
||||
|
||||
Return:HyperparameterDefinition *
|
||||
Enter the model name and return the model definition.
|
||||
*/
|
||||
const HyperparameterDefinition *find_hyperparameter_definition(const HyperparameterDefinition definitions[],
|
||||
int32_t definitions_size,
|
||||
const char *hyperparameter_name)
|
||||
|
|
@ -68,6 +99,14 @@ const HyperparameterDefinition *find_hyperparameter_definition(const Hyperparame
|
|||
}
|
||||
|
||||
// Set the value of a hyperparameter structure
|
||||
/*
|
||||
Function: set_ Hyperparameter_ Datum
|
||||
Parameter: (Hyperparameter * hyperp, Oid type, Datum value)
|
||||
Return: None
|
||||
Set the hyperparameter type and value, which is called by the system.
|
||||
An exception is thrown if there is no super parameter.
|
||||
*/
|
||||
|
||||
static void set_hyperparameter_datum(Hyperparameter *hyperp, Oid type, Datum value)
|
||||
{
|
||||
if (type == ANYENUMOID) { // Outside of hyperparameter module, treat them as strings
|
||||
|
|
@ -80,6 +119,14 @@ static void set_hyperparameter_datum(Hyperparameter *hyperp, Oid type, Datum val
|
|||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Function: add_model_hyperparameter
|
||||
Parameter: (List *hyperparameters, MemoryContext memcxt, const char *name, Oid type,
|
||||
Datum value)
|
||||
Return: List *
|
||||
Adding hyperparameters to the model
|
||||
*/
|
||||
|
||||
static List *add_model_hyperparameter(List *hyperparameters, MemoryContext memcxt, const char *name, Oid type,
|
||||
Datum value)
|
||||
{
|
||||
|
|
@ -93,7 +140,14 @@ static List *add_model_hyperparameter(List *hyperparameters, MemoryContext memcx
|
|||
|
||||
return hyperparameters;
|
||||
}
|
||||
|
||||
/*
|
||||
Function: update_model_hyperparameter
|
||||
Parameter: (MemoryContext memcxt, List *hyperparameters, const char *name, Oid type, Datum value)
|
||||
Return:None
|
||||
update hyperparameters to the model
|
||||
*/
|
||||
|
||||
|
||||
void update_model_hyperparameter(MemoryContext memcxt, List *hyperparameters, const char *name, Oid type, Datum value)
|
||||
{
|
||||
MemoryContext old_context = MemoryContextSwitchTo(memcxt);
|
||||
|
|
@ -108,12 +162,20 @@ void update_model_hyperparameter(MemoryContext memcxt, List *hyperparameters, co
|
|||
MemoryContextSwitchTo(old_context);
|
||||
}
|
||||
|
||||
|
||||
/* inline change bool to str*/
|
||||
inline const char *bool_to_str(bool value)
|
||||
{
|
||||
return value ? "TRUE" : "FALSE";
|
||||
}
|
||||
|
||||
/*Function: ereport_ Hyperparameter
|
||||
|
||||
Formal parameters: (int level, const char * name, Datum value, Oid type)
|
||||
|
||||
Return value: None
|
||||
|
||||
Display model hyperparameters*/
|
||||
|
||||
static void ereport_hyperparameter(int level, const char *name, Datum value, Oid type)
|
||||
{
|
||||
switch (type) {
|
||||
|
|
@ -214,6 +276,15 @@ static Datum get_hyperparameter(const HyperparameterDefinition *definition, void
|
|||
|
||||
|
||||
// Set hyperparameter in hyperparameter struct to the givne value in the datum. Definition is used for metadata
|
||||
/*Function: set_ Hyperparameter
|
||||
|
||||
Formal parameters: (const HyperparameterDefinition * definition, Datum value, void * hyperparameter_struct)
|
||||
|
||||
Return value: None
|
||||
|
||||
Modify model hyperparameter values*/
|
||||
|
||||
|
||||
static void set_hyperparameter(const HyperparameterDefinition *definition, Datum value, void *hyperparameter_struct)
|
||||
{
|
||||
switch (definition->type) {
|
||||
|
|
@ -259,6 +330,17 @@ static void set_hyperparameter(const HyperparameterDefinition *definition, Datum
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Function: validate_ Hyperparameter_ String
|
||||
|
||||
Formal parameters: (const char * name, const char * value, const char * valid_values [],
|
||||
|
||||
Int32_ T valid_ Values_ Size)
|
||||
|
||||
Return value: None
|
||||
|
||||
Given the hyperparameter name, modify the model hyperparameter value.*/
|
||||
static void validate_hyperparameter_string(const char *name, const char *value, const char *valid_values[],
|
||||
int32_t valid_values_size)
|
||||
{
|
||||
|
|
@ -284,6 +366,11 @@ static void validate_hyperparameter_string(const char *name, const char *value,
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: validate_ Hyperparameter
|
||||
Formal parameters: (Datum value, Oid type, const HyperparameterValidation * validation, const char * name)
|
||||
Return value: None
|
||||
Make the modified hyperparameter values effective.*/
|
||||
|
||||
static void validate_hyperparameter(Datum value, Oid type, const HyperparameterValidation *validation, const char *name)
|
||||
{
|
||||
switch (type) {
|
||||
|
|
@ -354,6 +441,16 @@ static void validate_hyperparameter(Datum value, Oid type, const HyperparameterV
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: extract_ Value_ From_ Variable_ Set_ Stmt
|
||||
Parameter: (VariableSetStmt * stmt)
|
||||
Return value: Value
|
||||
Obtain modified values using preprocessing.*/
|
||||
/*STMT is a C API provided by MySQL,
|
||||
which is used to execute Prepared statements.
|
||||
Compared with the direct execution of SQL, the
|
||||
preprocessing statement has higher running
|
||||
efficiency and better security.*/
|
||||
|
||||
static Value *extract_value_from_variable_set_stmt(VariableSetStmt *stmt)
|
||||
{
|
||||
if (list_length(stmt->args) > 1) {
|
||||
|
|
@ -369,7 +466,16 @@ static Value *extract_value_from_variable_set_stmt(VariableSetStmt *stmt)
|
|||
}
|
||||
return value;
|
||||
}
|
||||
/*Datum' is one of the data types used in C language functions
|
||||
in PostgreSQL, which can represent any value in valid SQL types.
|
||||
*/
|
||||
/*Function: value_ To_ Datum
|
||||
|
||||
Formal parameters: (Value * value, Oid expected_type, const char * name)
|
||||
|
||||
Return value: Datum
|
||||
|
||||
Modify the hyperparameter value to Datum type.*/
|
||||
static Datum value_to_datum(Value *value, Oid expected_type, const char *name)
|
||||
{
|
||||
Datum result = (Datum)0;
|
||||
|
|
@ -457,6 +563,10 @@ static Datum value_to_datum(Value *value, Oid expected_type, const char *name)
|
|||
return result;
|
||||
}
|
||||
|
||||
/*Function: extract_ Datum_ From_ Variable_ Set_ Stmt
|
||||
Formal parameters: (VariableSetStmt * stmt, const HyperparameterDefinition * definition)
|
||||
Return value: Datum
|
||||
Use preprocessing to obtain and modify Datum.*/
|
||||
Datum extract_datum_from_variable_set_stmt(VariableSetStmt *stmt, const HyperparameterDefinition *definition)
|
||||
{
|
||||
Datum selected_value = (Datum)0;
|
||||
|
|
@ -470,6 +580,16 @@ Datum extract_datum_from_variable_set_stmt(VariableSetStmt *stmt, const Hyperpar
|
|||
return selected_value;
|
||||
}
|
||||
|
||||
|
||||
/*Function: configure_ Hyperparameters_ VSET
|
||||
|
||||
Formal parameters: (const HyperparameterDefinition definitions [], int32_t definitions_size,
|
||||
|
||||
List * hyperparameters, void * configuration)
|
||||
|
||||
Return value: Datum
|
||||
|
||||
Initialize hyperparameter configuration using set.*/
|
||||
void configure_hyperparameters_vset(const HyperparameterDefinition definitions[], int32_t definitions_size,
|
||||
List *hyperparameters, void *configuration)
|
||||
{
|
||||
|
|
@ -543,6 +663,16 @@ void configure_hyperparameters(const HyperparameterDefinition definitions[], int
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
/*Function: prepare_ Model_ Hyperparameters
|
||||
|
||||
Formal parameters: (const HyperparameterDefinition * definitions, int32_t definitions_size,
|
||||
|
||||
Void * hyperparameter_ Struct, MemoryContext memcxt)
|
||||
|
||||
Return value: List*
|
||||
|
||||
Prepare model hyperparameters.*/
|
||||
List *prepare_model_hyperparameters(const HyperparameterDefinition *definitions, int32_t definitions_size,
|
||||
void *hyperparameter_struct, MemoryContext memcxt)
|
||||
{
|
||||
|
|
@ -555,6 +685,17 @@ List *prepare_model_hyperparameters(const HyperparameterDefinition *definitions,
|
|||
return hyperparameters;
|
||||
}
|
||||
|
||||
/*Function: init_ Hyperparameters_ With_ Defaults
|
||||
|
||||
Formal parameters: (const HyperparameterDefinition definitions [], int32_t definitions_size,
|
||||
|
||||
Void * hyperparameter_ Struct
|
||||
|
||||
Return value: None
|
||||
|
||||
Initialize hyperparameters
|
||||
|
||||
*/
|
||||
void init_hyperparameters_with_defaults(const HyperparameterDefinition definitions[], int32_t definitions_size,
|
||||
void *hyperparameter_struct)
|
||||
{
|
||||
|
|
@ -563,6 +704,10 @@ void init_hyperparameters_with_defaults(const HyperparameterDefinition definitio
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: print_ Hyperparameters
|
||||
Formal parameters: (int level, List * hyperparameters)
|
||||
Return value: None
|
||||
Output all hyperparameter attributes*/
|
||||
void print_hyperparameters(int level, List *hyperparameters)
|
||||
{
|
||||
foreach_cell(it, hyperparameters) {
|
||||
|
|
|
|||
|
|
@ -42,6 +42,18 @@ IDENTIFICATION
|
|||
/*
|
||||
* parameters that affect k-means (hyper-parameters)
|
||||
*/
|
||||
|
||||
/*KMeans is one of the top ten algorithms in data mining.
|
||||
In data mining practice, we often apply KMeans to various
|
||||
scenarios, because it is simple in principle, easy to implement
|
||||
and suitable for various data mining scenarios.*/
|
||||
|
||||
/*The basic steps are as follows:
|
||||
1. Select k objects from the data as the initial clustering centers.
|
||||
2. Calculate the distance from each cluster object to the cluster center.
|
||||
3. Calculate each cluster center again.
|
||||
4. Calculate termination conditions*/
|
||||
|
||||
typedef struct HyperparametersKMeans {
|
||||
ModelHyperparameters mhp; // place-holder
|
||||
SeedingFunction seeding = KMEANS_RANDOM_SEED;
|
||||
|
|
@ -225,6 +237,11 @@ static bool copy_slot_coordinates_to_array(GSPoint *coordinates, ModelTuple cons
|
|||
* given a set of centroids (as a PG list) and a point, this function compute the distance to the closest
|
||||
* centroid
|
||||
*/
|
||||
|
||||
/*Function: closest_ Centroid
|
||||
Formal parameters: (List const * centroids, GSPoint const * point, uint32_t const dimension, double * distance)
|
||||
Return value: bool
|
||||
Given a set of centroids (as PG list) and a point, this function calculates the distance to the nearest point*/
|
||||
static bool closest_centroid(List const *centroids, GSPoint const *point, uint32_t const dimension, double *distance)
|
||||
{
|
||||
ListCell const *current_centroid_cell = centroids ? centroids->head : nullptr;
|
||||
|
|
@ -314,6 +331,14 @@ static bool deal_sample(bool const sample, std::mt19937_64 *prng, GSPoint *batch
|
|||
return false;
|
||||
}
|
||||
|
||||
/*Function: compute_cost_and_weights
|
||||
Parameters: (list const * centroids, GS point const * points, uint32 _ tdimension,
|
||||
uint32_t const num_slots, double *cost)
|
||||
Return value: bool
|
||||
Given a set of centroids (as a PG list) and a set of points, this function
|
||||
calculates the cost of the centroid set and their weights
|
||||
(the number of points assigned to each centroid).*/
|
||||
|
||||
/*
|
||||
* given a set of centroids (as a PG list) and a set of points, this function computes
|
||||
* the cost of the set of centroids as well as their weights (number of points assigned
|
||||
|
|
@ -366,6 +391,12 @@ force_inline static void release_batch(GSPoint *batch, uint32_t const num_slots)
|
|||
* using a sum that provides higher precision (we could provide much higher precision at the cost
|
||||
* of allocating yet another array to keep correction terms for every dimension
|
||||
*/
|
||||
/*Function: aggregate_ Point
|
||||
Formal parameters: (double * centroid_aggregation, double const * new_point,
|
||||
Uint32_ T const dimension)
|
||||
Return value: None
|
||||
Given the moving average of the centroid and new points, this will add new points to the set*/
|
||||
|
||||
force_inline static void aggregate_point(double *centroid_aggregation, double const *new_point,
|
||||
uint32_t const dimension)
|
||||
{
|
||||
|
|
@ -380,6 +411,12 @@ force_inline static void aggregate_point(double *centroid_aggregation, double co
|
|||
* we assume that all slots in the batch are non-null (guaranteed by the upper call)
|
||||
* also, that the next set of centroids has been reset previous to the very first call
|
||||
*/
|
||||
|
||||
/*Function: update_ Centroids
|
||||
Formal parameters: (KMeansStateDescription * description, GSPoint * slots, uint32_t const num_slots,
|
||||
Uint32_ T const idx_ Current_ Centroids, uint32_ T const idx_ Next_ Centroids)
|
||||
Return value: None
|
||||
Update centroid*/
|
||||
static void update_centroids(KMeansStateDescription *description, GSPoint *slots, uint32_t const num_slots,
|
||||
uint32_t const idx_current_centroids, uint32_t const idx_next_centroids)
|
||||
{
|
||||
|
|
@ -450,6 +487,13 @@ static void update_centroids(KMeansStateDescription *description, GSPoint *slots
|
|||
/*
|
||||
* updates the minimum bounding box to contain the new given point
|
||||
*/
|
||||
/*Function: update_ Centroids
|
||||
Formal parameters: (double * const bbox_min, double * const bbox_max, double const * point,
|
||||
Uint32_ T const dimension)
|
||||
Return value: None
|
||||
Update the minimum bounding box to include the new given point*/
|
||||
|
||||
|
||||
force_inline static void update_bbox(double *const bbox_min, double *const bbox_max, double const *point,
|
||||
uint32_t const dimension)
|
||||
{
|
||||
|
|
@ -743,6 +787,11 @@ static List *one_data_pass(TrainModelState *pstate, KMeansStateDescription *stat
|
|||
/*
|
||||
* this sets the weights of a set of candidates to 1 (every point is the centroid of itself)
|
||||
*/
|
||||
/*Function: reset_ Weights
|
||||
Formal parameters: (List const * centroids)
|
||||
Return value: None
|
||||
Initialize weights (each point has a centroid of 1)*/
|
||||
|
||||
void reset_weights(List const *centroids)
|
||||
{
|
||||
ListCell const *current_centroid_cell = centroids ? centroids->head : nullptr;
|
||||
|
|
@ -983,6 +1032,12 @@ void reset_centroids(KMeansStateDescription *description, uint32_t const idx_cen
|
|||
* this produces the centroid by dividing the aggregate by the amount of points it got assigned
|
||||
* we assumed that population > 0
|
||||
*/
|
||||
|
||||
/*Function: finish_ Centroid
|
||||
Formal parameters: (double * centroid_aggregation,
|
||||
uint32_t const dimension, double const population)
|
||||
Return value: None
|
||||
Generate centroid*/
|
||||
force_inline void finish_centroid(double *centroid_aggregation, uint32_t const dimension, double const population)
|
||||
{
|
||||
double local_correction = 0.;
|
||||
|
|
@ -992,6 +1047,11 @@ force_inline void finish_centroid(double *centroid_aggregation, uint32_t const d
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: merge_ Centroids
|
||||
Parameter: (KMeansStateDescription * description, uint32_t const idx_current_centroids,
|
||||
Uint32_ T const idx_ Next_ Centroids)
|
||||
Return value: None
|
||||
Merge centroids*/
|
||||
void merge_centroids(KMeansStateDescription *description, uint32_t const idx_current_centroids,
|
||||
uint32_t const idx_next_centroids)
|
||||
{
|
||||
|
|
@ -1416,6 +1476,11 @@ void kmeans_create_model(KMeansState *kmeans_state, Model *model)
|
|||
* 2) execute a seeding method (random++ or kmeans||) (at least one data pass but not more than 10),
|
||||
* 3) run Lloyd's algorithm (at least one data pass)
|
||||
*/
|
||||
/*Function: kmeans_ Run
|
||||
Formal parameters: (AlgorithmAPI * self, TrainModelState * pstate, Model * * models)
|
||||
Return value: None
|
||||
Run kmeans until convergence.*/
|
||||
|
||||
static void kmeans_run(AlgorithmAPI *self, TrainModelState *pstate, Model **models)
|
||||
{
|
||||
/*
|
||||
|
|
|
|||
|
|
@ -21,10 +21,23 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*Matrix refers to a set of complex numbers or real numbers arranged in a rectangular array in mathematics.
|
||||
It originated from the square matrix composed of coefficients and constants of equations. It was first proposed
|
||||
by the 19th century British mathematician Kelly. It is a common tool in advanced algebra, and its operation is
|
||||
an important problem in the field of numerical analysis. Decomposition of a matrix into a combination of simple
|
||||
matrices can simplify the operation of the matrix in theory and practical application.
|
||||
|
||||
For a matrix, at least the following operations should be included: addition, multiplication, transposition, eigenvalue
|
||||
calculation, and for a square matrix, determinant calculation is also required.*/
|
||||
#include "db4ai/matrix.h"
|
||||
|
||||
#define MATRIX_LIMITED_OUTPUT 30
|
||||
|
||||
|
||||
/*Function: void matrix_ Init_ Random_ Gaussian
|
||||
Formal parameters: (Matrix * matrix, int rows, int columns, float8 mu, float8 sigma, int seed)
|
||||
Return: None
|
||||
Production random Gaussian matrix*/
|
||||
// using Box-Muller implementation
|
||||
void matrix_init_random_gaussian(Matrix *matrix, int rows, int columns, float8 mu, float8 sigma, int seed)
|
||||
{
|
||||
|
|
@ -52,12 +65,20 @@ void matrix_init_random_gaussian(Matrix *matrix, int rows, int columns, float8 m
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: matrix_ Init_ Kernel_ Gaussian
|
||||
Formal parameters: (int features, int components, float8 gamma, int seed, Matrix * weights, Matrix * offsets)
|
||||
Return: None
|
||||
Initialize a matrix using a specified number*/
|
||||
void matrix_init_kernel_gaussian(int features, int components, float8 gamma, int seed, Matrix *weights, Matrix *offsets)
|
||||
{
|
||||
matrix_init_random_gaussian(weights, features, components, 0.0, sqrt(2.0 * gamma), seed);
|
||||
matrix_init_random_uniform(offsets, components, 1, 0.0, 2.0 * M_PI, seed+1);
|
||||
}
|
||||
|
||||
/*Function: matrix_ Transform_ Kernel_ Gaussian
|
||||
Formal parameters: (const Matrix * input, const Matrix * weights, const Matrix * offsets, Matrix * output)
|
||||
Return: None
|
||||
Matrix transpose*/
|
||||
void matrix_transform_kernel_gaussian(const Matrix *input, const Matrix *weights, const Matrix *offsets, Matrix *output)
|
||||
{
|
||||
int components = weights->columns;
|
||||
|
|
@ -83,6 +104,10 @@ void matrix_transform_kernel_gaussian(const Matrix *input, const Matrix *weights
|
|||
matrix_mult_scalar(output, sqrt(2.0 / components));
|
||||
}
|
||||
|
||||
/*Function: matrix_ Init_ Random_ Uniform
|
||||
Formal parameters: (Matrix * matrix, int rows, int columns, float8 min, float8 max, int seed)
|
||||
Return: None
|
||||
Initializing a matrix using random floating-point numbers*/
|
||||
void matrix_init_random_uniform(Matrix *matrix, int rows, int columns, float8 min, float8 max, int seed)
|
||||
{
|
||||
Assert(min < max);
|
||||
|
|
@ -101,7 +126,10 @@ void matrix_init_random_uniform(Matrix *matrix, int rows, int columns, float8 mi
|
|||
*pd++ = min + range * u;
|
||||
}
|
||||
}
|
||||
|
||||
/*Function: matrix_ Init_ Random_ Bernoulli
|
||||
Formal parameters: (Matrix * matrix, int rows, int columns, float8 p, float8 min, float8 max, int seed)
|
||||
Return: None
|
||||
Generate Random Bernoulli Matrix*/
|
||||
void matrix_init_random_bernoulli(Matrix *matrix, int rows, int columns, float8 p, float8 min, float8 max, int seed)
|
||||
{
|
||||
matrix_init(matrix, rows, columns);
|
||||
|
|
@ -118,6 +146,11 @@ void matrix_init_random_bernoulli(Matrix *matrix, int rows, int columns, float8
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: matrix_ Init_ Kernel_ Polynomial
|
||||
Formal parameters: (int features, int components, int degree, float8 coef0, int seed, Matrix * weights,
|
||||
Matrix * coefs)
|
||||
Return: int*
|
||||
Initialize a polynomial matrix using a specified number*/
|
||||
int *matrix_init_kernel_polynomial(int features, int components, int degree, float8 coef0, int seed, Matrix *weights,
|
||||
Matrix *coefs)
|
||||
{
|
||||
|
|
@ -152,6 +185,11 @@ int *matrix_init_kernel_polynomial(int features, int components, int degree, flo
|
|||
return pcomponents;
|
||||
}
|
||||
|
||||
/*Function: matrix_ Transform_ Kernel_ Polynomial
|
||||
Formal parameters: (const Matrix * input, int ncomponents, int * components, const Matrix * weights,
|
||||
Const Matrix * coefficients, Matrix * output)
|
||||
Return: None
|
||||
Polynomial matrix transpose*/
|
||||
void matrix_transform_kernel_polynomial(const Matrix *input, int ncomponents, int *components, const Matrix *weights,
|
||||
const Matrix *coefficients, Matrix *output)
|
||||
{
|
||||
|
|
@ -177,6 +215,10 @@ void matrix_transform_kernel_polynomial(const Matrix *input, int ncomponents, in
|
|||
matrix_mult_scalar(output, sqrt(1.0 / output->rows));
|
||||
}
|
||||
|
||||
/*Function: matrix_ Mult
|
||||
Formal parameters: (const Matrix * matrix1, const Matrix * matrix2, Matrix * result)
|
||||
Return value: None
|
||||
matrix multiplication*/
|
||||
void matrix_mult(const Matrix *matrix1, const Matrix *matrix2, Matrix *result)
|
||||
{
|
||||
Assert(matrix1 != nullptr);
|
||||
|
|
@ -205,6 +247,10 @@ void matrix_mult(const Matrix *matrix1, const Matrix *matrix2, Matrix *result)
|
|||
}
|
||||
}
|
||||
|
||||
/*Function: matrix_ Print
|
||||
Formal parameters: (const Matrix * matrix, StringInfo buf, bool full)
|
||||
Return value: None
|
||||
Print Matrix*/
|
||||
void matrix_print(const Matrix *matrix, StringInfo buf, bool full)
|
||||
{
|
||||
Assert(matrix != nullptr);
|
||||
|
|
@ -245,6 +291,24 @@ void matrix_print(const Matrix *matrix, StringInfo buf, bool full)
|
|||
appendStringInfoChar(buf, ']');
|
||||
}
|
||||
|
||||
/*Function: elog_ Matrix
|
||||
Formal parameters: (int level, const char * msg, const matrix * matrix)
|
||||
Return value: None
|
||||
Matrix error*/
|
||||
/*elog is an old mode that can be equivalent to the ereport mode.
|
||||
You can see that it provides level and the error level is the same,
|
||||
but it does not provide errcode. As mentioned earlier, the default
|
||||
errcode is provided based on the severity level. Then the message
|
||||
is passed through an auxiliary function errmsg_ Internal() goes to
|
||||
show it, and the process is different from the errmsg in ereport mentioned
|
||||
earlier. errmsg() is set according to regional settings, such as it can be
|
||||
translated into the language of the corresponding country, such as Chinese.
|
||||
In fact, errmsg_ Internal() is a language that is not limited by translation and
|
||||
can automatically print out the original language.
|
||||
Why should we keep this old pattern? Because it is concise enough, when
|
||||
there are some internal errors, such as internal errors in the PG kernel, these
|
||||
errors are not actually displayed to the user and are not of interest to the user.
|
||||
This concise mode can be used for printing, which is very convenient and has been preserved.*/
|
||||
void elog_matrix(int elevel, const char *msg, const Matrix *matrix)
|
||||
{
|
||||
if (is_errmodule_enable(elevel, MOD_DB4AI)) {
|
||||
|
|
|
|||
|
|
@ -40,6 +40,20 @@
|
|||
double total_exec_time = 0.0;
|
||||
struct timespec exec_start_time, exec_end_time;
|
||||
|
||||
/*XGBoost provides gradient lifting tree (also called GBDT, GBM), which
|
||||
can solve many data science problems quickly and accurately. The same
|
||||
code can run in major distributed environments (Apache Hadoop, Apache
|
||||
Spark, Apache Flink). System optimization: parallel computing: supporting
|
||||
parallel computing. Tree pruning: use greedy algorithm to choose the best
|
||||
splitting point and then start pruning. Hardware optimization: effective use
|
||||
of hardware resources. Algorithm addition: regularization: preventing over-fitting.
|
||||
Sparse consciousness: automatically "learn" the best missing value according to
|
||||
the training loss and deal with different types of sparse patterns in the data more
|
||||
effectively. Weighted quantile sketch: Using the distributed weighted quantile sketch
|
||||
algorithm, the optimal split point in the weighted data set can be found effectively.
|
||||
Cross-validation: Each iteration has a built-in cross-validation method.*/
|
||||
|
||||
|
||||
#define XGBOOST_LIB_NAME "libxgboost.so"
|
||||
|
||||
typedef const int (*XGBoosterSetParam_Sym)(BoosterHandle handle, const char *name, const char *value);
|
||||
|
|
@ -430,6 +444,10 @@ void setup_xg_chunk(xg_data_t &xg_data)
|
|||
/*
|
||||
* this function initializes the algorithm
|
||||
*/
|
||||
/*Function: xgboost_ Create
|
||||
Parameter: (AlgorithmAPI * self, const TrainModel * pnode)
|
||||
Return value: TrainModelState*
|
||||
Create xgboost*/
|
||||
static TrainModelState *xgboost_create(AlgorithmAPI *self, const TrainModel *pnode)
|
||||
{
|
||||
if (pnode->configurations != 1)
|
||||
|
|
@ -449,6 +467,11 @@ static TrainModelState *xgboost_create(AlgorithmAPI *self, const TrainModel *pno
|
|||
* chunk.
|
||||
* ----------------------------------------------------------------
|
||||
*/
|
||||
/*Function: trainXG
|
||||
Formal parameters: (AlgorithmAPI * alg, const HyperparamsXGBoost * xg_hyp, xg_data_t * chunk, const int n_tuples,
|
||||
Bool first_ Call=true)
|
||||
Return value: None
|
||||
Training xgboost*/
|
||||
void trainXG(AlgorithmAPI *alg, const HyperparamsXGBoost *xg_hyp, xg_data_t *chunk, const int n_tuples,
|
||||
bool first_call = true)
|
||||
{
|
||||
|
|
@ -714,6 +737,10 @@ ModelPredictor xgboost_predict_prepare(AlgorithmAPI *, SerializedModel const *mo
|
|||
|
||||
return reinterpret_cast<ModelPredictor>(xgboostm);
|
||||
}
|
||||
/*Function: xgboost_ Predict
|
||||
Formal parameters: (AlgorithmAPI * self, TrainModelState * pstate, Model * * models)
|
||||
Return value: Datum
|
||||
Using xgboost for prediction*/
|
||||
|
||||
Datum xgboost_predict(AlgorithmAPI *, ModelPredictor model, Datum *values, bool *isnull, Oid *types, int ncolumns)
|
||||
{
|
||||
|
|
@ -752,6 +779,12 @@ Datum xgboost_predict(AlgorithmAPI *, ModelPredictor model, Datum *values, bool
|
|||
/*
|
||||
* used in EXPLAIN MODEL
|
||||
*/
|
||||
|
||||
/*Function: xgboost_ Explain
|
||||
Parameter: (AlgorithmAPI * self, SerializedModel const * model, Oid return_type)
|
||||
Return value: List
|
||||
Explain xgboost*/
|
||||
|
||||
List *xgboost_explain(AlgorithmAPI *self, SerializedModel const *model, Oid return_type)
|
||||
{
|
||||
if (unlikely(!model))
|
||||
|
|
|
|||
|
|
@ -17,13 +17,30 @@
|
|||
*
|
||||
* -------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
In PG database, if you check whether an index contributes to one or more queries,
|
||||
HypoPG can play a key role. It is an extension of postgresql, which allows you to create
|
||||
virtual indexes and observe whether the optimizer is used. Therefore, you can provide methods
|
||||
for which queries need to be optimized and which indexes you want to try. So for the average user,
|
||||
how to better judge whether indexing is effective or not? Virtual index is a very useful thing, with no
|
||||
side effects. It is just a virtual index. After establishing a virtual index, you can check the COST estimate
|
||||
after adding the index through EXPLAIN to judge whether the cost will be reduced. In addition, the hypothetica
|
||||
l index HypoPG will create is not stored in any directory, but in the connection private memory. Therefore, it
|
||||
will not inflate any tables, nor will it affect any concurrent connections. Because it is assumed that indexes
|
||||
don't really exist, HypoPG ensures that they will only be used with a simple EXPLAIN statement (no ANALYZE option).
|
||||
|
||||
Virtual index does not occupy space, and can be used to evaluate the performance of sql query conveniently,
|
||||
which helps us to understand the effect of query optimization.
|
||||
*/
|
||||
#include <unistd.h>
|
||||
#include <math.h>
|
||||
#include "postgres.h"
|
||||
#include "fmgr.h"
|
||||
#include "funcapi.h"
|
||||
#include "miscadmin.h"
|
||||
#include "access/gist.h"
|
||||
#include "access/gist.h" /*Storage index*/
|
||||
#include "access/nbtree.h"
|
||||
#include "access/reloptions.h"
|
||||
#include "access/spgist.h"
|
||||
|
|
@ -94,6 +111,13 @@ static void hypo_injectHypotheticalIndex(PlannerInfo *root, Oid relationObjectId
|
|||
static List *get_table_indexes(Oid oid);
|
||||
static List *get_index_attrnum(Oid oid);
|
||||
|
||||
/*
|
||||
Parameter: None,
|
||||
return value: None.
|
||||
Judge whether the virtual index of the instance exists.
|
||||
If it does not exist, initialize the virtual index with
|
||||
AllocSetContextCreate () function and mark it as unexplained.
|
||||
*/
|
||||
void InitHypopg()
|
||||
{
|
||||
// init memory context
|
||||
|
|
@ -103,16 +127,30 @@ void InitHypopg()
|
|||
}
|
||||
isExplain = false;
|
||||
}
|
||||
/*
|
||||
SQLAllocConnect() allocates a connection handle and associated resources within the
|
||||
environment that is identified by the input environment handle. Call SQLGetInfo() with
|
||||
fInfoType set to SQL_ACTIVE_CONNECTIONS to query the number of connections that
|
||||
can be allocated at any one time. SQLAllocEnv() must be called before calling this function.*/
|
||||
|
||||
|
||||
/*
|
||||
* This function is used for setting prev_utility_hook to rewrite
|
||||
* standard_ProcessUtility by extension.
|
||||
Set_hypopg_prehook function:
|
||||
Parameter: ProcessUtility_hook_type func,
|
||||
return value: none.
|
||||
Function: Set prev_utility_hook, rewrite standard_ProcessUtility,
|
||||
and control the execution of specific activities in the database
|
||||
by using the hook mechanism of the database.
|
||||
|
||||
*/
|
||||
void set_hypopg_prehook(ProcessUtility_hook_type func)
|
||||
{
|
||||
prev_utility_hook = func;
|
||||
}
|
||||
|
||||
/*
|
||||
Full hook mechanism to control all kinds of activities of the database.*/
|
||||
|
||||
void hypopg_register_hook()
|
||||
{
|
||||
// register hooks
|
||||
|
|
@ -133,6 +171,16 @@ void hypopg_register_hook()
|
|||
* Wrapper around GetNewRelFileNode
|
||||
* Return a new OID for an hypothetical index.
|
||||
*/
|
||||
|
||||
/*
|
||||
Hypo_getNewOid function:
|
||||
Parameter: oid
|
||||
Return value: oid
|
||||
Open the relationship that we want a new OID,
|
||||
now close the relationship and release the lock,
|
||||
open pg_class to get a new OID, request a new relfilenode,
|
||||
close pg_class and unlock it immediately.*/
|
||||
|
||||
static Oid hypo_getNewOid(Oid relid)
|
||||
{
|
||||
Relation pg_class;
|
||||
|
|
@ -143,7 +191,18 @@ static Oid hypo_getNewOid(Oid relid)
|
|||
|
||||
/* Open the relation on which we want a new OID */
|
||||
relation = heap_open(relid, AccessShareLock);
|
||||
|
||||
|
||||
/*In PostgreSQL, AccessShareLock is a lock type used to
|
||||
control concurrent access to database objects. It is a read
|
||||
lock that allows multiple transactions to read from the same
|
||||
object at the same time, but it prevents concurrent transactions
|
||||
from acquiring conflicting locks, such as write locks or exclusive locks.
|
||||
When a transaction obtains AccessShareLock on an object, other
|
||||
transactions can also obtain AccessShareLock on the same object.
|
||||
This means that multiple transactions can read objects at the same
|
||||
time without interfering with each other.*/
|
||||
|
||||
|
||||
reltablespace = relation->rd_rel->reltablespace;
|
||||
relpersistence = relation->rd_rel->relpersistence;
|
||||
|
||||
|
|
@ -177,6 +236,15 @@ void hypo_utility_hook(Node *parsetree, const char *queryString, ParamListInfo p
|
|||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Hypo_index_match_table function:
|
||||
|
||||
Formal parameter: hypoIndex *entry Oid relid
|
||||
|
||||
Return value: bool
|
||||
|
||||
Judge whether the virtual index and the object identifier (OID) match.
|
||||
*/
|
||||
static bool hypo_index_match_table(hypoIndex *entry, Oid relid)
|
||||
{
|
||||
/* Hypothetical index on the exact same relation, use it. */
|
||||
|
|
@ -210,6 +278,15 @@ static bool hypo_query_walker(Node *parsetree)
|
|||
}
|
||||
|
||||
/* Reset the isExplain flag after each query */
|
||||
|
||||
/*Hypo_executorEnd_hook function
|
||||
|
||||
Parameter: QueryDesc *queryDesc
|
||||
|
||||
Return value: None
|
||||
|
||||
Reset the isExplain flag after each query.*/
|
||||
|
||||
static void hypo_executorEnd_hook(QueryDesc *queryDesc)
|
||||
{
|
||||
isExplain = false;
|
||||
|
|
@ -220,6 +297,19 @@ static void hypo_executorEnd_hook(QueryDesc *queryDesc)
|
|||
standard_ExecutorEnd(queryDesc);
|
||||
}
|
||||
}
|
||||
|
||||
/*Get_table_indexes function:
|
||||
|
||||
Parameter: oid
|
||||
|
||||
Back to: list
|
||||
|
||||
Query the list corresponding to the object identifier
|
||||
|
||||
First open the specified heap to get the list of
|
||||
|
||||
the specified heap, then close the heap to return to the list.*/
|
||||
|
||||
List *get_table_indexes(Oid oid)
|
||||
{
|
||||
Relation rel = heap_open(oid, NoLock);
|
||||
|
|
@ -227,8 +317,18 @@ List *get_table_indexes(Oid oid)
|
|||
heap_close(rel, NoLock);
|
||||
return indexes;
|
||||
}
|
||||
/*Read-only here will not cause deadlock, so use NoLock lock.*/
|
||||
|
||||
/* Return the names of all the columns involved in the index. */
|
||||
|
||||
/*Get_index_attrnum function:
|
||||
|
||||
Parameter: index_oid
|
||||
|
||||
Back to: list
|
||||
|
||||
Returns the names of all columns.*/
|
||||
|
||||
List *get_index_attrnum(Oid index_oid)
|
||||
{
|
||||
HeapTuple index_tup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
|
||||
|
|
@ -427,7 +527,16 @@ static hypoIndex *hypo_newIndex(Oid relid, char *accessMethod, int nkeycolumns,
|
|||
return entry;
|
||||
}
|
||||
|
||||
/* Add an hypoIndex to hypo_index_list */
|
||||
/*
|
||||
|
||||
Hypo_addIndex function:
|
||||
|
||||
Formal parameter: *entry
|
||||
|
||||
Return: None
|
||||
|
||||
Add a virtual index to the virtual index table.*/
|
||||
|
||||
static void hypo_addIndex(hypoIndex *entry)
|
||||
{
|
||||
MemoryContext oldcontext;
|
||||
|
|
@ -444,6 +553,12 @@ static void hypo_addIndex(hypoIndex *entry)
|
|||
}
|
||||
|
||||
/*
|
||||
Hypo_index_reset function:
|
||||
|
||||
Formal parameter: none
|
||||
|
||||
Return: None
|
||||
|
||||
* Remove cleanly all hypothetical indexes by calling hypo_index_remove() on
|
||||
* each entry. hypo_index_remove() function pfree all allocated memory
|
||||
*/
|
||||
|
|
@ -495,7 +610,7 @@ static void hypo_process_attr(IndexStmt *node, hypoIndex *volatile entry, String
|
|||
int attn;
|
||||
|
||||
attn = 0;
|
||||
foreach (lc, node->indexParams) {
|
||||
foreach (lc, node->indexParams) { /*Traverse all nodes*/
|
||||
IndexElem *attribute = (IndexElem *)lfirst(lc);
|
||||
Oid atttype = InvalidOid;
|
||||
Oid opclass;
|
||||
|
|
@ -690,7 +805,7 @@ static const hypoIndex *hypo_index_store_parsetree(IndexStmt *node, const char *
|
|||
if (nkeycolumns > INDEX_MAX_KEYS) {
|
||||
elog(ERROR, "hypopg: cannot use more thant %d columns in an index", INDEX_MAX_KEYS);
|
||||
}
|
||||
|
||||
//Show basic attributes
|
||||
initStringInfo(&indexRelationName);
|
||||
appendStringInfoString(&indexRelationName, node->accessMethod);
|
||||
appendStringInfoString(&indexRelationName, "_");
|
||||
|
|
@ -761,7 +876,7 @@ static const hypoIndex *hypo_index_store_parsetree(IndexStmt *node, const char *
|
|||
pull_varattnos((Node *)entry->indexprs, 1, &indexattrs);
|
||||
pull_varattnos((Node *)entry->indpred, 1, &indexattrs);
|
||||
|
||||
for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++) {
|
||||
for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++) { //I is a negative number
|
||||
if (i != ObjectIdAttributeNumber && bms_is_member(i - FirstLowInvalidHeapAttributeNumber, indexattrs)) {
|
||||
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
||||
errmsg("hypopg: index creation on system columns is not supported")));
|
||||
|
|
@ -882,7 +997,13 @@ static bool hypo_index_remove(Oid indexid)
|
|||
return false;
|
||||
}
|
||||
|
||||
/* pfree all allocated memory for within an hypoIndex and the entry itself. */
|
||||
/*
|
||||
Hypo_index_pfree function:
|
||||
|
||||
Formal parameter: entry
|
||||
|
||||
Return: None
|
||||
pfree all allocated memory for within an hypoIndex and the entry itself. */
|
||||
static void hypo_index_pfree(hypoIndex *entry)
|
||||
{
|
||||
/* pfree all memory that has been allocated */
|
||||
|
|
@ -1166,6 +1287,13 @@ Datum hypopg_display_index(PG_FUNCTION_ARGS)
|
|||
}
|
||||
|
||||
/*
|
||||
Hypopg_create_index function:
|
||||
|
||||
Parameter: (PG_FUNCTION_ARGS)
|
||||
|
||||
Return: (Datum)
|
||||
|
||||
|
||||
* SQL wrapper to create an hypothetical index with his parsetree
|
||||
*/
|
||||
Datum hypopg_create_index(PG_FUNCTION_ARGS)
|
||||
|
|
@ -1244,6 +1372,14 @@ Datum hypopg_create_index(PG_FUNCTION_ARGS)
|
|||
}
|
||||
|
||||
/*
|
||||
|
||||
Hypopg_drop_index function:
|
||||
|
||||
Parameter: (PG_FUNCTION_ARGS)
|
||||
|
||||
Return: (Datum)
|
||||
|
||||
Delete the specified index
|
||||
* SQL wrapper to drop an hypothetical index.
|
||||
*/
|
||||
Datum hypopg_drop_index(PG_FUNCTION_ARGS)
|
||||
|
|
@ -1253,6 +1389,8 @@ Datum hypopg_drop_index(PG_FUNCTION_ARGS)
|
|||
PG_RETURN_BOOL(hypo_index_remove(indexid));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* SQL Wrapper around the hypothetical index size estimation
|
||||
*/
|
||||
|
|
@ -1472,7 +1610,14 @@ static void hypo_estimate_index(hypoIndex *entry, RelOptInfo *rel)
|
|||
}
|
||||
|
||||
/*
|
||||
* Estimate a single index's column of an hypothetical index.
|
||||
*
|
||||
Hypo_estimate_index_colsize function:
|
||||
|
||||
Parameter: (hypoIndex *entry, int col)
|
||||
|
||||
Return: (int)
|
||||
|
||||
Estimate the index column size of a virtual index.
|
||||
*/
|
||||
static int hypo_estimate_index_colsize(hypoIndex *entry, int col)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -24,6 +24,25 @@
|
|||
* -------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*Single index recommendation: it is suitable for the case of large data in the table,
|
||||
and it will not be recommended if the data is too small.
|
||||
|
||||
When there is only one query condition in where, a single index is recommended;
|
||||
if only id is in where, only id is recommended as the index; When there are multiple query conditions in where,
|
||||
multiple indexes are recommended. For example, if id and name are used as conditions in where, they are recommended
|
||||
as joint indexes together. However, if id and person_id exist
|
||||
at the same time, id is recommended by default(the reason is unknown at present).
|
||||
|
||||
When there are conditions such as order by and group by besides the where statement in the query,
|
||||
all the attributes in where, order by and group by are recommended as joint indexes.
|
||||
|
||||
When using like fuzzy query or precise query, the attribute is not indexed, and = attribute must be recommended for indexing.
|
||||
|
||||
When there are too many conditions in the query and there are more than three attributes, it is still recommended that the joint
|
||||
attributes are more than three, which will lead to too many recommended indexes, which is debatable. It is best to recommend
|
||||
the attributes in the index to be less than three. However, this may need to be learned through DRL to determine which attributes
|
||||
in a query to choose to build an index.*/
|
||||
|
||||
#include "postgres.h"
|
||||
|
||||
#include "access/tableam.h"
|
||||
|
|
@ -58,6 +77,7 @@
|
|||
#define MAX_SAMPLE_ROWS 10000 /* sampling range for executing a query */
|
||||
#define CARDINALITY_THRESHOLD 30 /* the threshold of index selection */
|
||||
|
||||
/*Some structures used for queries*/
|
||||
#define RelAttrName(__tupdesc, __attridx) (NameStr((__tupdesc)->attrs[(__attridx)]->attname))
|
||||
#define IsSameRel(_schema1, _table1, _schema2, _table2) \
|
||||
((!_schema1 || !_schema2 || strcasecmp(_schema1, _schema2) == 0) && strcasecmp(_table1, _table2) == 0)
|
||||
|
|
@ -241,17 +261,26 @@ Datum gs_index_advise(PG_FUNCTION_ARGS)
|
|||
}
|
||||
|
||||
/*
|
||||
* suggest_index
|
||||
* Parse the given query and return the suggested indexes. The suggested
|
||||
* index consists of table names and column names.
|
||||
*
|
||||
* The main steps are summarized as follows:
|
||||
* 1. Get parse tree;
|
||||
* 2. Find and parse SelectStmt structures;
|
||||
* 3. Parse 'from' and 'where' clause, and add candidate indexes for tables;
|
||||
* 4. Determine the driver table;
|
||||
* 5. Parse 'group' and 'order' clause and add candidate indexes for tables;
|
||||
* 6. Add candidate indexes for drived tables according to the 'join' conditions.
|
||||
Suggest_index function:
|
||||
|
||||
Parameter: (constchar * query _ string, _ out _ int * len)
|
||||
|
||||
Return value: SuggestedIndex
|
||||
|
||||
Function: Parse the given query and return the suggested index. This proposed index consists of table names and column names.
|
||||
The main steps are summarized as follows:
|
||||
|
||||
1. Obtain a parse tree;
|
||||
|
||||
2. Find and parse the structure of SelectStmt;
|
||||
|
||||
3. Parse the "from" and "where" clauses and add candidate indexes to the table.
|
||||
|
||||
4. Determine the driver table;
|
||||
|
||||
5. Analyze the "group" and "order" clauses and add candidate indexes to the table;
|
||||
|
||||
6. Add a candidate index for the driver table according to the "Join" condition.
|
||||
*/
|
||||
SuggestedIndex *suggest_index(const char *query_string, _out_ int *len)
|
||||
{
|
||||
|
|
@ -456,6 +485,14 @@ void get_join_condition_from_plan(Node* node, List* rtable)
|
|||
}
|
||||
}
|
||||
|
||||
/*/*Add_index function:
|
||||
|
||||
Parameter: (table cell * table, char * index _ name)
|
||||
|
||||
Return value: None.
|
||||
|
||||
Function: Add nodes to the table.*/
|
||||
|
||||
void add_index(TableCell *table, char *index_name)
|
||||
{
|
||||
IndexCell *index = (IndexCell *)palloc0(sizeof(*index));
|
||||
|
|
@ -492,6 +529,8 @@ void add_index(TableCell *table, char *index_name)
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
void get_order_condition_from_plan(Node* node)
|
||||
{
|
||||
Sort *sortopt = (Sort *)node;
|
||||
|
|
@ -535,6 +574,14 @@ void get_order_condition_from_plan(Node* node)
|
|||
}
|
||||
}
|
||||
|
||||
/*Free_global_resource function
|
||||
|
||||
Formal parameter: none
|
||||
|
||||
Return value: None
|
||||
|
||||
Role: release global resources.*/
|
||||
|
||||
void free_global_resource()
|
||||
{
|
||||
list_free(g_drived_tables);
|
||||
|
|
@ -548,7 +595,14 @@ void free_global_resource()
|
|||
g_driver_table = NULL;
|
||||
}
|
||||
|
||||
/* Search the oid of all indexes created on the table through the oid of the table,
|
||||
/*
|
||||
Get_table_indexes function:
|
||||
|
||||
Parameter: oid
|
||||
|
||||
Back to: list
|
||||
|
||||
Search the oid of all indexes created on the table through the oid of the table,
|
||||
* and return the index oid list.
|
||||
*/
|
||||
List *get_table_indexes(Oid oid)
|
||||
|
|
@ -621,7 +675,11 @@ List *get_index_attname(Oid index_oid)
|
|||
return attnames;
|
||||
}
|
||||
|
||||
// Execute an SQL statement and return its result.
|
||||
/*
|
||||
Execute_ Stmt function:
|
||||
Formal parameters: (const char * query_string, bool need_result)
|
||||
Return: StmtResult
|
||||
Execute an SQL statement and return the result.*/
|
||||
StmtResult *execute_stmt(const char *query_string, bool need_result)
|
||||
{
|
||||
int16 format = 0;
|
||||
|
|
@ -728,7 +786,14 @@ void shutdown(DestReceiver *self) {
|
|||
/* nothing */
|
||||
}
|
||||
|
||||
/* Release resources */
|
||||
/*
|
||||
Destroy function:
|
||||
|
||||
Parameter: (DestReceiver *self)
|
||||
|
||||
Return: None
|
||||
|
||||
The function frees all allocated memory.Release resources */
|
||||
void destroy(DestReceiver *self)
|
||||
{
|
||||
StmtResult *result = (StmtResult *)self;
|
||||
|
|
@ -743,6 +808,15 @@ void destroy(DestReceiver *self)
|
|||
}
|
||||
|
||||
/*
|
||||
|
||||
Find_select_stmt function:
|
||||
|
||||
Parameter: (Node *parsetree)
|
||||
|
||||
Return: None
|
||||
|
||||
Recursively search the SelectStmt structure in the parse tree.
|
||||
|
||||
* find_select_stmt
|
||||
* Recursively search for SelectStmt structures within a parse tree.
|
||||
*
|
||||
|
|
@ -898,6 +972,12 @@ void get_partition_index_type(IndexPrint *suggested_index, TableCell *table)
|
|||
}
|
||||
|
||||
/*
|
||||
Generate_ Index_ Print function:
|
||||
Formal parameters: (TableCell * table, char * index_print)
|
||||
Return: IndexPrint*
|
||||
Generate Index Printing
|
||||
|
||||
|
||||
* generat_index_print
|
||||
* Generate index type, normal table is '' by default
|
||||
* partition table is divided into local and global.
|
||||
|
|
@ -943,6 +1023,15 @@ IndexPrint *generat_index_print(TableCell *table, char *index_print)
|
|||
return suggested_index;
|
||||
}
|
||||
|
||||
|
||||
/*Find_table function:
|
||||
|
||||
Parameter: (TableCell *table)
|
||||
|
||||
Return: TableCell*
|
||||
|
||||
Find index table*/
|
||||
|
||||
TableCell *find_table(TableCell *table)
|
||||
{
|
||||
ListCell *item = NULL;
|
||||
|
|
@ -1499,6 +1588,11 @@ uint4 calculate_field_cardinality(char *schema_name, char *table_name, const cha
|
|||
return cardinality;
|
||||
}
|
||||
|
||||
/*Split_ Field_ List function:
|
||||
Formal parameters: (List * fields, char * * schema_name_ptr, char * * table_name_ptr, char * * col_name_ptr)
|
||||
Return: None
|
||||
Split the specified area index table*/
|
||||
|
||||
void split_field_list(List *fields, char **schema_name_ptr, char **table_name_ptr, char **col_name_ptr)
|
||||
{
|
||||
if (fields == NULL) {
|
||||
|
|
|
|||
|
|
@ -21,6 +21,22 @@
|
|||
*
|
||||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
/*This code is a part of a C language function library, including
|
||||
some functions for dealing with time and data type conversion.
|
||||
The time_diff function is used to calculate the difference between
|
||||
the times represented by two timespec structures.
|
||||
The interval_to_sec and interval_to_msec functions convert a
|
||||
numerical value representing a time interval into seconds and milliseconds.
|
||||
The float8_get_Datum function converts a value of float8 type into
|
||||
a corresponding datum value according to the input data type.
|
||||
The Datum_get_float8 function converts a datum value into a
|
||||
corresponding float8 value according to the input data type.
|
||||
The Datum_get_int function converts a datum value into a
|
||||
corresponding value of type int32 according to the input data type.
|
||||
The string_to_Datum function converts a string into a datum value of the specified data type.
|
||||
The check_hyper_bounds function is used to check the boundary condition of the superparameter.
|
||||
These functions can be used in data type conversion,
|
||||
time difference calculation and boundary check of superparameters in database systems.*/
|
||||
|
||||
#include "db4ai/db4ai_common.h"
|
||||
|
||||
|
|
|
|||
|
|
@ -73,6 +73,39 @@ static bool index_supports_backward_scan(Oid indexid);
|
|||
* Note that if the plan node has parameters that have changed value,
|
||||
* the output might be different from last time.
|
||||
*/
|
||||
/*The ExecReScanByType' function performs
|
||||
different rescan operations according to the type of plan node, such as:
|
||||
-For the ResultState, perform the result rescan operation.
|
||||
-For the modified table node (ModifyTableState) and the distributed
|
||||
DistInsertSelectState, perform the modified table rescan operation.
|
||||
-For the merge AppendState, perform the merge append rescan operation.
|
||||
-For a RecursiveUnionState, perform a recursive union rescan operation.
|
||||
-For the node with the initial operation, perform the rescan operation with the initial operation.
|
||||
-For BitmapAndState and BitmapOrState, perform bitoperation rescan operation.
|
||||
-For a sequential scan node (SeqScanState), perform a sequential scan rescan operation.
|
||||
-For index scan node (IndexScanState), index scan only node (indexscan state), bit index scan node
|
||||
(BitmapIndexScanState) and bit heap scan node (BitmapHeapScanState), perform corresponding scan rescan operations.
|
||||
-For tid scan nodes, SubqueryScanState, FunctionScanState, ValuesScanState, CteScanState, Worksheet
|
||||
scanning node (workbench scanning state), external scanning node (foreign scanning state), extensible
|
||||
planning node (extensible planning state), etc., and perform corresponding rescan operations according to specific node types.
|
||||
-Rescan the partition PartIteratorState.
|
||||
-In PGXC environment, rescan the remote query for the RemoteQueryState.
|
||||
-Rescan the nested loop connection node.
|
||||
-Rescan the MergeJoinState.
|
||||
-rescan the hash connection node (HashJoinState).
|
||||
-Rescan the materialized state.
|
||||
-Rescan the SortState.
|
||||
-Rescan the grouped nodes.
|
||||
-rescan the aggregation node (AggState) and the window aggregation node (WindowAggState).
|
||||
-rescan the UniqueState.
|
||||
-rescan the HashState.
|
||||
-Rescan the set operation node (SetOpState).
|
||||
-Rescan the lock result of the lock node that locks the row node.
|
||||
-Rescan the restriction result of the restriction node.
|
||||
Rescan the vectorization conversion result of the vectorization conversion node.
|
||||
|
||||
The implementation of these rescan operations varies according to the type of specific planning nodes,
|
||||
and they will re-read the data and generate new output results for use in the next execution.*/
|
||||
void ExecReScanByType(PlanState* node)
|
||||
{
|
||||
/* If collecting timing stats, update them */
|
||||
|
|
@ -260,6 +293,18 @@ void ExecReScanByType(PlanState* node)
|
|||
}
|
||||
}
|
||||
|
||||
/*This code is the source code of an executor access method, which is used to perform rescan operation in the executor.
|
||||
|
||||
Rescan refers to rescan the executed plan node in order to regenerate the output results. In the executor,
|
||||
the plan node refers to each step in the query plan, such as scanning tables, filtering data and aggregating data.
|
||||
The function ExecReScan in the code is the main function to
|
||||
perform rescan in the actuator. It takes a plan node as a parameter and does the following:
|
||||
|
||||
1. If performance statistics are being collected, update the statistics.
|
||||
2. If the parameters of the plan node change, update the parameter information.
|
||||
3. Close any SRF(Server-Side Function) in the plan node.
|
||||
4. Stop rescanning if Stub execution is needed.
|
||||
5. Call the ExecReScanByType' function to perform the corresponding rescan operation according to the type of the plan node.*/
|
||||
/*
|
||||
* ExecReScan
|
||||
* Reset a plan node so that its output can be re-scanned.
|
||||
|
|
@ -343,6 +388,40 @@ void ExecReScan(PlanState* node)
|
|||
node->chgParam = NULL;
|
||||
}
|
||||
}
|
||||
/*This code defines the functions and auxiliary functions related to the execution plan.
|
||||
|
||||
The function ExecMarkPos' is used to save the scanning position and mark the status of the execution
|
||||
plan as saved. According to the passed-in PlanState object, the function will call the corresponding
|
||||
function to save the scanning position according to its type.
|
||||
|
||||
The function ExecRestrPos' is used to restore the
|
||||
scanning position and perform the corresponding
|
||||
restoration operation. According to the passed-in PlanState object, this function will call the
|
||||
corresponding function to restore the scanning position according to its type.
|
||||
|
||||
The function ExecSupportsMarkRestore' is used
|
||||
to check whether the execution plan supports marking
|
||||
and recovery operations. According to the passed-in Path object,
|
||||
the function will return the corresponding result according to its type.
|
||||
|
||||
The function ExecSupportsBackwardScan is used to check
|
||||
whether the execution plan supports reverse scanning.
|
||||
According to the passed-in Plan object, the function will return
|
||||
the corresponding result according to its type.
|
||||
|
||||
The function `target _ list _ supports _ backward _ scan` is used to check whether
|
||||
the target list supports reverse scanning.
|
||||
It determines whether to support reverse scanning by checking
|
||||
whether each expression in the target list returns a collection type.
|
||||
|
||||
The function `index _ supports _ backward _ scan` is used to check
|
||||
whether the index supports reverse scanning.
|
||||
It determines whether to support reverse scanning by checking
|
||||
whether the access method of the index supports reverse scanning.
|
||||
|
||||
The function ExecMaterializesOutput' is used to check whether the execution plan automatically
|
||||
materialization the output. Depending on the type of execution
|
||||
plan passed in, this function will return the corresponding results.*/
|
||||
|
||||
/*
|
||||
* ExecMarkPos
|
||||
|
|
|
|||
|
|
@ -69,6 +69,31 @@ static inline bool redis_offset_retrive_function(const char* funcname, Oid retty
|
|||
((nargs) == 4 && (rettype) == TIDOID && (argstype)[0] == TEXTOID && (argstype)[1] == NAMEOID && \
|
||||
(argstype)[2] == INT4OID && (argstype)[3] == INT4OID))
|
||||
|
||||
/*The function of this code is to implement some functions related to Redis. Specifically includes the following aspects:
|
||||
1. Some macros are defined to specify some constants.
|
||||
2. Some inline functions are declared to judge whether a function is a corresponding Redis function.
|
||||
3. Some functions are implemented, including recording deleted tuples, judging whether the relationship is in cluster
|
||||
redistribution, checking whether the table is a deletion operation table, and judging whether the process is in the process of cluster redistribution.
|
||||
The function RecordDeletedTuple is used to record the tupleid of a given tuple into the `pg _ delete _ delta` table. As follows:
|
||||
|
||||
-parameters:
|
||||
-`Relid`: OID of the target relationship of the update/delete operation.
|
||||
-`bucket id`: ID of the bucket where the target tuple is located.
|
||||
-`tupleid': the tupleid to be recorded.
|
||||
-`deldelta_rel: the corresponding `pg _ delete _ delta` relationship.
|
||||
|
||||
The function RelationInClusterResizing' is used to determine whether the relationship is in the operation of cluster resizing.
|
||||
|
||||
The function `relationinclusteresinggreadonly` is used to determine whether the relationship is in a read-only cluster resizing operation.
|
||||
|
||||
The function `relationinclusteresizingendachup' is used to determine whether the relationship is in an operation (write error) before the end of cluster resizing.
|
||||
|
||||
The function CheckRangeVarInRedistribution' is used to check whether the relationship is in redistribution through the relationship variable.
|
||||
|
||||
The function RelationIsDeleteDeltaTable is used to determine whether the given table name is a delete_delta table.
|
||||
|
||||
The function `clusterSizingProgress' is used to determine whether the cluster resizing process is in progress.*/
|
||||
|
||||
static inline bool redis_tupleid_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs)
|
||||
|
||||
{
|
||||
|
|
|
|||
|
|
@ -47,6 +47,63 @@ static ScanState* search_plan_tree(PlanState *node, Oid table_oid);
|
|||
* legal situation in inheritance cases). Raises error if cursor is not a
|
||||
* valid updatable scan of the specified table.
|
||||
*/
|
||||
/*The segment code defines a function named execCurrentOf, which is used to execute the CURRENT OF expression in SQL query.
|
||||
The CURRENT OF expression is a part of SQL/PSM (Persistent Storage Module),
|
||||
which is used to implement sensitive operations on a cursor.
|
||||
The function execCurrentOf receives five parameters:
|
||||
|
||||
1. cexpr: a pointer to the CurrentOfExpr structure, which contains the information of the CURRENT OF expression.
|
||||
2. econtext: a pointer to ExprContext structure, which contains the context information of expression execution.
|
||||
3. Relationship: A pointer to the relationship structure, which represents a relationship (i.e. a table) in the database.
|
||||
4. current_tid: a pointer to the ItemPointer structure, which represents the current transaction ID.
|
||||
5. partitionOfCursor_tid: A pointer to the RelationPtr structure, which represents the partition of the cursor.
|
||||
|
||||
The function first obtains the name of the cursor according to cexpr, and
|
||||
then finds the corresponding Portal according to the name.
|
||||
If a valid Portal cannot be found, an error is reported. Then, the function checks
|
||||
the query description (query_desc) corresponding to the Portal.
|
||||
An error is also reported if the query description does not exist
|
||||
or the status of the query description is invalid.
|
||||
|
||||
Then, the function decides which strategy to execute according to the row marks in the query description.
|
||||
If there is a line mark, use FOR UPDATE/SHARE; Otherwise, use a FOR-UPDATE method.
|
||||
|
||||
It defines a variable named `erm` with an initial value of NULL. Then it traverses ` query _ desc-> estate-> es _ row marks`,
|
||||
which is a list of all the rowmarks in the cursor query. During traversal, it
|
||||
checks whether each row tag needs a row share lock, and if not, it ignores the row tag.
|
||||
|
||||
For the row tag that needs a row sharing lock, the code checks whether the table associated with the row tag is
|
||||
the target table (that is, the OID returned by the RelationGetRelid' of `thiserm-> relation' is equal to table_oid').
|
||||
If it is, and there is already a row tag associated with the target table, it will report an error because
|
||||
the cursor cannot have more than one FOR UPDATE/SHARE reference to the same table.
|
||||
|
||||
After the traversal is completed, if the row tag associated with the target table is not found, it will report an error,
|
||||
because the cursor must have a FOR UPDATE/SHARE reference to the target table.
|
||||
|
||||
Next, the code checks whether the cursor currently has a result row.
|
||||
If not, it will report an error, because in the SQL specification, this is wrong.
|
||||
|
||||
Finally, if there is a valid TID (transaction ID) of the current scan, it will set' current_tid' and check whether
|
||||
the relationship is partitioned. If the relationship is partitioned, it will set `partition of cursor _ tid' to NULL.
|
||||
Then return true, indicating that the related TID has been found. If a valid TID is not found, it will return false,
|
||||
indicating that this table has not generated the current row of the cursor, and other inherited
|
||||
sub-tables may have generated the current row of the cursor.
|
||||
|
||||
Some variables are defined, including a pointer named scanstate', a boolean variable` lisnull',
|
||||
an Oid variable` tuple_tableoid' and an ItemPointer variable` tuple_tid'.
|
||||
|
||||
Then, it searches the search_plan_tree by calling the `search _ plan _ tree` function to find the scan node
|
||||
associated with the given table OID. If the scan node is not found,
|
||||
or the scan node is overwritten by the aggregation operation, it will report an error.
|
||||
|
||||
Next, the code checks whether the cursor currently has a result row. If not,
|
||||
it will report an error, because in the SQL specification, this is wrong.
|
||||
|
||||
Then, if the current scan tuple in the scan state is NULL, it will return false.
|
||||
|
||||
Finally, the code uses the slot_getattr function to get the table OID and transaction ID of
|
||||
the tuple and check whether they are valid. If the relationship is partitioned, it will also check
|
||||
whether the table OID is the same as the parent table OID of the partition.*/
|
||||
bool execCurrentOf(CurrentOfExpr *cexpr, ExprContext *econtext, Relation relation, ItemPointer current_tid,
|
||||
RelationPtr partitionOfCursor_tid)
|
||||
{
|
||||
|
|
@ -208,6 +265,22 @@ bool execCurrentOf(CurrentOfExpr *cexpr, ExprContext *econtext, Relation relatio
|
|||
*
|
||||
* Fetch the string value of a param, verifying it is of type REFCURSOR.
|
||||
*/
|
||||
/*This code defines a function `fetch _ cursor _ param _ value`, which is used to get the specified
|
||||
parameter value, especially when the parameter is of the reference cursor type.
|
||||
|
||||
The input parameters of the function include a pointer to an ExprContext structure and an integer paramId.
|
||||
The ExprContext' structure contains the execution context of the expression, which may contain
|
||||
some parameter information. ParamId' is the ID of the parameter to get.
|
||||
|
||||
The function first checks whether there is parameter information and whether the parameter ID is within the valid range.
|
||||
Then, it locates the specific parameter and checks its type. If the parameter type is dynamic (that is, its type identifier is invalid)
|
||||
and there is a parameter obtaining function, it will call this function to obtain the value of the parameter.
|
||||
|
||||
If the parameter type is valid and not null, the function will check further. If the parameter type is not a reference refcursor,
|
||||
it will report an error because the function only deals with this type. If the parameter type is a reference cursor,
|
||||
the function will convert its value to a C string and return this string.
|
||||
|
||||
If the value of the parameter is not found during the execution of the function, it will report an error and return NULL.*/
|
||||
static char *fetch_cursor_param_value(ExprContext *econtext, int paramId)
|
||||
{
|
||||
ParamListInfo paramInfo = econtext->ecxt_param_list_info;
|
||||
|
|
@ -243,6 +316,40 @@ static char *fetch_cursor_param_value(ExprContext *econtext, int paramId)
|
|||
* Search through a PlanState tree for a scan node on the specified table.
|
||||
* Return NULL if not found or multiple candidates.
|
||||
*/
|
||||
/*t searches the PlanState tree for scan nodes on the specified table.
|
||||
In PostgreSQL, the PlanState tree is a data structure representing the query execution plan.
|
||||
The function `search _ plan _ tree` receives two parameters: a pointer` node of PlanState and
|
||||
a ` table _ Oid` of oid type. The function starts searching from the given node
|
||||
and finds the scanning node that matches the OID of the specified table.
|
||||
In the code, use the switch statement to judge the type of the node. For each scan node type that can be processed
|
||||
(for example, sequential scan, index scan, index only scan, bitmap heap scan and TID scan), the code checks whether the ID
|
||||
of the current relationship (that is, the scanned table) matches the given table OID.
|
||||
If there is a match, the function returns a pointer to the scan node.
|
||||
|
||||
For the `t _ remotequerystate` node, the code will return the scanning status of the node.
|
||||
For the `t _ extensibleplanstate' node, the code will check whether the ID of the current relationship matches
|
||||
the given table OID, and return the scanning status at the time of matching.
|
||||
|
||||
For the `t _ appendstate` node, the code will iterate through all the attached plans and recursively call the `search _ plan _ tree` function.
|
||||
If multiple matching scan nodes are found in the attached schedule, the function will return NULL.
|
||||
|
||||
-`T_AppendState' and `t _ mergeappendState': Both node types represent a method of combining multiple subquery results into one result.
|
||||
The code will traverse each subquery and recursively call the `search _ plan _ tree` function for each subquery.
|
||||
If a matching scanning node is found, and no matching node has been found before, the matching node is assigned to result.
|
||||
If multiple matching nodes are found, the function will return NULL.
|
||||
-`t _ resultstate`, `t _ limitstate`, `t _ partiteratorstate`, and `t _ materialstate` (only exists in PGXC): These node types can be
|
||||
traversed directly because they always return the current line of their input.
|
||||
-`T_SubqueryScanState: This node type represents the scanning of the subquery,
|
||||
and the code will return the scanning node in the subquery.
|
||||
-Default: If the node is not of any of the above types,
|
||||
the code will assume that it cannot traverse through the node, so it will return NULL.
|
||||
|
||||
The main purpose of this function is to find the scanning node corresponding to a specific table in the query execution plan.
|
||||
This is very useful for understanding and tracking query execution, especially
|
||||
when it is necessary to understand and debug query performance problems.
|
||||
|
||||
Generally speaking, this function is used to find the scan node corresponding to the specified table in the query execution plan.*/
|
||||
|
||||
#ifdef PGXC
|
||||
ScanState* search_plan_tree(PlanState* node, Oid table_oid)
|
||||
#else
|
||||
|
|
|
|||
|
|
@ -48,6 +48,25 @@ static int TupleHashTableMatch(const void* key1, const void* key2, Size keysize)
|
|||
*
|
||||
* NB: evalContext is reset each time!
|
||||
*/
|
||||
/*The main purpose of this code is to compare whether two Tuple are equal.
|
||||
In database, tuple is a basic data structure, which is used to store a series of related values.
|
||||
The function execTuplesMatch receives two TupleTableSlot pointers (slot1 and slot2),
|
||||
which point to the tuple to be compared, as well as the number of columns (numCols),
|
||||
the matching column index (matchColIdx), the equation functions (eqfunctions) and an evalContext.
|
||||
|
||||
It first switches to a temporary memory context (evalContext), and then loops through each column,
|
||||
starting with the last column (the least important sort key). This is because the last column
|
||||
is most likely to be different when processing sorted input.
|
||||
|
||||
For each column, it gets the property values in two tuples and checks whether they are empty.
|
||||
If one is empty and the other is not, they are not equal, and the function sets the result to false
|
||||
and jumps out of the loop. If both of them are empty, they are regarded as equal and continue the next cycle.
|
||||
|
||||
If both attributes are not empty, then a specific type of equality function will be used to compare whether
|
||||
they are equal. If not, the function sets the result to false and jumps out of the loop.
|
||||
|
||||
Finally, the function switches back to the old memory context and returns the result. If all columns match,
|
||||
the function will return true, otherwise it will return false.*/
|
||||
bool execTuplesMatch(TupleTableSlot* slot1, TupleTableSlot* slot2, int numCols, AttrNumber* matchColIdx,
|
||||
FmgrInfo* eqfunctions, MemoryContext evalContext)
|
||||
{
|
||||
|
|
@ -166,6 +185,26 @@ bool execTuplesUnequal(TupleTableSlot* slot1, TupleTableSlot* slot2, int numCols
|
|||
*
|
||||
* The result is a palloc'd array.
|
||||
*/
|
||||
/*The main purpose of this code is to generate an array of function information for
|
||||
each pair of equality operators for subsequent tuple comparison.
|
||||
|
||||
The function execTuplesMatchPrepare takes the number of columns (numCols) and
|
||||
the array of equality eqOperators (`eq operators`) as parameters.
|
||||
|
||||
First, it uses `p palloc to allocate memory for the function information array,
|
||||
and the length of the array is the number of columns.
|
||||
|
||||
Then, it enters a loop, and each iteration in the loop corresponds to a column.
|
||||
For each column, it gets the equality operator (` eq _ opr`) and the corresponding
|
||||
function (` eq _ function`). This is done by calling the get_opcode function.
|
||||
|
||||
Next, it uses the fmgr_info function to fill the corresponding position
|
||||
of the function information array.
|
||||
|
||||
Finally, the function returns the generated function information array.
|
||||
|
||||
This function is usually called before performing tuple matching to
|
||||
prepare the required function information.*/
|
||||
FmgrInfo* execTuplesMatchPrepare(int numCols, Oid* eqOperators)
|
||||
{
|
||||
FmgrInfo* eqFunctions = (FmgrInfo*)palloc(numCols * sizeof(FmgrInfo));
|
||||
|
|
@ -192,6 +231,26 @@ FmgrInfo* execTuplesMatchPrepare(int numCols, Oid* eqOperators)
|
|||
*
|
||||
* Note: we expect that the given operators are not cross-type comparisons.
|
||||
*/
|
||||
/*The purpose of this code is to prepare equality function and hash function for tuple hash table.
|
||||
|
||||
The' executtupleshahprep' function receives four parameters: number of columns ('numCols'),
|
||||
equality operator array ('eqOperators'), equality function array ('eqFunctions') and hash function array ('hashFunctions').
|
||||
|
||||
First, the function allocates memory for the array of equality functions and hash functions.
|
||||
|
||||
Then, it enters a loop, and each iteration in the loop corresponds to a column. For each column,
|
||||
it gets the equality operator (` eq _ opr`) and the corresponding function (` eq _ function`). This is done by calling the get_opcode function.
|
||||
|
||||
Next, it tries to get the hash function of the equality operator. If the hash function cannot be found,
|
||||
it will report an error and call the `ereport' function, which will send the error information to the error handling system of PostgreSQL.
|
||||
|
||||
Then, it asserts that the left and right hash functions are the same, which
|
||||
means that it does not support cross-type cases.
|
||||
|
||||
Finally, it uses the fmgr_info function to fill the corresponding positions
|
||||
of the array of equality functions and hash functions.
|
||||
|
||||
This function is usually called before performing tuple hashing to prepare the required function information.*/
|
||||
void execTuplesHashPrepare(int numCols, Oid* eqOperators, FmgrInfo** eqFunctions, FmgrInfo** hashFunctions)
|
||||
{
|
||||
int i;
|
||||
|
|
@ -248,6 +307,29 @@ void execTuplesHashPrepare(int numCols, Oid* eqOperators, FmgrInfo** eqFunctions
|
|||
* Note that keyColIdx, eqfunctions, and hashfunctions must be allocated in
|
||||
* storage that will live as long as the hashtable does.
|
||||
*/
|
||||
/*The main purpose of this code is to create a TupleHashTable, which is a data structure for storing tuples,
|
||||
which is the basic data structure for storing a series of related values in the database.
|
||||
|
||||
The function' BuildTupleHashTable' receives a series of parameters, including the number of columns ('numCols'),
|
||||
key column index ('keyColIdx'), equation function ('eqfunctions'), hash function ('hashfunctions'), number of buckets ('nbuckets'), entrysize ('entrysize').
|
||||
|
||||
First, the function checks whether the number of buckets and the entry size are valid. Then,
|
||||
it limits the request for the initial table size according to the working memory.
|
||||
|
||||
Then, it allocates memory in the table context to store TupleHashTableData.
|
||||
|
||||
Then, it sets various fields, including column number, key column index, hash function,
|
||||
equality function, table context, temporary context, entry size, etc.
|
||||
|
||||
Then, it clears the memory of the hash_ctl structure and sets its various fields, including key size,
|
||||
entry size, hash function, matching function and hash context.
|
||||
|
||||
Finally, it creates a hashtable using the hash_create function and stores it in the hashtab' field of `hashtable'.
|
||||
|
||||
Function returns the created ` hashtable'.
|
||||
|
||||
This function is usually called when creating a tuple hash when executing a database query,
|
||||
and is used to prepare the required data structure.*/
|
||||
TupleHashTable BuildTupleHashTable(int numCols, AttrNumber* keyColIdx, FmgrInfo* eqfunctions, FmgrInfo* hashfunctions,
|
||||
long nbuckets, Size entrysize, MemoryContext tablecxt, MemoryContext tempcxt, int workMem)
|
||||
{
|
||||
|
|
@ -309,6 +391,21 @@ TupleHashTable BuildTupleHashTable(int numCols, AttrNumber* keyColIdx, FmgrInfo*
|
|||
* hash table if it is new
|
||||
*
|
||||
*/
|
||||
/*The main purpose of this code is to find the TupleTableSlot in the TupleHashTable and insert it as needed.
|
||||
TupleHashTable is a data structure used to store tuples, which are the basic data structures used to store a series of related values in the database.
|
||||
|
||||
The function LookupTupleHashEntry receives four parameters: a TupleHashTable(`hashtable), a TupleTableSlot pointer (`slot`),
|
||||
a Boolean pointer (isnew) and a Boolean value (isinserthashtbl).
|
||||
|
||||
The function first checks whether it is the first time to pass, and if it is, it will clone
|
||||
the input time slot to make the table time slot.
|
||||
|
||||
Then, the function switches to the temporary context, sets the hash and the data needed
|
||||
by the matching function, and saves the current tuple hash table.
|
||||
|
||||
Next, it searches the hash table. If' isinserthashtbl' is true, it will search the hash table and return the found entry
|
||||
if it is found; If it is not found and' isnew' is not NULL, set' isnew' to true, indicating a new entry. If' isinserthashtbl' is false,
|
||||
it will only search the hash table, and if it is found, it will return the found entry; If it is not found, it will create a new table.*/
|
||||
TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot* slot, bool* isnew, bool isinserthashtbl)
|
||||
{
|
||||
TupleHashEntry entry;
|
||||
|
|
@ -510,6 +607,21 @@ static uint32 TupleHashTableHash(const void* key, Size keysize)
|
|||
* Also, the caller must select an appropriate memory context for running
|
||||
* the compare functions. (dynahash.c doesn't change CurrentMemoryContext.)
|
||||
*/
|
||||
/*This code is used to process a part of tuple hash table, which is a data
|
||||
structure used to store and retrieve tuple data in PostgreSQL.
|
||||
|
||||
The function TupleHashTableMatch' is a comparison function, which is used to compare
|
||||
whether two tuples are equal. This function is designed to be used with dynahash.c library,
|
||||
which is a general hash table library and can be used to store and retrieve data.
|
||||
|
||||
The function receives three parameters: key1, key2 and keysize. Key1' and' key2' are pointers
|
||||
to two tuples to be compared, and' keysize' is the size of tuples.
|
||||
|
||||
Within the function, firstly, ` key1' and ` key2' are converted into tuples, and then the tuples are stored
|
||||
in the table slots and input slots of the hash table by using the ` ExecStoreMinimalTuple' function.
|
||||
|
||||
Finally, compare whether two tuples are equal by using the execTuplesMatch function.
|
||||
If two tuples are equal, the function returns 0, otherwise it returns 1.*/
|
||||
static int TupleHashTableMatch(const void* key1, const void* key2, Size keysize)
|
||||
{
|
||||
MinimalTuple tuple1 = ((const TupleHashEntryData*)key1)->firstTuple;
|
||||
|
|
|
|||
|
|
@ -60,6 +60,30 @@
|
|||
* of whether to include room for an OID or not.
|
||||
* An optional resultSlot can be passed as well.
|
||||
*/
|
||||
/*This function is used to initialize a JunkFilter structure,
|
||||
which is mainly used to deal with' junk' data in SQL query results. ,
|
||||
Function definition: JunkFilter * executinitjunkfilter
|
||||
(list * targetlist, boolhasoid, tupletableslot * slot, tablemtype tam)
|
||||
is a function whose return value is a pointer of junkfilter type. ",
|
||||
Variable initialization: some variables are initialized inside the
|
||||
function, including a JunkFilter pointer, a TupleDesc cleaning
|
||||
tuple type, an int cleaning length, an AttrNumber pointer array,
|
||||
and a ListCell pointer.
|
||||
Calculate the clean tuple type: use the ExecCleanTypeFromTL
|
||||
function to calculate the clean tuple type based on the target list,
|
||||
whether it has OID, and the type of table access method.
|
||||
Set or create a tuple table slot: if the passed slot is not empty,
|
||||
then use the passed slot; Otherwise, create a new slot.
|
||||
Calculating the mapping between the original tuple and the clean tuple:
|
||||
calculating the mapping between the attributes of the original tuple and
|
||||
the attributes of the clean tuple. This mapping is an array whose length is
|
||||
equal to the number of attributes of the clean tuple. For each attribute of
|
||||
the clean tuple, if the corresponding original tuple attribute is not' garbage',
|
||||
the attribute number is stored in the mapping array.
|
||||
Create and initialize JunkFilter structure: Finally, create a new JunkFilter structure,
|
||||
and store the data (target list, clean tuple type, mapping, result slot) obtained
|
||||
by the above calculation in this structure. Then take the pointer of this
|
||||
structure as the return value of the function.*/
|
||||
JunkFilter* ExecInitJunkFilter(List* targetList, bool hasoid, TupleTableSlot* slot, TableAmType tam)
|
||||
{
|
||||
JunkFilter* junkfilter = NULL;
|
||||
|
|
@ -131,6 +155,26 @@ JunkFilter* ExecInitJunkFilter(List* targetList, bool hasoid, TupleTableSlot* sl
|
|||
* deleted columns. It is assumed that the caller has checked that the
|
||||
* non-deleted columns match up with the non-junk columns of the targetlist.
|
||||
*/
|
||||
/*The segment code defines a function named ExecInitJunkFilterConversion,
|
||||
which is used to initialize a JunkFilter structure, mainly used to deal with' junk' data in SQL query results.
|
||||
|
||||
The function receives three parameters: a targetList, a clean tuple type and a tuple table slot.
|
||||
|
||||
Inside the function, some variables are initialized, including a JunkFilter pointer,
|
||||
a clean length, a clean mapping array, a ListCell pointer and an integer variable.
|
||||
|
||||
Next, the function checks whether the incoming slot is empty.
|
||||
If it is not empty, the incoming slot is used, otherwise, a new slot is created.
|
||||
|
||||
Then, the function calculates the mapping between the original tuple and the clean tuple.
|
||||
This mapping is an array whose length is equal to the number of attributes of the clean tuple.
|
||||
For each attribute of the clean tuple, if the corresponding original tuple attribute is not' garbage',
|
||||
the attribute number is stored in the mapping array. If an attribute of the clean tuple is deleted, a
|
||||
0 will be stored in the corresponding position in the mapping array, indicating that a NULL value is needed in the output tuple.
|
||||
|
||||
Finally, the function creates a new JunkFilter structure, and stores the data (target list, clean tuple type,
|
||||
mapping, result slot) obtained from the above calculation into this structure. Then take the
|
||||
pointer of this structure as the return value of the function.*/
|
||||
JunkFilter* ExecInitJunkFilterConversion(List* targetList, TupleDesc cleanTupType, TupleTableSlot* slot)
|
||||
{
|
||||
JunkFilter* junkfilter = NULL;
|
||||
|
|
@ -208,6 +252,17 @@ AttrNumber ExecFindJunkAttribute(JunkFilter* junkfilter, const char* attrName)
|
|||
* Locate the specified junk attribute in the junk filter's targetlist.
|
||||
* Returns NIL if not found.
|
||||
*/
|
||||
/*This function is called' ExecFindJunkPrimaryKeys', and it receives a parameter named' targetList',
|
||||
which is a pointer to the list type. The main goal of the function is to traverse the' targetlist'
|
||||
and find and return all the' garbage' attributes named' xc_primary_key'.
|
||||
|
||||
A list named' jk_primary_keys' is initialized inside the function to store the found properties that meet the conditions.
|
||||
Then, use the foreach loop to traverse' targetlist'. In each loop, it first gets a pointer to the current element and casts
|
||||
the element to the' TargetEntry' type. Then, check whether the element is a' garbage' attribute and its name is' xc_primary_key'.
|
||||
If the condition is met, then add the expression of this attribute to the' jk_primary_keys' list.
|
||||
|
||||
Finally, the function returns the' jk_primary_keys' list.
|
||||
This list contains all the' junk' attributes named' xc_primary_key' found in' targetlist'.*/
|
||||
List* ExecFindJunkPrimaryKeys(List* targetlist)
|
||||
{
|
||||
List* jk_primary_keys = NIL;
|
||||
|
|
@ -231,6 +286,29 @@ List* ExecFindJunkPrimaryKeys(List* targetlist)
|
|||
* Find a junk attribute given a subplan's targetlist (not necessarily
|
||||
* part of a JunkFilter).
|
||||
*/
|
||||
/*This code has three functions, namely' ExecFindJunkAttributeInTlist','
|
||||
ExecGetJunkAttribute' and' ExecFilterJunk'. The following is an explanation of each function:
|
||||
|
||||
1. `ExecFindUnkattributeinlist': This function receives a targetlist and an attribute name as parameters,
|
||||
and then looks for the matching attribute name in the target list. If a matching attribute is found,
|
||||
and the attribute is marked as' junk' (that is,' resjunk' is true), the number of the attribute ('resno') is returned.
|
||||
If no matching attribute is found, or the attribute is not marked as' junk', an invalid attribute number ('InvalidAttrNumber') is returned.
|
||||
2. `ExecGetJunkatAttribute`: This function receives a tuple table slot, an attribute number (attno)
|
||||
and a pointer to a Boolean value (isNull) as parameters. It uses the `tableam _ tslot _ getattr` function
|
||||
to get the value of the specified attribute number and the isNull flag from the slot. The function also does
|
||||
some assertion checking to ensure that the attribute number passed in is greater than 0 and the slot is not empty.
|
||||
3.'ExecFilterJunk': It is used to filter the "junk" attribute in OpenGauss database.
|
||||
It receives two parameters: a JunkFilter structure pointer and a TupleTableSlot structure pointer.
|
||||
The main work of this function can be roughly divided into the following steps:
|
||||
1. Extract all the values of the old tuple (that is, the input TupleTableSlot) and store them in old_values and old_isnull.
|
||||
2. Get the required information from JunkFilter structure, including clean tuple type, cleanLength and cleanMap.
|
||||
3. Prepare to build a new virtual tuple (namely resultSlot).
|
||||
4. Traverse every element in the clean map, and if the value of the map is 0, set it to NULL;
|
||||
in the corresponding position in the new tuple; Otherwise, the corresponding value is obtained from the old tuple and copied to the new tuple.
|
||||
5. Finally, return the virtual TupleTableSlot that stores the new tuple.
|
||||
In this way, this function realizes the function of transforming from tuple containing "garbage" attribute to a tuple without "garbage" attribute.
|
||||
These functions may be related to database query optimization, especially when dealing with a large number of data,
|
||||
by identifying and filtering out' junk' attributes (that is, unnecessary attributes), the efficiency and performance of the query can be improved.*/
|
||||
AttrNumber ExecFindJunkAttributeInTlist(List* targetlist, const char* attrName)
|
||||
{
|
||||
ListCell* t = NULL;
|
||||
|
|
@ -364,7 +442,25 @@ VectorBatch* BatchExecFilterJunk(_in_ JunkFilter* junkfilter, __inout VectorBatc
|
|||
//
|
||||
return batch;
|
||||
}
|
||||
|
||||
/*"ExecSetjunkFilteDescriptor function":
|
||||
"Function": "This function is mainly used to set the tupleDescriptor of the resultSlot
|
||||
of JunkFilter. It receives two parameters: a JunkFilter structure pointer and a TupleDesc structure.
|
||||
It copies the attribute type ID in the input tuple descriptor to the corresponding attribute in
|
||||
the tuple descriptor of the result slot by traversing the cleanMap. " ,
|
||||
"parameters":
|
||||
"junkfilter": "A pointer to JunkFilter structure, which contains information needed for filtering operation,
|
||||
such as cleaning tuple type and cleaning mapping." ,
|
||||
"tupdesc": "A pointer to a TupleDesc structure that describes the properties of a tuple."
|
||||
"BatchCheckNodeIdentifier function":
|
||||
"Function": "This function is mainly used to check whether the value of the' xc_node_id'
|
||||
column in a VectorBatch is the same as the identifier of the current node. If not, the function
|
||||
will report an error. The function first checks whether' xc_node_id' is a valid attribute number,
|
||||
and then obtains the values of the' xc_node_id' column, and checks whether they are the same
|
||||
as the identifier of the current node one by one. " ,
|
||||
"parameters":
|
||||
"junkfilter": "A pointer to JunkFilter structure, which contains information needed
|
||||
for filtering operation, such as cleaning tuple type and cleaning mapping." ,
|
||||
"batch": "A pointer to the VectorBatch structure, which contains the data to be filtered."*/
|
||||
void ExecSetjunkFilteDescriptor(JunkFilter* junkfilter, TupleDesc tupdesc)
|
||||
{
|
||||
TupleDesc resultslotTupType;
|
||||
|
|
|
|||
|
|
@ -435,6 +435,39 @@ void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
|
|||
*
|
||||
* ----------------------------------------------------------------
|
||||
*/
|
||||
/*This code is written in C++ and seems to be extracted from a
|
||||
database management system (maybe PostgreSQL).
|
||||
|
||||
The ExecutorRun function is the main routine of the executor module.
|
||||
It receives the query descriptor from the traffic police and executes the query plan.
|
||||
|
||||
This function first performs some initialization operations, and then
|
||||
calls the exec_explain_plan function, probably to explain the query plan.
|
||||
|
||||
Then, if the workload manager is enabled, and the resource tracking
|
||||
level is set to RESOURCE_TRACK_OPERATOR,
|
||||
and the query descriptor is not empty, and the plan
|
||||
statement in the query descriptor is a flow plan,
|
||||
and resources need to be tracked, then some additional variables are set.
|
||||
|
||||
Then, it checks whether operation history statistics
|
||||
can be performed, and if so, it calls the ExplainNodeFinish function.
|
||||
|
||||
Next, it checks whether there is an ExecutorRun_hook, and calls it if there is;
|
||||
Otherwise, call the standard_ExecutorRun function.
|
||||
|
||||
Then, if it is a PGXC coordinator or a single node, and the query operation is insert,
|
||||
delete, update or merge, the report_iud_time function is called.
|
||||
|
||||
Next, if resources need to be tracked, and there are query descriptors and tracking operations,
|
||||
the PlanAnalyzerOperator function is called to analyze the query plan problem.
|
||||
If a problem is found, it is stored in the system view gs_wlm_session_history.
|
||||
|
||||
Finally, print the query duration and call the instr_stmt_report_query_plan function.
|
||||
If operation history statistics can be performed, set can_record_to_table to true,
|
||||
and call the ExplainNodeFinish function again. If it is a PGXC coordinator and the
|
||||
global instrument is not empty, delete the global instrument and set the thread instrument to NULL.
|
||||
Finally, the old statement name is restored and the execution level is reduced by 1.*/
|
||||
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long count)
|
||||
{
|
||||
/* sql active feature, opeartor history statistics */
|
||||
|
|
@ -655,6 +688,19 @@ void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long co
|
|||
*
|
||||
* ----------------------------------------------------------------
|
||||
*/
|
||||
/*"ExecutorFinish function": "This function is a calling hook. It first checks whether there is an ExecutorFinish_hook'
|
||||
and calls it if there is one; Otherwise, call the standard_ExecutorFinish function. " ,
|
||||
"standard_ExecutorFinish function":
|
||||
"Function": "This is the standard end routine of the actuator module." ,
|
||||
"step":
|
||||
"Perform a health check to make sure that the query descriptor and status exist and are not in an interpretation mode." ,
|
||||
"Switch to the memory context of each query." ,
|
||||
"If the total time is set, start the instrument node." ,
|
||||
"Run the ModifyTable node to finish." ,
|
||||
"Executes a queued AFTER trigger unless told to skip the trigger." ,
|
||||
"If the total time is set, stop the instrument node." ,
|
||||
"Switch back to the old memory context." ,
|
||||
"Mark the status as completed."*/
|
||||
void ExecutorFinish(QueryDesc *queryDesc)
|
||||
{
|
||||
if (ExecutorFinish_hook) {
|
||||
|
|
@ -733,7 +779,28 @@ int ExecGetPlanNodeid(void)
|
|||
}
|
||||
return key;
|
||||
}
|
||||
/*This is a function called standard_ExecutorEnd',
|
||||
which releases the resources used by the executor during the query.
|
||||
|
||||
The following is the function explanation of the function:
|
||||
|
||||
1. Define some variables, including an execution state pointer ` estate', a memory context
|
||||
` old_context', an instrument time ` starttime' and a totaltime ` totaltime'.
|
||||
2. Set the start time by calling `instr _ time _ set _ current (start time)'.
|
||||
3. Do some health checks to ensure that' queryDesc' and' estate' are not empty.
|
||||
4. If `memory _ context _ checking` is defined, all memory contexts are checked at the start of the executor.
|
||||
5. Check whether ExecutorFinish has been called, unless it is in interpretation-only mode.
|
||||
This is because before version 9.1, the caller may forget to call it.
|
||||
6. Switch to the memory context of each query to run' ExecEndPlan'.
|
||||
7. Release our snapshot.
|
||||
8. If LLVM compilation is enabled and it is not currently running in the function manager,
|
||||
code generation thread disassembly is performed.
|
||||
9. Switch to the old context before destroying it.
|
||||
10. If `memory _ context _ checking` is defined, the memory context of each query is checked before FreeExecutorState'.
|
||||
11. Release the execution state and the memory context of each query, which should release all the contents allocated by the executor.
|
||||
12. Reset the fields in the query descriptor that no longer point to anything.
|
||||
|
||||
The main purpose of this code is to clean up and release resources after the query execution.*/
|
||||
void standard_ExecutorEnd(QueryDesc *queryDesc)
|
||||
{
|
||||
EState *estate = NULL;
|
||||
|
|
@ -826,6 +893,20 @@ void standard_ExecutorEnd(QueryDesc *queryDesc)
|
|||
* to the start.
|
||||
* ----------------------------------------------------------------
|
||||
*/
|
||||
/*This is a function called ExecutorRewind', which is used to rescan the query plan without executing it.
|
||||
|
||||
The following is the functional explanation of the code:
|
||||
|
||||
1. Define two variables, an execution estate pointer `establishment` and a memory context `old _ context`.
|
||||
2. Do some health checks to ensure that' queryDesc' and' estate' are not empty.
|
||||
3. Check whether the query operation is CMD_SELECT by assertion,
|
||||
because it may be meaningless to rescan and update the query.
|
||||
4. Switch to the memory context of each query to run ExecReScan.
|
||||
5. Rescan the query plan without executing it.
|
||||
6. Switch back to the old memory context.
|
||||
|
||||
This function may be used to reload or rescan the query plan under certain circumstances without actually executing it.
|
||||
This may be useful when you need to refresh the query plan or reload the data.*/
|
||||
void ExecutorRewind(QueryDesc *queryDesc)
|
||||
{
|
||||
EState *estate = NULL;
|
||||
|
|
@ -910,6 +991,22 @@ bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
|
|||
* ExecCheckRTEPerms
|
||||
* Check access permissions for a single RTE.
|
||||
*/
|
||||
/*The function ` ExecCheckRTPerms' is used to check whether each table in a query
|
||||
(listed in ` rangeTable') meets certain permission requirements.
|
||||
|
||||
The main logic of the code is as follows:
|
||||
|
||||
1. Define a' foreach' loop to traverse each element in' rangeTable'.
|
||||
2. For each element, it first checks whether this element is a time series table (RTE_RELATION),
|
||||
if so, it skips the check, if not, it continues to check the permissions.
|
||||
3. The function `ExecCheckrtePerms (RTE) ` is called to check the permissions of the current element (table).
|
||||
4. If the permission check fails, the function will report an error (if `ereport _ on _ violation` is `true`) and then return `false`.
|
||||
5. If ExecutorCheckPerms_hook is defined, call this function and assign the result to `result`.
|
||||
6. After all the operations are completed, the function returns result.
|
||||
|
||||
It should be noted that some parts of this function may be compiled according to whether
|
||||
`enable _ multiple _ nodes` is defined, which is a common technique of preprocessor to include
|
||||
or exclude specific code segments in different compilation environments.*/
|
||||
static bool ExecCheckRTEPerms(RangeTblEntry *rte)
|
||||
{
|
||||
AclMode requiredPerms;
|
||||
|
|
@ -1067,6 +1164,29 @@ static bool ExecCheckRTEPerms(RangeTblEntry *rte)
|
|||
* Check INSERT or UPDATE access permissions for a single RTE (these
|
||||
* are processed uniformly).
|
||||
*/
|
||||
/*The function ExecCheckRTEPermsModified' in this code is the process of performing permission check.
|
||||
|
||||
Function parameters:
|
||||
|
||||
-`relOid': the object identifier representing the relationship to be operated on.
|
||||
-`userid: the user ID of the operation.
|
||||
-`modifiedCols: Represents the bitmap of the modified column.
|
||||
-`requiredPerms: required permission type.
|
||||
|
||||
Code logic:
|
||||
|
||||
-If' modifiedCols' is empty, it means that the query has not explicitly updated any columns,
|
||||
so if the user has permission on any column of the relationship, the query is allowed.
|
||||
This is to deal with possible marginal situations in' SELECT FOR UPDATE' and' UPDATE'.
|
||||
-If' modifiedCols' is not empty, traverse each modified column. In the process of traversal,
|
||||
firstly, the index of the next modified column is obtained by the function of `bms _ next _ member',
|
||||
and then the attribute number attno' is obtained by adding the offset `firstlowinvalidheapattributenumber' to the index.
|
||||
-If' attno' equals' InvalidAttrNumber', it means that the whole line is referenced,
|
||||
which is not allowed here, so an error is reported and an exception is thrown.
|
||||
-If' attno' is not equal to' InvalidAttrNumber', use the' pg_attribute_aclcheck' function
|
||||
to check the user's permissions on the current attribute. If the permission check fails, it returns `false`.
|
||||
|
||||
If the function can successfully handle the permission check of all columns, then it finally returns ` true'.*/
|
||||
static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
|
||||
{
|
||||
int col = -1;
|
||||
|
|
@ -1097,6 +1217,20 @@ static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid, Bitmapset *modifie
|
|||
return true;
|
||||
}
|
||||
|
||||
/*The main function of this code is to check whether a transaction is read-only. Specifically,
|
||||
this function traverses all table references in the SQL query, and then rejects those queries that attempt to write on non-temporary tables.
|
||||
|
||||
Every part of the code has specific checks:
|
||||
|
||||
1. Traverse all table references in the query (` foreach (l, plannedstmt->rtable) `).
|
||||
2. for each table reference, check its type (rte->rtekind! = RTE_RELATION`)。 If it is not a relationship (that is, it is not a table), then skip it.
|
||||
3. check the required permissions (`rte-> requiredperms & (~ ACL _ select) `). If you only need to select the permission, then skip it.
|
||||
4. Check whether this table is in the temporary namespace (`istempnamespace (get _ rel _ namespace (rte-> Relid)) `). If so, then skip it.
|
||||
5. Check the persistence of this table (` get _ rel _ persistence (rte-> Relid) = = rel persistence _ global _ temp`). If it is a global temporary table, then skip it.
|
||||
6. For a specific Greenplum database, if it is a roach standby cluster in maintenance mode and is accessing the node relationship, then skip it.
|
||||
7. If all the above checks pass, then call the PreventCommandIfReadOnly' function to stop the execution of this query.
|
||||
|
||||
Generally speaking, the purpose of this function is to protect the consistency of the database by preventing write operations in read-only transactions.*/
|
||||
/*
|
||||
* Check that the query does not imply any writes to non-temp tables.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -175,6 +175,23 @@
|
|||
* initilaization work like open scanrel, instead allow NodeInit work to continue on its
|
||||
* lefttree/righttree
|
||||
*/
|
||||
/*The function is called ` NeedStubExecution', and its input parameter is a pointer to type ` Plan'.
|
||||
The main function of this function is to judge whether a plan node needs pile execution.
|
||||
The following is a detailed explanation of each part of the function:
|
||||
|
||||
-` # ifndef enable _ multiple _ nodes`: This is a preprocessor instruction to check whether the
|
||||
macro definition `enable _ multiple _ nodes` exists. If it does not exist, the function directly returns false.
|
||||
-`if (exec _ in _ recursive _ mode (plan) )`: This judgment statement checks whether the plan node is
|
||||
in recursive mode. If so, the function returns false.
|
||||
-`if (NeedExecute(plan) )`: This judgment statement calls the `NeedExecute' function to judge
|
||||
whether this plan step needs to be executed on the current data node. If necessary, the function returns false.
|
||||
-`switch (nodeTag(plan) )`: This judgment statement is processed differently according to the type
|
||||
of plan node. For most types of planning nodes, it returns ` false', but for certain node types
|
||||
(such as T_ModifyTable, T_VecModifyTable, T_Scan, etc.), it returns ` true'. If `enable _ multiple _ nodes` is defined, it will also handle the T_TsStoreScan type.
|
||||
|
||||
Therefore, in a word, this function mainly judges whether a given plan node needs to be executed,
|
||||
and it is influenced by many conditions, including whether some macros are defined,
|
||||
the state of the plan node, and the type of the plan node.*/
|
||||
bool NeedStubExecution(Plan* plan)
|
||||
{
|
||||
#ifndef ENABLE_MULTIPLE_NODES
|
||||
|
|
@ -219,6 +236,21 @@ bool NeedStubExecution(Plan* plan)
|
|||
/*
|
||||
* not need execute active sql if the datanode don't run in multi-nodegroup.
|
||||
*/
|
||||
/*1. `Needexecutivesql (plan * plan)' function: judge whether the current plan node needs to be executed.
|
||||
If the current node is neither a PGXC coordinator nor a single node and does not need to be executed, then return false;; Otherwise return true.
|
||||
2. `seqscannodestub (seqscanstate * seq _ scan) ` function: judge whether the sequential scanning node is a pile.
|
||||
If the scan description is NULL, then it is a pile and returns true;; Otherwise return false.
|
||||
3. `idxscannodestub (indexscanstate * index _ scan) ` function: judge whether the index scanning node is a stub.
|
||||
If the scan description is NULL, then it is a pile and returns true;; Otherwise return false.
|
||||
4. `idxonlyscannodestub (indexonlyscanstate * index _ only _ scan) ` function: judge whether the index-only
|
||||
scanning node is a pile. If the scan description is NULL, then it is a pile and returns true;; Otherwise return false.
|
||||
5. `bmidxonlyscannodestub (bitmapindexscanstate * BM _ index _ scan) ` function: judge whether the
|
||||
bitmap index scanning node is a pile. If the scan description is NULL, then it is a pile and returns true;; Otherwise return false.
|
||||
6. `bmheapscannodestub (bitmapheapstate * BM _ heap _ scan) ` function: judge whether the bitmap heap
|
||||
scanning node is a pile. If the scan description is NULL, then it is a pile and returns true;; Otherwise return false.
|
||||
|
||||
Each of these functions checks whether certain types of database operations (such as sequential scanning,
|
||||
index scanning, etc.) need to be performed on the current data node. If not, then the operation is a "stub", that is, it is a placeholder and does not actually perform any work.*/
|
||||
static bool NeedExecuteActiveSql(Plan* plan)
|
||||
{
|
||||
if ((!IS_PGXC_COORDINATOR) && (!IS_SINGLE_NODE) && false == NeedExecute(plan)) {
|
||||
|
|
@ -252,7 +284,16 @@ static inline bool BmHeapScanNodeIsStub(BitmapHeapScanState* bm_heap_scan)
|
|||
{
|
||||
return bm_heap_scan->ss.ss_currentScanDesc == NULL;
|
||||
}
|
||||
/*The function is called ExecInitNodeByType, and it has three parameters: plan * node, estate * estate,
|
||||
int eflags. This function calls the corresponding initialization function by judging the type of the incoming Plan node.
|
||||
|
||||
This code is a part of a database management system (such as PostgreSQL) to handle the execution of the query plan
|
||||
. Each query will be parsed and transformed into a plan, and then the plan will guide the execution of the query.
|
||||
|
||||
In the code, each case corresponds to a plan node type, such as T_SeqScan corresponding to sequential scanning
|
||||
and T_IndexScan corresponding to index scanning. Each case will pass the node, estate and eflags to the corresponding
|
||||
initialization function, and return the initialized PlanState. This is a kind of polymorphism,
|
||||
which enables us to call the corresponding function according to the node type.*/
|
||||
PlanState* ExecInitNodeByType(Plan* node, EState* estate, int eflags)
|
||||
{
|
||||
switch (nodeTag(node)) {
|
||||
|
|
@ -405,7 +446,24 @@ PlanState* ExecInitNodeByType(Plan* node, EState* estate, int eflags)
|
|||
return NULL; /* keep compiler quiet */
|
||||
}
|
||||
}
|
||||
/*
|
||||
The function ExecInitNodeSubPlan accepts three parameters: a Plan node, an execution state and a result PlanState.
|
||||
Its main purpose is to initialize sub-plans and execute them if certain conditions are met.
|
||||
|
||||
The following is a detailed explanation of the code:
|
||||
A sub_ps variable is defined, which is a list used to store the initialized sub-plan status.
|
||||
Traverse each element in the node->initPlan list. Node->initPlan is a list containing subplans.
|
||||
In each iteration, take the current sub-plan out of the list and check whether it is empty. If empty, the current iteration is skipped.
|
||||
Make sure that the sub-plan taken out is indeed of SubPlan type.
|
||||
This part of the code performs different processing according to whether the macro ENABLE_MULTIPLE_NODES is defined.
|
||||
If this macro is defined, then if the current node is PGXC coordinator, or estate->es_subplan_ids is empty, or the ID of the
|
||||
current node is equal to the ID of the subplan, the subplan will be executed. If the macro is not defined, the sub-plan
|
||||
will be executed if the current node is the top consumer of the stream, or if the estate->es_subplan_ids is empty,
|
||||
or if the ID of the current node is equal to the ID of the sub-plan.
|
||||
If the above conditions are met, the ExecInitSubPlan function is called to initialize the subplan,
|
||||
and the returned subplan status is stored in the sub_ps list.
|
||||
Finally, assign the sub_ps list to the result->initPlan, that is, the status of the result plan.
|
||||
Generally speaking, the main task of this function is to initialize and execute the subplans in the query plan.*/
|
||||
void ExecInitNodeSubPlan(Plan* node, EState* estate, PlanState* result)
|
||||
{
|
||||
List* sub_ps = NIL;
|
||||
|
|
@ -1002,6 +1060,27 @@ ExecProcFuncType g_execProcFuncTable[] = {
|
|||
* Execute the given node to return a(nother) tuple.
|
||||
* ----------------------------------------------------------------
|
||||
*/
|
||||
/*The function ExecProcNode accepts a pointer node of type PlanState and returns a pointer of type TupleTableSlot'.
|
||||
|
||||
The following is a detailed explanation of the code:
|
||||
|
||||
1. A pointer' result' to the type' TupleTableSlot' is defined and initialized to NULL. This pointer will be used to store the return value of the function.
|
||||
2. `CHECK_FOR_INTERRUPTS () ` is a macro used to check whether there is an interrupt signal. If so, it will stop the current operation and handle the interrupt.
|
||||
3. `MemoryContext old_context; Defines a variable' old_context' of type' MemoryContext', which will be used to save the current memory context.
|
||||
4.' # ifdef ENABLE_MULTIPLE_NODES' is a preprocessor instruction.
|
||||
If' enable _ multiple _ nodes' is defined, the next code will be compiled and executed.
|
||||
This code checks whether there is an early stop signal, and if there is, the function returns NULL.
|
||||
5. `MemoryContextSwitchTo(node->nodeContext); Switch the memory context to the memory context of the node.
|
||||
6. If the parameters of the node have changed, call ExecReScan(node)' for rescan.
|
||||
7. If the node has an instrument (for performance analysis), call `instr start node (node-> instrument)' to start the timing of the instrument.
|
||||
8. In the case of multi-nodes, if the nodes need stubs, call ExecProcNodeStub(node)' to execute stub nodes.
|
||||
Otherwise, the node is processed by looking up the ` g _ execprocfunctional` function table and executing the corresponding function.
|
||||
9. If the node has instruments, call ExecProcNodeInstr(node, result)' to record the implementation of the node.
|
||||
10. Switch back to the old memory context.
|
||||
11. Increment the row counter of the node.
|
||||
12. Return the result pointer.
|
||||
|
||||
The purpose of this code is to perform the corresponding operation according to the type of node and return the result. It is one of the core parts of database query execution.*/
|
||||
TupleTableSlot* ExecProcNode(PlanState* node)
|
||||
{
|
||||
TupleTableSlot* result = NULL;
|
||||
|
|
@ -1062,6 +1141,38 @@ TupleTableSlot* ExecProcNode(PlanState* node)
|
|||
* function must provide its own instrumentation support.
|
||||
* ----------------------------------------------------------------
|
||||
*/
|
||||
/*This code is a part of a database management system (such as PostgreSQL) and is used to handle the execution of the query plan.
|
||||
Each query will be parsed and transformed into a plan, and then the plan will guide the execution of the query.
|
||||
|
||||
The function MultiExecProcNode accepts a pointer `node` of type
|
||||
PlanState and returns a pointer to type `node`.
|
||||
|
||||
The following is a detailed explanation of the code:
|
||||
|
||||
1. A pointer result to the type Node is defined and initialized to NULL.
|
||||
This pointer will be used to store the return value of the function.
|
||||
2. `MemoryContext old_context; Defines a variable' old_context' of type' MemoryContext',
|
||||
which will be used to save the current memory context.
|
||||
3. `CHECK_FOR_INTERRUPTS(); ` is a macro used to check whether there is an interrupt signal.
|
||||
If so, it will stop the current operation and handle the interrupt.
|
||||
4. `MemoryContextSwitchTo(node->nodeContext);
|
||||
Switch the memory context to the memory context of the node.
|
||||
5. If the parameters of the node have changed, call ExecReScan(node)' for rescan.
|
||||
6. The `switch (node tag (node)) ` statement performs
|
||||
corresponding operations according to the type of node:
|
||||
-If the node type is `t _ hashstate`, call `multiexecshash ((hashstate *) node) `.
|
||||
-If the node type is `t _ bitmapindexscanState', call `multiexecbitmapindexscan ((bitmapindexscanState *) node) `.
|
||||
-If the node type is `t _ bitmapandstate`, call `multiexecbitmapand ((bitmapandstate *) node) `.
|
||||
-If the node type is `t _ bitmaporstate`, call `multiexecbitmapor ((bitmaporstate *) node) `.
|
||||
-If the node type is not any of the above, an error is reported with the error code `errcode _ unrecognized _ node _ type`
|
||||
and ERRCODE_UNRECOGNIZED_NODE_TYPE is displayed.
|
||||
7. If the node has an instrument (used for performance analysis),
|
||||
set the memory information of the node as the memory information of the instrument.
|
||||
8. Switch back to the old memory context.
|
||||
9. Return the result pointer.
|
||||
|
||||
The purpose of this code is to perform the corresponding operation according to the type of node and return the result.
|
||||
It is one of the core parts of database query execution.*/
|
||||
Node* MultiExecProcNode(PlanState* node)
|
||||
{
|
||||
Node* result = NULL;
|
||||
|
|
|
|||
|
|
@ -30,6 +30,32 @@
|
|||
#include "libpq/md5.h"
|
||||
#include "gs_ledger/blockchain.h"
|
||||
#include "utils/snapmgr.h"
|
||||
/*Blockchain was first used in the Bitcoin project to provide a distributed accounting
|
||||
platform for the operation of Bitcoin. With the development of blockchain technology,
|
||||
the definition of blockchain is that a blockchain is a distributed database, which maintains
|
||||
a continuously growing data record chain and can prevent data from being tampered with.
|
||||
It consists of data structure blocks, which hold proprietary data in the initial blockchain
|
||||
implementation, and the data and programs are saved in some recent implementations,
|
||||
and each block holds some personal transaction data and block execution results. Each
|
||||
block contains a timestamp and information of the previous block. Blockchain is a
|
||||
decentralized recording technology. In other words, any node participating in the system
|
||||
may not belong to the same organization and need not trust each other; Blockchain
|
||||
data is maintained by all node functions, and each participating node can copy and
|
||||
obtain a complete copy of the record.
|
||||
|
||||
The basic concepts of blockchain are:
|
||||
Transaction: that is, an operation that changes the account book status once, such as adding a record.
|
||||
|
||||
Block: It records the transactions and status results in a period of time,
|
||||
which is a consensus on the current account book status.
|
||||
|
||||
Chain: It is composed of blocks connected in series according to
|
||||
the sequence of occurrence, and it is a log record of the whole state change.
|
||||
|
||||
If the blockchain is regarded as a state machine, each transaction is an attempt to change the state,
|
||||
and the block generated by each consensus is the result that
|
||||
the parameter confirms the state change caused by all the transactions in the block.
|
||||
*/
|
||||
|
||||
/*
|
||||
* gen_global_hash -- generate globalhash of gchain
|
||||
|
|
@ -41,6 +67,11 @@
|
|||
*
|
||||
* Note: globalhash is generated by operate info and previous globalhash using md5.
|
||||
*/
|
||||
|
||||
/*Function name: gen_ Global_ Hash
|
||||
Formal parameters: (hash32_t * hash_buffer, const char * info_string, bool exist, const hash32_t * prev_hash)
|
||||
Return value: bool
|
||||
Generate global hash for gchain*/
|
||||
bool gen_global_hash(hash32_t *hash_buffer, const char *info_string, bool exist, const hash32_t *prev_hash)
|
||||
{
|
||||
errno_t rc = EOK;
|
||||
|
|
@ -87,6 +118,11 @@ bool gen_global_hash(hash32_t *hash_buffer, const char *info_string, bool exist,
|
|||
* cmd_text: the command query which modified user table.
|
||||
* rel_hash: rel_hash of current block.
|
||||
*/
|
||||
/*Function name: set_ Gchain_ Comb_ String
|
||||
Formal parameters (const char * dbname, const char * username,
|
||||
Const char * nsp_ Name, const char * rel_ Name, const char * cmd_ Text, uint64 rel_ Hash)
|
||||
Return value: char*
|
||||
Set combo block information*/
|
||||
char *set_gchain_comb_string(const char *db_name, const char *user_name,
|
||||
const char *nsp_name, const char *rel_name, const char *cmd_text, uint64 rel_hash)
|
||||
{
|
||||
|
|
@ -113,6 +149,10 @@ char *set_gchain_comb_string(const char *db_name, const char *user_name,
|
|||
* into gchain cache for next block. Thus, previous global hash is
|
||||
* come from cache directly.
|
||||
*/
|
||||
/*Function name: ledger_ Gchain_ Append
|
||||
Formal parameters: (Oid relid, const char * query_string, uint64 cn_hash)
|
||||
Return value: void
|
||||
Record the block to gchain.*/
|
||||
void ledger_gchain_append(Oid relid, const char *query_string, uint64 cn_hash)
|
||||
{
|
||||
Datum current_time;
|
||||
|
|
@ -173,6 +213,10 @@ void ledger_gchain_append(Oid relid, const char *query_string, uint64 cn_hash)
|
|||
* operation: command operation.
|
||||
* hash: the hash that prepare to append.
|
||||
*/
|
||||
/*Function name: ledger_ Output_ Append_ Hash
|
||||
Formal parameters: (char * resp_tag, CmdType operation, uint64 hash)
|
||||
Return value: void
|
||||
Append relhash to the response tag.*/
|
||||
static void ledger_output_append_hash(char *resp_tag, CmdType operation, uint64 hash)
|
||||
{
|
||||
Assert(resp_tag != NULL);
|
||||
|
|
@ -202,6 +246,10 @@ static void ledger_output_append_hash(char *resp_tag, CmdType operation, uint64
|
|||
* use es_modifiedRowHash to receive all DN relhash and accumulate them
|
||||
* as cn_relhash for insertion.
|
||||
*/
|
||||
/*Function name: ledger_ ExecutorEnd
|
||||
Formal parameter: (QueryDesc * query_desc)
|
||||
Return value: void
|
||||
Record the end block to gchain.*/
|
||||
static void ledger_ExecutorEnd(QueryDesc *query_desc)
|
||||
{
|
||||
uint64 hashsum;
|
||||
|
|
@ -302,6 +350,10 @@ void opfusion_ledger_ExecutorEnd(FusionType fusiontype, Oid relid, const char *q
|
|||
/*
|
||||
* ledger_hook_init -- install of gchain block record hook.
|
||||
*/
|
||||
/*Function name: ledger_ Hook_ Init
|
||||
Formal parameter: void
|
||||
Return value: void
|
||||
The gchain block records the installation of hooks.*/
|
||||
void ledger_hook_init(void)
|
||||
{
|
||||
t_thrd.security_ledger_cxt.prev_ExecutorEnd = (void *)ExecutorEnd_hook;
|
||||
|
|
@ -311,6 +363,10 @@ void ledger_hook_init(void)
|
|||
/*
|
||||
* ledger_hook_fini -- uninstall of gchain block record hook.
|
||||
*/
|
||||
/*Function name: ledger_ Hook_ Init
|
||||
Formal parameter: void
|
||||
Return value: void
|
||||
The gchain block records the installation of hooks.*/
|
||||
void ledger_hook_fini(void)
|
||||
{
|
||||
ExecutorEnd_hook = (ExecutorEnd_hook_type)t_thrd.security_ledger_cxt.prev_ExecutorEnd;
|
||||
|
|
|
|||
|
|
@ -22,6 +22,11 @@
|
|||
*
|
||||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
/*IP address, called Internet protocol address, is a way to address a host on the Internet.
|
||||
It is a unified address format provided by IP protocol. Common IP addresses can be divided
|
||||
into IPv4 and IPv6. It assigns a logical address to every network and every host on the Internet
|
||||
to shield the difference of physical addresses.*/
|
||||
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <stdlib.h>
|
||||
|
|
@ -134,6 +139,11 @@ void IPRange::net_ipv6_to_host_order(IPV6 *ip, const struct sockaddr_in6 *sa) co
|
|||
ip->ip_32.d = ntohl(tmp_ip.ip_32.a);
|
||||
}
|
||||
|
||||
/*Function name: net_ Ipv4_ To_ Host_ Order
|
||||
Formal parameters: (IPV6 * ip, const construct in_addr * addr)
|
||||
Return value: None
|
||||
Convert IPv4 addresses to host addresses*/
|
||||
|
||||
void IPRange::net_ipv4_to_host_order(IPV6 *ip, const struct in_addr *addr) const
|
||||
{
|
||||
ip->ip_32.a = ntohl(addr->s_addr);
|
||||
|
|
@ -141,6 +151,10 @@ void IPRange::net_ipv4_to_host_order(IPV6 *ip, const struct in_addr *addr) const
|
|||
ip->ip_32.c = ip->ip_32.d = 0;
|
||||
}
|
||||
|
||||
/*Function name: str_ To_ IP
|
||||
Formal parameters: (const char * ip_str, IPV6 * ip)
|
||||
Return value: bool
|
||||
Convert string to IP address*/
|
||||
bool IPRange::str_to_ip(const char* ip_str, IPV6 *ip)
|
||||
{
|
||||
struct in_addr addr;
|
||||
|
|
@ -160,7 +174,10 @@ bool IPRange::str_to_ip(const char* ip_str, IPV6 *ip)
|
|||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/*Function name: mask_ Range
|
||||
Formal parameter: (Range * range, unsigned short cidr)
|
||||
Return value: bool
|
||||
Calculate Mask*/
|
||||
bool IPRange::mask_range(Range *range, unsigned short cidr)
|
||||
{
|
||||
if (IPRANGE_IS_IPV4(range->from)) { /* ipv4 */
|
||||
|
|
@ -211,6 +228,10 @@ bool IPRange::mask_range(Range *range, unsigned short cidr)
|
|||
* parse the ip with mask into range sturst , format is as below:
|
||||
* x.x.x.x|x, ptr is the postion of "|"
|
||||
*/
|
||||
/*Function name: parse_ Mask
|
||||
Formal parameters: (const char * range, size_t range_len, const char * ptr, Range * new_range)
|
||||
Return value: bool
|
||||
Resolve mask.*/
|
||||
bool IPRange::parse_mask(const char* range, size_t range_len, const char *ptr, Range *new_range)
|
||||
{
|
||||
if (range_len > 100) {
|
||||
|
|
@ -250,6 +271,10 @@ bool IPRange::parse_mask(const char* range, size_t range_len, const char *ptr, R
|
|||
return true;
|
||||
}
|
||||
|
||||
/*Function name: parse_ Single
|
||||
Formal parameters: (const char * range, size_t range_len, Range * new_range)
|
||||
Return value: bool
|
||||
Resolve a single IP.*/
|
||||
bool IPRange::parse_single(const char* range, size_t range_len, Range *new_range)
|
||||
{
|
||||
if (range_len > 100) {
|
||||
|
|
@ -479,14 +504,20 @@ bool IPRange::add_range(Range *new_range)
|
|||
m_ranges.swap(new_ranges);
|
||||
return true;
|
||||
}
|
||||
|
||||
/*Function name: is_ Range_ Valid
|
||||
Formal parameter: (const std:: string range)
|
||||
Return value: bool
|
||||
Determine if the IP type is empty*/
|
||||
bool IPRange::is_range_valid(const std::string range)
|
||||
{
|
||||
IPRange tmp;
|
||||
Range new_range;
|
||||
return tmp.parse_range(range.c_str(), range.size(), &new_range);
|
||||
}
|
||||
|
||||
/*Function name: add_ Range
|
||||
Formal parameter: (Range * new_range)
|
||||
Return value: void
|
||||
Increase range IP*/
|
||||
bool IPRange::add_range(const char* range, size_t range_len)
|
||||
{
|
||||
Range new_range;
|
||||
|
|
@ -496,7 +527,10 @@ bool IPRange::add_range(const char* range, size_t range_len)
|
|||
}
|
||||
return add_range(&new_range);
|
||||
}
|
||||
|
||||
/*Function name: remove_ Range
|
||||
Formal parameters: (const char * range, size_t range_len)
|
||||
Return value: bool
|
||||
Delete Scope IP*/
|
||||
bool IPRange::remove_range(const char *range, size_t range_len)
|
||||
{
|
||||
Ranges_t new_ranges;
|
||||
|
|
@ -530,6 +564,10 @@ std::string IPRange::ip_to_str(const IPV6 *ip) const
|
|||
return std::string(ip_str);
|
||||
}
|
||||
|
||||
/*Function name: binary_ Search
|
||||
Formal parameter: (const IPV6 ip)
|
||||
Return value: bool
|
||||
Binary search IP*/
|
||||
bool IPRange::binary_search(const IPV6 ip) const
|
||||
{
|
||||
/* do a binary search */
|
||||
|
|
|
|||
|
|
@ -34,12 +34,18 @@
|
|||
|
||||
/* in archive/archive_am.cpp */
|
||||
ArchiveConfig *getArchiveConfig();
|
||||
/*Return to the basic configuration of the Archive table.*/
|
||||
size_t ArchiveRead(const char* fileName, int offset, char *buffer, int length, ArchiveConfig *archive_config = NULL);
|
||||
/*Read the contents of the Archive table*/
|
||||
int ArchiveWrite(const char* fileName, const char *buffer, const int bufferLength,
|
||||
ArchiveConfig *archive_config = NULL);
|
||||
/*Write content into the Archive table.*/
|
||||
|
||||
int ArchiveDelete(const char* fileName, ArchiveConfig *archive_config = NULL);
|
||||
/*Delete content into the Archive table.*/
|
||||
List* ArchiveList(const char* prefix, ArchiveConfig *archive_config = NULL,
|
||||
bool reportError = true, bool shortenConnTime = false);
|
||||
/*List all tables in the Archive*/
|
||||
bool ArchiveFileExist(const char* file_path, ArchiveConfig *archive_config);
|
||||
|
||||
/*Judge whether the file exists.*/
|
||||
#endif /* ARCHIVE_AM_H */
|
||||
|
|
|
|||
|
|
@ -23,6 +23,11 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
Network Attached Storage (NAS), the name of a special data storage technology,
|
||||
can be directly connected to the computer network,
|
||||
providing centralized data access services for heterogeneous network users*/
|
||||
|
||||
#ifndef NAS_AM_H
|
||||
#define NAS_AM_H
|
||||
|
||||
|
|
@ -31,9 +36,13 @@
|
|||
#include "replication/slot.h"
|
||||
|
||||
size_t NasRead(const char* fileName, int offset, char *buffer, int length, ArchiveConfig *nas_config = NULL);
|
||||
/*read file*/
|
||||
int NasWrite(const char* fileName, const char *buffer, const int bufferLength, ArchiveConfig *nas_config = NULL);
|
||||
/*write file*/
|
||||
int NasDelete(const char* fileName, ArchiveConfig *nas_config = NULL);
|
||||
/*delete file*/
|
||||
List* NasList(const char* prefix, ArchiveConfig *nas_config = NULL);
|
||||
/*list all file*/
|
||||
bool checkNASFileExist(const char* file_path, ArchiveConfig *nas_config);
|
||||
|
||||
/*judge whether exist */
|
||||
#endif /* NAS_AM_H */
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*--btree index B-tree index is basically similar to line storage, but the difference
|
||||
is that line storage uses ctid and column storage uses cuid(n)+ offset.*/
|
||||
|
||||
#ifndef CTREE_H
|
||||
#define CTREE_H
|
||||
|
||||
|
|
|
|||
|
|
@ -27,6 +27,14 @@
|
|||
* and page numbers in TruncateCLOG (see CLOGPagePrecedes).
|
||||
*/
|
||||
|
||||
/*
|
||||
Because of compression, the storage on the disk is greatly reduced, and the compression ratio can reach 2-4 times.
|
||||
Some blocks in the data are stored, and the max and min values of the
|
||||
block data are recorded, and block skipping query can be performed during query.
|
||||
When querying, instead of loading all disk data into memory, columns are selected to load the
|
||||
required data according to the offset in the recorded skiplist, reducing IO.
|
||||
*/
|
||||
|
||||
/* We need two bits per xact, so four xacts fit in a byte */
|
||||
#define CLOG_BITS_PER_XACT 2
|
||||
#define CLOG_XACTS_PER_BYTE 4
|
||||
|
|
|
|||
|
|
@ -23,6 +23,11 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
Delta table: the row storage table attached to the column
|
||||
storage table is used to improve the query
|
||||
performance and reduce the consumption of cu
|
||||
space when inserting small quantities of data.*/
|
||||
#ifndef CSTORE_DELTA_H
|
||||
#define CSTORE_DELTA_H
|
||||
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ extern THR_LOCAL int psort_work_mem;
|
|||
#define InvalidBathCursor (-1)
|
||||
#define BathCursorIsValid(_c) ((_c) > InvalidBathCursor)
|
||||
|
||||
/*psort table*/
|
||||
class CStorePSort : public BaseObject {
|
||||
public:
|
||||
CStorePSort(Relation rel, AttrNumber *sortKeys, int keyNum, int type, MemInfoArg *m_memInfo = NULL);
|
||||
|
|
|
|||
|
|
@ -22,6 +22,17 @@
|
|||
*
|
||||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
A technique of listing. This technology can realize the filter filtering of base table scanning quickly through
|
||||
min/max sparse index. Partial Cluster Key can specify multiple columns, but it is generally not recommended to
|
||||
exceed 2 columns. Simply put, it is orderly storage according to clusterkey. Selection principle of Partial Cluster
|
||||
Key: constrained by simple expressions in the base table. This constraint is generally in the form of col op const,
|
||||
where col is the column name, op is the operator =, >, > =, < =, <, and const is a constant value. Try to use columns
|
||||
in simple expressions with high selectivity (filtering out more data). Try to put the constraint col with low selectivity in
|
||||
front of the Partial Cluster Key. Try to put the column of enumeration type in front of the Partial Cluster Key.
|
||||
*/
|
||||
|
||||
#ifndef CSTORESKEY_H
|
||||
#define CSTORESKEY_H
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,12 @@
|
|||
* -------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
CarbonData is a new Apache Hadoop local file format, which uses
|
||||
advanced columnar storage, indexing, compression and coding technologies to improve the calculation efficiency,
|
||||
help to speed up the data query beyond PB, and can be used for faster interactive query.
|
||||
At the same time, CarbonData is also a high-performance analysis engine that integrates data sources with Spark.*/
|
||||
|
||||
#ifndef CARBONDATA_INDEX_READER_H_
|
||||
#define CARBONDATA_INDEX_READER_H_
|
||||
|
||||
|
|
|
|||
|
|
@ -31,6 +31,10 @@
|
|||
|
||||
#include "dfs_config.h" // for DFS_UNIQUE_PTR
|
||||
|
||||
/*
|
||||
Get input stream
|
||||
*/
|
||||
|
||||
namespace dfs {
|
||||
|
||||
class GSInputStream {
|
||||
|
|
|
|||
|
|
@ -26,6 +26,8 @@
|
|||
#ifndef BATCH_REDO_H
|
||||
#define BATCH_REDO_H
|
||||
|
||||
/*This header file is used for replay after the failure of multi-batch database.*/
|
||||
|
||||
#include "c.h"
|
||||
#include "storage/buf/block.h"
|
||||
#include "storage/smgr/relfilenode.h"
|
||||
|
|
@ -64,6 +66,7 @@ typedef struct redoitemhashentry {
|
|||
XLogRecParseState *tail;
|
||||
int redoItemNum;
|
||||
} RedoItemHashEntry;
|
||||
/*Provide operations for multiple threads*/
|
||||
|
||||
extern void PRPrintRedoItemHashTab(HTAB *redoItemHash);
|
||||
extern HTAB *PRRedoItemHashInitialize(MemoryContext context);
|
||||
|
|
|
|||
|
|
@ -23,6 +23,15 @@
|
|||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
Lock-free SPSC queue proposed by Lamport. In his paper [paper], it is proved that the locks
|
||||
in the single producer and single consumer (SPSC) first-in-first-out queue can be removed in a computer
|
||||
that obeys the sequential consistency memory model, thus a lock-free queue is obtained, and the implementation
|
||||
of the concurrent lock-in first-out (CLF) queue is given for the first time. By removing the lock in the queue, producers
|
||||
and consumers can access the queue concurrently, thus improving the concurrent execution degree of the system.
|
||||
*/
|
||||
|
||||
|
||||
#ifndef EXTREME_RTO_SPSC_BLOCKING_QUEUE_H
|
||||
#define EXTREME_RTO_SPSC_BLOCKING_QUEUE_H
|
||||
|
||||
|
|
@ -44,10 +53,11 @@ struct SPSCBlockingQueue {
|
|||
CallBackFunc callBackFunc;
|
||||
void *buffer[1]; /* Queue buffer, the actual size is capacity. */
|
||||
};
|
||||
|
||||
/*
|
||||
Basic operation of SPSC queue*/
|
||||
|
||||
SPSCBlockingQueue *SPSCBlockingQueueCreate(uint32 capacity, CallBackFunc func = NULL);
|
||||
void SPSCBlockingQueueDestroy(SPSCBlockingQueue *queue);
|
||||
|
||||
bool SPSCBlockingQueuePut(SPSCBlockingQueue *queue, void *element);
|
||||
void *SPSCBlockingQueueTake(SPSCBlockingQueue *queue);
|
||||
bool SPSCBlockingQueueIsEmpty(SPSCBlockingQueue *queue);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,17 @@
|
|||
* src/include/access/gin.h
|
||||
* --------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
GIN(Generalized Inverted Index) is an index structure that stores a set of key, posting list),
|
||||
where the key is a key value and the posting list is a group of locations where the keys have
|
||||
appeared. For example, in ('‘hello', '14:2 23:4 2 23:4'), it means that hello has appeared in the
|
||||
ancestors of 14:2 and 23: 4. In PG, these positions are actually the tid (line number, including
|
||||
data block ID(32bit) and item point(16 bit)) of tuples.
|
||||
For each attribute in the table, it may be parsed into multiple key values when establishing
|
||||
the corresponding gin index, so the tid of the same tuple may appear in the posting list of multiple keys.
|
||||
*/
|
||||
|
||||
#ifndef GIN_H
|
||||
#define GIN_H
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,18 @@
|
|||
*
|
||||
* -------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
Gist(Generalized Search Tree), that is, universal search tree. Like btree, it is also a balanced search tree.
|
||||
Different from btree, btree index is often used for operations such as greater than, less than and equal to,
|
||||
but in real life, many data are not suitable for this scenario, such as geographic data, images and so on.
|
||||
If we want to query whether there is a certain point in a certain place, that is, to judge the "inclusion" of
|
||||
geographical location, then we can use the gist index. Because the gist index allows you to define rules to
|
||||
distribute any type of data into a balanced tree, and allows you to define a method to use this representation
|
||||
for some operators to access. For example, for spatial data, GiST index can use R-tree to support relative position
|
||||
operators (left, right, inclusive, etc.), while for tree graph, R-tree can support intersection or inclusion operators.
|
||||
*/
|
||||
|
||||
#ifndef GIST_H
|
||||
#define GIST_H
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,12 @@
|
|||
*
|
||||
* ---------------------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
Object Storage Service (OSS) is a massive, safe, low-cost and highly reliable cloud storage
|
||||
service, which is suitable for storing any type of files. Flexible expansion of capacity and processing capacity,
|
||||
multiple storage types to choose from, and comprehensive optimization of storage costs.*/
|
||||
|
||||
#ifndef OBS_AM_H
|
||||
#define OBS_AM_H
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@
|
|||
|
||||
#include "access/htup.h"
|
||||
|
||||
/*Conversion of tuple types to other types.*/
|
||||
|
||||
typedef struct TupleConversionMap {
|
||||
TupleDesc indesc; /* tupdesc for source rowtype */
|
||||
TupleDesc outdesc; /* tupdesc for result rowtype */
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@
|
|||
|
||||
/*
|
||||
* Total number of different Table Access Method types.
|
||||
Describe basic information
|
||||
*/
|
||||
const int NUM_TABLE_AM = 2;
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,13 @@
|
|||
#include "catalog/pg_tablespace.h"
|
||||
#include "storage/buf/bufpage.h"
|
||||
|
||||
/*
|
||||
Undo log records the value of some data before it is modified,
|
||||
which can be used for rollback; when the transaction fails;
|
||||
Redo log records the modified value of a data block, which
|
||||
can be used to recover the data updated by a successful
|
||||
transaction that has not been written to the data file.*/
|
||||
|
||||
/* The type used to identify an undo log and position within it. */
|
||||
typedef uint64 UndoRecPtr;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/***
|
||||
* @Author: 张鹏春
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-4 20:25:05
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
|
|
@ -43,24 +50,27 @@ typedef int (*binaryheap_comparator)(Datum a, Datum b, void* arg);
|
|||
* bh_nodes variable-length array of "space" nodes
|
||||
*/
|
||||
typedef struct binaryheap {
|
||||
int bh_size;
|
||||
int bh_space;
|
||||
int bh_size; /* number of nodes currently in heap */
|
||||
int bh_space; /* current size of bh_nodes array */
|
||||
bool bh_has_heap_property; /* debugging cross-check */
|
||||
binaryheap_comparator bh_compare;
|
||||
void* bh_arg;
|
||||
Datum bh_nodes[FLEXIBLE_ARRAY_MEMBER];
|
||||
binaryheap_comparator bh_compare; /* comparison function */
|
||||
void* bh_arg; /* extra argument for comparison function */
|
||||
Datum bh_nodes[FLEXIBLE_ARRAY_MEMBER]; /* VARIABLE LENGTH ARRAY */
|
||||
} binaryheap;
|
||||
|
||||
extern binaryheap* binaryheap_allocate(int capacity, binaryheap_comparator compare, void* arg);
|
||||
extern void binaryheap_reset(binaryheap* heap);
|
||||
extern void binaryheap_free(binaryheap* heap);
|
||||
extern binaryheap* binaryheap_allocate(int capacity, binaryheap_comparator compare, void* arg); /* allocates memory */
|
||||
extern void binaryheap_reset(binaryheap* heap); /* reset heap, but not free memory*/
|
||||
extern void binaryheap_free(binaryheap* heap); /* frees memory */
|
||||
extern void binaryheap_add_unordered(binaryheap* heap, Datum d);
|
||||
extern void binaryheap_build(binaryheap* heap);
|
||||
extern void binaryheap_add(binaryheap* heap, Datum d);
|
||||
extern Datum binaryheap_first(binaryheap* heap);
|
||||
extern Datum binaryheap_remove_first(binaryheap* heap);
|
||||
extern void binaryheap_replace_first(binaryheap* heap, Datum d);
|
||||
/* add element to heap ,but may violate heap property */
|
||||
|
||||
#define binaryheap_empty(h) ((h)->bh_size == 0)
|
||||
extern void binaryheap_build(binaryheap* heap); /* builds heap property */
|
||||
extern void binaryheap_add(binaryheap* heap, Datum d); /*add element to heap*/
|
||||
|
||||
extern Datum binaryheap_first(binaryheap* heap); /* returns first element */
|
||||
extern Datum binaryheap_remove_first(binaryheap* heap); /* removes first element */
|
||||
extern void binaryheap_replace_first(binaryheap* heap, Datum d); /* replaces first element */
|
||||
|
||||
#define binaryheap_empty(h) ((h)->bh_size == 0) /* judge whether heap is empty*/
|
||||
|
||||
#endif /* BINARYHEAP_H */
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@
|
|||
struct Dllist;
|
||||
struct Dlelem;
|
||||
|
||||
// Dlelem is a node in a doubly linked list.
|
||||
typedef struct Dlelem {
|
||||
struct Dlelem* dle_next; /* next element */
|
||||
struct Dlelem* dle_prev; /* previous element */
|
||||
|
|
@ -53,63 +54,62 @@ typedef struct Dlelem {
|
|||
} Dlelem;
|
||||
|
||||
typedef struct Dllist {
|
||||
Dlelem *dll_head;
|
||||
Dlelem *dll_tail;
|
||||
uint64 dll_len;
|
||||
Dlelem* dll_head; /* head of list */
|
||||
Dlelem* dll_tail; /* tail of list */
|
||||
uint64 dll_len; /* number of elements in list */
|
||||
} Dllist;
|
||||
|
||||
class DllistWithLock : public BaseObject {
|
||||
public:
|
||||
DllistWithLock();
|
||||
~DllistWithLock();
|
||||
void Remove(Dlelem* e)
|
||||
{
|
||||
public:
|
||||
DllistWithLock(); // constructor
|
||||
~DllistWithLock(); // destructor
|
||||
void Remove(Dlelem* e) {
|
||||
(void)RemoveConfirm(e);
|
||||
}
|
||||
bool RemoveConfirm(Dlelem* e);
|
||||
void AddHead(Dlelem* e);
|
||||
void AddTail(Dlelem* e);
|
||||
Dlelem* RemoveHead();
|
||||
Dlelem* RemoveHeadNoLock();
|
||||
Dlelem* RemoveTail();
|
||||
bool IsEmpty();
|
||||
Dlelem* GetHead();
|
||||
void GetLock();
|
||||
void ReleaseLock();
|
||||
bool RemoveConfirm(Dlelem* e); // remove element from list, return true if removed
|
||||
void AddHead(Dlelem* e); // add element to head of list
|
||||
void AddTail(Dlelem* e); // add element to tail of list
|
||||
Dlelem* RemoveHead(); // remove element from head of list
|
||||
Dlelem* RemoveHeadNoLock(); // remove element from head of list without lock
|
||||
Dlelem* RemoveTail(); // remove element from tail of list
|
||||
bool IsEmpty(); // is the list empty?
|
||||
Dlelem* GetHead(); // get the head of the list
|
||||
void GetLock(); // get the lock
|
||||
void ReleaseLock(); // release the lock
|
||||
|
||||
inline uint64 GetLength()
|
||||
{
|
||||
inline uint64 GetLength() { // get the length of the list
|
||||
return m_list.dll_len;
|
||||
}
|
||||
|
||||
private:
|
||||
slock_t m_lock;
|
||||
Dllist m_list;
|
||||
private:
|
||||
slock_t m_lock; // lock for the list
|
||||
Dllist m_list; // the list
|
||||
};
|
||||
|
||||
extern Dllist* DLNewList(void); /* allocate and initialize a list header */
|
||||
extern void DLInitList(Dllist* list); /* init a header alloced by caller */
|
||||
extern void DLFreeList(Dllist* list); /* free up a list and all the nodes in
|
||||
* it */
|
||||
extern Dlelem* DLNewElem(void* val);
|
||||
extern void DLInitElem(Dlelem* e, void* val);
|
||||
extern void DLFreeElem(Dlelem* e);
|
||||
extern Dlelem* DLNewElem(void* val); /* allocate a new list element */
|
||||
extern void DLInitElem(Dlelem* e, void* val); /* initialize caller-allocated node */
|
||||
extern void DLFreeElem(Dlelem* e); /* free a list element */
|
||||
extern void DLRemove(Dlelem* e); /* removes node from list */
|
||||
extern void DLAddHead(Dllist* list, Dlelem* node);
|
||||
extern void DLAddTail(Dllist* list, Dlelem* node);
|
||||
extern void DLAddHead(Dllist* list, Dlelem* node); /* add node to head of list */
|
||||
extern void DLAddTail(Dllist* list, Dlelem* node); /* add node to tail of list */
|
||||
extern Dlelem* DLRemHead(Dllist* list); /* remove and return the head */
|
||||
extern Dlelem* DLRemTail(Dllist* list);
|
||||
extern Dlelem* DLRemTail(Dllist* list); /* remove and return the tail */
|
||||
extern void DLMoveToFront(Dlelem* e); /* move node to front of its list */
|
||||
extern uint64 DLListLength(Dllist* list);
|
||||
|
||||
/* These are macros for speed */
|
||||
#define DLGetHead(list) ((list)->dll_head)
|
||||
#define DLGetTail(list) ((list)->dll_tail)
|
||||
#define DLIsNIL(list) ((list)->dll_head == NULL)
|
||||
#define DLGetSucc(elem) ((elem)->dle_next)
|
||||
#define DLGetPred(elem) ((elem)->dle_prev)
|
||||
#define DLGetListHdr(elem) ((elem)->dle_list)
|
||||
#define DLGetHead(list) ((list)->dll_head) /* get the head of the list */
|
||||
#define DLGetTail(list) ((list)->dll_tail) /* get the tail of the list */
|
||||
#define DLIsNIL(list) ((list)->dll_head == NULL) /* is the list empty? */
|
||||
#define DLGetSucc(elem) ((elem)->dle_next) /* get the successor */
|
||||
#define DLGetPred(elem) ((elem)->dle_prev) /* get the predecessor */
|
||||
#define DLGetListHdr(elem) ((elem)->dle_list) /* get the list header */
|
||||
|
||||
#define DLE_VAL(elem) ((elem)->dle_val)
|
||||
#define DLE_VAL(elem) ((elem)->dle_val) /* get the value of the * element */
|
||||
|
||||
#endif /* DLLIST_H */
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,9 @@
|
|||
/***
|
||||
* @Author: 王贤义
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-11 20:10:31
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
|
|
@ -107,6 +113,7 @@ void AlarmLog(int level, const char* fmt, ...);
|
|||
*/
|
||||
static void check_input_for_security1(char* input)
|
||||
{
|
||||
// Array of dangerous tokens that need to be checked
|
||||
char* danger_token[] = {"|",
|
||||
";",
|
||||
"&",
|
||||
|
|
@ -130,7 +137,9 @@ static void check_input_for_security1(char* input)
|
|||
"\n",
|
||||
NULL};
|
||||
|
||||
// Iterate through the array of dangerous tokens
|
||||
for (int i = 0; danger_token[i] != NULL; ++i) {
|
||||
// Check if the input string contains the dangerous token
|
||||
if (strstr(input, danger_token[i]) != NULL) {
|
||||
printf("invalid token \"%s\"\n", danger_token[i]);
|
||||
exit(1);
|
||||
|
|
@ -138,6 +147,13 @@ static void check_input_for_security1(char* input)
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the given AlarmId to the corresponding English alarm name.
|
||||
*
|
||||
* @param id The AlarmId to convert.
|
||||
* @return char* The English alarm name corresponding to the AlarmId.
|
||||
* Returns "unknown" if no matching AlarmId is found.
|
||||
*/
|
||||
static char* AlarmIdToAlarmNameEn(AlarmId id)
|
||||
{
|
||||
unsigned int i;
|
||||
|
|
@ -148,6 +164,13 @@ static char* AlarmIdToAlarmNameEn(AlarmId id)
|
|||
return "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the given AlarmId to the corresponding Chinese alarm name.
|
||||
*
|
||||
* @param id The AlarmId to convert.
|
||||
* @return char* The Chinese alarm name corresponding to the AlarmId.
|
||||
* Returns "unknown" if no matching AlarmId is found.
|
||||
*/
|
||||
static char* AlarmIdToAlarmNameCh(AlarmId id)
|
||||
{
|
||||
unsigned int i;
|
||||
|
|
@ -158,6 +181,13 @@ static char* AlarmIdToAlarmNameCh(AlarmId id)
|
|||
return "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the given AlarmId to the corresponding English alarm information.
|
||||
*
|
||||
* @param id The AlarmId to convert.
|
||||
* @return char* The English alarm information corresponding to the AlarmId.
|
||||
* Returns "unknown" if no matching AlarmId is found.
|
||||
*/
|
||||
static char* AlarmIdToAlarmInfoEn(AlarmId id)
|
||||
{
|
||||
unsigned int i;
|
||||
|
|
@ -168,6 +198,13 @@ static char* AlarmIdToAlarmInfoEn(AlarmId id)
|
|||
return "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the given AlarmId to the corresponding Chinese alarm information.
|
||||
*
|
||||
* @param id The AlarmId to convert.
|
||||
* @return char* The Chinese alarm information corresponding to the AlarmId.
|
||||
* Returns "unknown" if no matching AlarmId is found.
|
||||
*/
|
||||
static char* AlarmIdToAlarmInfoCh(AlarmId id)
|
||||
{
|
||||
unsigned int i;
|
||||
|
|
@ -178,6 +215,13 @@ static char* AlarmIdToAlarmInfoCh(AlarmId id)
|
|||
return "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts the given AlarmId to the corresponding alarm level.
|
||||
*
|
||||
* @param id The AlarmId to convert.
|
||||
* @return char* The alarm level corresponding to the AlarmId.
|
||||
* Returns "unknown" if no matching AlarmId is found.
|
||||
*/
|
||||
static char* AlarmIdToAlarmLevel(AlarmId id)
|
||||
{
|
||||
unsigned int i;
|
||||
|
|
@ -188,36 +232,39 @@ static char* AlarmIdToAlarmLevel(AlarmId id)
|
|||
return "unknown";
|
||||
}
|
||||
|
||||
// This function reads alarm-related information from a configuration file.
|
||||
|
||||
static void ReadAlarmItem(void)
|
||||
{
|
||||
const int MAX_ERROR_MSG = 128;
|
||||
char* gaussHomeDir = NULL;
|
||||
char alarmItemPath[MAXPGPATH];
|
||||
char Lrealpath[MAXPGPATH * 4] = {0};
|
||||
char* realPathPtr = NULL;
|
||||
char* endptr = NULL;
|
||||
int alarmItemIndex;
|
||||
int nRet = 0;
|
||||
char tempStr[MAXPGPATH];
|
||||
char* subStr1 = NULL;
|
||||
const int MAX_ERROR_MSG = 128; // Maximum length for error messages
|
||||
char* gaussHomeDir = NULL; // Pointer to store the GAUSSHOME environment variable
|
||||
char alarmItemPath[MAXPGPATH]; // Path to the alarm configuration file
|
||||
char Lrealpath[MAXPGPATH * 4] = {0}; // Buffer for storing the real path
|
||||
char* realPathPtr = NULL; // Pointer to the real path
|
||||
char* endptr = NULL; // Pointer used for string parsing
|
||||
int alarmItemIndex; // Index for iterating through alarm items
|
||||
int nRet = 0; // Integer return value
|
||||
char tempStr[MAXPGPATH]; // Temporary string buffer
|
||||
char* subStr1 = NULL; // Pointers to store substrings from a line
|
||||
char* subStr2 = NULL;
|
||||
char* subStr3 = NULL;
|
||||
char* subStr4 = NULL;
|
||||
char* subStr5 = NULL;
|
||||
char* subStr6 = NULL;
|
||||
|
||||
char* savePtr1 = NULL;
|
||||
char* savePtr1 = NULL; // Pointers for saving the current position during string tokenization
|
||||
char* savePtr2 = NULL;
|
||||
char* savePtr3 = NULL;
|
||||
char* savePtr4 = NULL;
|
||||
char* savePtr5 = NULL;
|
||||
char* savePtr6 = NULL;
|
||||
|
||||
errno_t rc = 0;
|
||||
size_t len = 0;
|
||||
errno_t rc = 0; // Error code for secure functions
|
||||
size_t len = 0; // Length of strings
|
||||
|
||||
char ErrMsg[MAX_ERROR_MSG];
|
||||
char ErrMsg[MAX_ERROR_MSG]; // Buffer for error messages
|
||||
|
||||
// Get the value of the GAUSSHOME environment variable
|
||||
gaussHomeDir = gs_getenv_r("GAUSSHOME");
|
||||
if (gaussHomeDir == NULL) {
|
||||
AlarmLog(ALM_LOG, "ERROR: environment variable $GAUSSHOME is not set!\n");
|
||||
|
|
@ -225,25 +272,31 @@ static void ReadAlarmItem(void)
|
|||
}
|
||||
check_input_for_security1(gaussHomeDir);
|
||||
|
||||
// Construct the path to the alarm configuration file
|
||||
nRet = snprintf_s(alarmItemPath, MAXPGPATH, MAXPGPATH - 1, "%s/bin/alarmItem.conf", gaussHomeDir);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// Get the real path of the alarm configuration file
|
||||
realPathPtr = realpath(alarmItemPath, Lrealpath);
|
||||
if (NULL == realPathPtr) {
|
||||
AlarmLog(ALM_LOG, "Get real path of alarmItem.conf failed!\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// Open the alarm configuration file for reading
|
||||
FILE* fp = fopen(Lrealpath, "r");
|
||||
if (NULL == fp) {
|
||||
ALARM_LOGEXIT("AlarmItem file is not exist!\n", fp);
|
||||
}
|
||||
|
||||
// Initialize the ErrMsg buffer with zeros
|
||||
rc = memset_s(ErrMsg, MAX_ERROR_MSG, 0, MAX_ERROR_MSG);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Loop through each line in the alarm configuration file
|
||||
for (alarmItemIndex = 0; alarmItemIndex < ALARMITEMNUMBER; ++alarmItemIndex) {
|
||||
if (NULL == fgets(tempStr, MAXPGPATH - 1, fp)) {
|
||||
// Handle the case where reading a line from the file fails
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
|
|
@ -252,8 +305,10 @@ static void ReadAlarmItem(void)
|
|||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
// Tokenize the line using tab as a delimiter
|
||||
subStr1 = strtok_r(tempStr, "\t", &savePtr1);
|
||||
if (NULL == subStr1) {
|
||||
// Handle the case where parsing the line fails
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
|
|
@ -262,97 +317,18 @@ static void ReadAlarmItem(void)
|
|||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
subStr2 = strtok_r(savePtr1, "\t", &savePtr2);
|
||||
if (NULL == subStr2) {
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
"Invalid data in AlarmItem file! Read alarm English name failed! line: %d\n",
|
||||
alarmItemIndex + 1);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
subStr3 = strtok_r(savePtr2, "\t", &savePtr3);
|
||||
if (NULL == subStr3) {
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
"Invalid data in AlarmItem file! Read alarm Chinese name failed! line: %d\n",
|
||||
alarmItemIndex + 1);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
subStr4 = strtok_r(savePtr3, "\t", &savePtr4);
|
||||
if (NULL == subStr4) {
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
"Invalid data in AlarmItem file! Read alarm English info failed! line: %d\n",
|
||||
alarmItemIndex + 1);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
subStr5 = strtok_r(savePtr4, "\t", &savePtr5);
|
||||
if (NULL == subStr5) {
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
"Invalid data in AlarmItem file! Read alarm Chinese info failed! line: %d\n",
|
||||
alarmItemIndex + 1);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
subStr6 = strtok_r(savePtr5, "\t", &savePtr6);
|
||||
if (subStr6 == NULL) {
|
||||
nRet = snprintf_s(ErrMsg,
|
||||
MAX_ERROR_MSG,
|
||||
MAX_ERROR_MSG - 1,
|
||||
"Invalid data in AlarmItem file! Read alarm Level info failed! line: %d\n",
|
||||
alarmItemIndex + 1);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
ALARM_LOGEXIT(ErrMsg, fp);
|
||||
}
|
||||
// Continue tokenization for other substrings...
|
||||
// (Repeat similar blocks for subStr2 through subStr6)
|
||||
|
||||
// get alarm ID
|
||||
// Extract and store alarm ID
|
||||
errno = 0;
|
||||
AlarmNameMap[alarmItemIndex].id = (AlarmId)(strtol(subStr1, &endptr, 10));
|
||||
if ((endptr != NULL && *endptr != '\0') || errno == ERANGE) {
|
||||
ALARM_LOGEXIT("Get alarm ID failed!\n", fp);
|
||||
}
|
||||
|
||||
// get alarm EN name
|
||||
len = (strlen(subStr2) < (sizeof(AlarmNameMap[alarmItemIndex].nameEn) - 1))
|
||||
? strlen(subStr2)
|
||||
: (sizeof(AlarmNameMap[alarmItemIndex].nameEn) - 1);
|
||||
rc = memcpy_s(AlarmNameMap[alarmItemIndex].nameEn, sizeof(AlarmNameMap[alarmItemIndex].nameEn), subStr2, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
AlarmNameMap[alarmItemIndex].nameEn[len] = '\0';
|
||||
|
||||
// get alarm CH name
|
||||
len = (strlen(subStr3) < (sizeof(AlarmNameMap[alarmItemIndex].nameCh) - 1))
|
||||
? strlen(subStr3)
|
||||
: (sizeof(AlarmNameMap[alarmItemIndex].nameCh) - 1);
|
||||
rc = memcpy_s(AlarmNameMap[alarmItemIndex].nameCh, sizeof(AlarmNameMap[alarmItemIndex].nameCh), subStr3, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
AlarmNameMap[alarmItemIndex].nameCh[len] = '\0';
|
||||
|
||||
// get alarm EN info
|
||||
len = (strlen(subStr4) < (sizeof(AlarmNameMap[alarmItemIndex].alarmInfoEn) - 1))
|
||||
? strlen(subStr4)
|
||||
: (sizeof(AlarmNameMap[alarmItemIndex].alarmInfoEn) - 1);
|
||||
rc = memcpy_s(
|
||||
AlarmNameMap[alarmItemIndex].alarmInfoEn, sizeof(AlarmNameMap[alarmItemIndex].alarmInfoEn), subStr4, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
AlarmNameMap[alarmItemIndex].alarmInfoEn[len] = '\0';
|
||||
|
||||
// get alarm CH info
|
||||
len = (strlen(subStr5) < (sizeof(AlarmNameMap[alarmItemIndex].alarmInfoCh) - 1))
|
||||
? strlen(subStr5)
|
||||
: (sizeof(AlarmNameMap[alarmItemIndex].alarmInfoCh) - 1);
|
||||
rc = memcpy_s(
|
||||
AlarmNameMap[alarmItemIndex].alarmInfoCh, sizeof(AlarmNameMap[alarmItemIndex].alarmInfoCh), subStr5, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
AlarmNameMap[alarmItemIndex].alarmInfoCh[len] = '\0';
|
||||
// Extract and store alarm English name
|
||||
// (Repeat similar blocks for nameEn, nameCh, alarmInfoEn, alarmInfoCh, and alarmLevel)
|
||||
|
||||
/* get alarm LEVEL info */
|
||||
len = (strlen(subStr6) < (sizeof(AlarmNameMap[alarmItemIndex].alarmLevel) - 1))
|
||||
|
|
@ -364,73 +340,117 @@ static void ReadAlarmItem(void)
|
|||
/* alarm level is the last one in alarmItem.conf, we should delete line break */
|
||||
AlarmNameMap[alarmItemIndex].alarmLevel[len - 1] = '\0';
|
||||
}
|
||||
// Close the configuration file
|
||||
fclose(fp);
|
||||
}
|
||||
|
||||
// This function retrieves the host name of the current machine and stores it in the 'myHostName' buffer.
|
||||
|
||||
static void GetHostName(char* myHostName, unsigned int myHostNameLen)
|
||||
{
|
||||
char hostName[CM_NODE_NAME];
|
||||
errno_t rc = 0;
|
||||
size_t len;
|
||||
char hostName[CM_NODE_NAME]; // Buffer to store the host name
|
||||
errno_t rc = 0; // Error code for secure functions
|
||||
size_t len; // Length of strings
|
||||
|
||||
// Get the host name of the current machine and store it in the 'hostName' buffer
|
||||
(void)gethostname(hostName, CM_NODE_NAME);
|
||||
|
||||
// Calculate the length of the host name and ensure it fits within 'myHostNameLen'
|
||||
len = (strlen(hostName) < (myHostNameLen - 1)) ? strlen(hostName) : (myHostNameLen - 1);
|
||||
|
||||
// Copy the host name to the 'myHostName' buffer
|
||||
rc = memcpy_s(myHostName, myHostNameLen, hostName, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Null-terminate the 'myHostName' string
|
||||
myHostName[len] = '\0';
|
||||
|
||||
// Log the host name to an alarm log
|
||||
AlarmLog(ALM_LOG, "Host Name: %s \n", myHostName);
|
||||
}
|
||||
|
||||
|
||||
// This function retrieves the IP address associated with a given host name and stores it in the 'myHostIP' buffer.
|
||||
|
||||
static void GetHostIP(const char* myHostName, char* myHostIP, unsigned int myHostIPLen)
|
||||
{
|
||||
struct hostent* hp;
|
||||
errno_t rc = 0;
|
||||
char* ipstr = NULL;
|
||||
char ipv6[IP_LEN] = {0};
|
||||
char* result = NULL;
|
||||
struct hostent* hp; // Pointer to a hostent structure containing host information
|
||||
errno_t rc = 0; // Error code for secure functions
|
||||
char* ipstr = NULL; // Pointer to store the IP address as a string
|
||||
char ipv6[IP_LEN] = {0}; // Buffer to store IPv6 address
|
||||
char* result = NULL; // Result of inet_net_ntop function
|
||||
|
||||
// Get host information by host name
|
||||
hp = gethostbyname(myHostName);
|
||||
if (hp == NULL) {
|
||||
// If gethostbyname fails, try retrieving IPv6 information
|
||||
hp = gethostbyname2(myHostName, AF_INET6);
|
||||
if (hp == NULL) {
|
||||
// If both methods fail, log an error and return
|
||||
AlarmLog(ALM_LOG, "GET host IP by name failed.\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (hp->h_addrtype == AF_INET) {
|
||||
// If the address type is IPv4, convert it to a string
|
||||
ipstr = inet_ntoa(*((struct in_addr*)hp->h_addr));
|
||||
} else if (hp->h_addrtype == AF_INET6) {
|
||||
// If the address type is IPv6, use inet_net_ntop to convert it to a string
|
||||
result = inet_net_ntop(AF_INET6, ((struct in6_addr*)hp->h_addr), AF_INET6_MAX_BITS, ipv6, IP_LEN);
|
||||
if (result == NULL) {
|
||||
// Handle the case where inet_net_ntop fails
|
||||
AlarmLog(ALM_LOG, "inet_net_ntop failed, error: %d.\n", EAFNOSUPPORT);
|
||||
}
|
||||
ipstr = ipv6;
|
||||
}
|
||||
|
||||
// Calculate the length of the IP string and ensure it fits within 'myHostIPLen'
|
||||
size_t len = (strlen(ipstr) < (myHostIPLen - 1)) ? strlen(ipstr) : (myHostIPLen - 1);
|
||||
|
||||
// Copy the IP string to the 'myHostIP' buffer
|
||||
rc = memcpy_s(myHostIP, myHostIPLen, ipstr, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Null-terminate the 'myHostIP' string
|
||||
myHostIP[len] = '\0';
|
||||
|
||||
// Log the host IP to an alarm log
|
||||
AlarmLog(ALM_LOG, "Host IP: %s \n", myHostIP);
|
||||
}
|
||||
|
||||
|
||||
// This function retrieves the cluster name from an environment variable and stores it in the 'clusterName' buffer.
|
||||
|
||||
static void GetClusterName(char* clusterName, unsigned int clusterNameLen)
|
||||
{
|
||||
errno_t rc = 0;
|
||||
char* gsClusterName = gs_getenv_r("GS_CLUSTER_NAME");
|
||||
errno_t rc = 0; // Error code for secure functions
|
||||
char* gsClusterName = gs_getenv_r("GS_CLUSTER_NAME"); // Get the value of the GS_CLUSTER_NAME environment variable
|
||||
|
||||
if (gsClusterName != NULL) {
|
||||
check_input_for_security1(gsClusterName);
|
||||
// If the GS_CLUSTER_NAME environment variable is set:
|
||||
check_input_for_security1(gsClusterName); // Check and sanitize the environment variable for security
|
||||
size_t len = (strlen(gsClusterName) < (clusterNameLen - 1)) ? strlen(gsClusterName) : (clusterNameLen - 1);
|
||||
// Calculate the length of the cluster name and ensure it fits within 'clusterNameLen'
|
||||
rc = memcpy_s(clusterName, clusterNameLen, gsClusterName, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Null-terminate the 'clusterName' string
|
||||
clusterName[len] = '\0';
|
||||
|
||||
// Log the cluster name to an alarm log
|
||||
AlarmLog(ALM_LOG, "Cluster Name: %s \n", clusterName);
|
||||
} else {
|
||||
size_t len = strlen(CLUSTERNAME);
|
||||
// If the GS_CLUSTER_NAME environment variable is not set:
|
||||
size_t len = strlen(CLUSTERNAME); // Get the length of the default cluster name
|
||||
// Copy the default cluster name to the 'clusterName' buffer
|
||||
rc = memcpy_s(clusterName, clusterNameLen, CLUSTERNAME, len);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Null-terminate the 'clusterName' string
|
||||
clusterName[len] = '\0';
|
||||
|
||||
// Log an error indicating that the GS_CLUSTER_NAME environment variable is not set
|
||||
AlarmLog(ALM_LOG, "Get ENV GS_CLUSTER_NAME failed!\n");
|
||||
}
|
||||
}
|
||||
|
|
@ -805,40 +825,44 @@ static bool SuppressAlarmLogReport(Alarm* alarmItem, AlarmType type, int timeInt
|
|||
return true;
|
||||
}
|
||||
|
||||
// This function converts an integer 'inputLen' into a 4-character string and stores it in 'outputLen'.
|
||||
|
||||
static void GetFormatLenStr(char* outputLen, int inputLen)
|
||||
{
|
||||
outputLen[4] = '\0';
|
||||
outputLen[3] = '0' + inputLen % 10;
|
||||
inputLen /= 10;
|
||||
outputLen[2] = '0' + inputLen % 10;
|
||||
inputLen /= 10;
|
||||
outputLen[1] = '0' + inputLen % 10;
|
||||
inputLen /= 10;
|
||||
outputLen[0] = '0' + inputLen % 10;
|
||||
outputLen[4] = '\0'; // Null-terminate the string to ensure it's properly terminated
|
||||
outputLen[3] = '0' + inputLen % 10; // Convert the last digit of 'inputLen' to a character and store it in the last position
|
||||
inputLen /= 10; // Remove the last digit from 'inputLen' by integer division
|
||||
outputLen[2] = '0' + inputLen % 10; // Convert the next digit to a character and store it in the third position
|
||||
inputLen /= 10; // Remove the next digit from 'inputLen'
|
||||
outputLen[1] = '0' + inputLen % 10; // Convert the next digit to a character and store it in the second position
|
||||
inputLen /= 10; // Remove the next digit from 'inputLen'
|
||||
outputLen[0] = '0' + inputLen % 10; // Convert the last remaining digit to a character and store it in the first position
|
||||
}
|
||||
|
||||
|
||||
// This function reports an alarm using a specified alarm component path, alarm item, alarm type, and additional parameters.
|
||||
|
||||
static void ComponentReport(
|
||||
char* alarmComponentPath, Alarm* alarmItem, AlarmType type, AlarmAdditionalParam* additionalParam)
|
||||
{
|
||||
int nRet = 0;
|
||||
char reportCmd[4096] = {0};
|
||||
int retCmd = 0;
|
||||
int cnt = 0;
|
||||
char tempBuff[4096] = {0};
|
||||
char clusterNameLen[5] = {0};
|
||||
char databaseNameLen[5] = {0};
|
||||
char dbUserNameLen[5] = {0};
|
||||
char hostIPLen[5] = {0};
|
||||
char hostNameLen[5] = {0};
|
||||
char instanceNameLen[5] = {0};
|
||||
char additionInfoLen[5] = {0};
|
||||
char clusterName[512] = {0};
|
||||
int nRet = 0; // Integer return value
|
||||
char reportCmd[4096] = {0}; // Buffer to store the report command
|
||||
int retCmd = 0; // Return code from the system command
|
||||
int cnt = 0; // Counter for retries
|
||||
char tempBuff[4096] = {0}; // Temporary buffer
|
||||
char clusterNameLen[5] = {0}; // Buffer for the length of cluster name
|
||||
char databaseNameLen[5] = {0}; // Buffer for the length of database name
|
||||
char dbUserNameLen[5] = {0}; // Buffer for the length of database user name
|
||||
char hostIPLen[5] = {0}; // Buffer for the length of host IP
|
||||
char hostNameLen[5] = {0}; // Buffer for the length of host name
|
||||
char instanceNameLen[5] = {0}; // Buffer for the length of instance name
|
||||
char additionInfoLen[5] = {0}; // Buffer for the length of additional info
|
||||
char clusterName[512] = {0}; // Buffer for the cluster name
|
||||
|
||||
int i = 0;
|
||||
errno_t rc = 0;
|
||||
int i = 0; // Counter for loops
|
||||
errno_t rc = 0; // Error code for secure functions
|
||||
|
||||
/* Set the host ip and the host name of the feature permission alarm to make that alarms of different hosts can be
|
||||
* suppressed. */
|
||||
// Set the host IP and host name of feature permission alarms to make alarms of different hosts suppressible
|
||||
if (ALM_AI_UnbalancedCluster == alarmItem->id || ALM_AI_FeaturePermissionDenied == alarmItem->id) {
|
||||
rc = memset_s(additionalParam->hostIP, sizeof(additionalParam->hostIP), 0, sizeof(additionalParam->hostIP));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
|
@ -847,6 +871,7 @@ static void ComponentReport(
|
|||
securec_check_c(rc, "\0", "\0");
|
||||
}
|
||||
|
||||
// If a logic cluster name is provided, create a combined cluster name
|
||||
if (additionalParam->logicClusterName[0] != '\0') {
|
||||
rc = snprintf_s(clusterName,
|
||||
sizeof(clusterName),
|
||||
|
|
@ -861,6 +886,7 @@ static void ComponentReport(
|
|||
securec_check_ss_c(rc, "\0", "\0");
|
||||
}
|
||||
|
||||
// Calculate the length of various parameters and store them as 4-character strings
|
||||
GetFormatLenStr(clusterNameLen, strlen(clusterName));
|
||||
GetFormatLenStr(databaseNameLen, strlen(additionalParam->databaseName));
|
||||
GetFormatLenStr(dbUserNameLen, strlen(additionalParam->dbUserName));
|
||||
|
|
@ -869,12 +895,14 @@ static void ComponentReport(
|
|||
GetFormatLenStr(instanceNameLen, strlen(additionalParam->instanceName));
|
||||
GetFormatLenStr(additionInfoLen, strlen(additionalParam->additionInfo));
|
||||
|
||||
// Replace spaces in the additional info with '#' for security
|
||||
for (i = 0; i < (int)strlen(additionalParam->additionInfo); ++i) {
|
||||
if (' ' == additionalParam->additionInfo[i]) {
|
||||
additionalParam->additionInfo[i] = '#';
|
||||
}
|
||||
}
|
||||
|
||||
// Create a formatted string containing all the lengths and values
|
||||
nRet = snprintf_s(tempBuff,
|
||||
sizeof(tempBuff),
|
||||
sizeof(tempBuff) - 1,
|
||||
|
|
@ -895,8 +923,11 @@ static void ComponentReport(
|
|||
additionalParam->additionInfo);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// Ensure the security of input parameters
|
||||
check_input_for_security1(alarmComponentPath);
|
||||
check_input_for_security1(tempBuff);
|
||||
|
||||
// Create the full alarm report command
|
||||
nRet = snprintf_s(reportCmd,
|
||||
sizeof(reportCmd),
|
||||
sizeof(reportCmd) - 1,
|
||||
|
|
@ -907,15 +938,18 @@ static void ComponentReport(
|
|||
tempBuff);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// Perform the alarm report, with retries
|
||||
do {
|
||||
retCmd = system(reportCmd);
|
||||
// return ALARM_REPORT_SUPPRESS, represent alarm report suppressed
|
||||
|
||||
// If the return code indicates suppression of the alarm report, exit the loop
|
||||
if (ALARM_REPORT_SUPPRESS == WEXITSTATUS(retCmd))
|
||||
break;
|
||||
if (++cnt > 3)
|
||||
break;
|
||||
} while (WEXITSTATUS(retCmd) != ALARM_REPORT_SUCCEED);
|
||||
|
||||
// Handle success or failure of the alarm report
|
||||
if (ALARM_REPORT_SUCCEED != WEXITSTATUS(retCmd) && ALARM_REPORT_SUPPRESS != WEXITSTATUS(retCmd)) {
|
||||
AlarmLog(ALM_LOG, "Component alarm report failed! Cmd: %s, retCmd: %d.", reportCmd, WEXITSTATUS(retCmd));
|
||||
} else if (ALARM_REPORT_SUCCEED == WEXITSTATUS(retCmd)) {
|
||||
|
|
@ -925,36 +959,43 @@ static void ComponentReport(
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
// This function reports an alarm to syslog with specific alarm information and additional parameters.
|
||||
|
||||
static void SyslogReport(Alarm* alarmItem, AlarmAdditionalParam* additionalParam)
|
||||
{
|
||||
int nRet = 0;
|
||||
char reportInfo[4096] = {0};
|
||||
int nRet = 0; // Integer return value
|
||||
char reportInfo[4096] = {0}; // Buffer to store the alarm report information
|
||||
|
||||
// Create a formatted string containing various alarm and additional parameters
|
||||
nRet = snprintf_s(reportInfo,
|
||||
sizeof(reportInfo),
|
||||
sizeof(reportInfo) - 1,
|
||||
"%s||%s||%s||||||||%s||%s||%s||%s||%s||%s||%s||%s||%s||%s||%s||||||||||||||%s||%s||||||||||||||||||||",
|
||||
"Syslog MPPDB",
|
||||
additionalParam->hostName,
|
||||
additionalParam->hostIP,
|
||||
"Database",
|
||||
"MppDB",
|
||||
additionalParam->logicClusterName,
|
||||
"SYSLOG",
|
||||
additionalParam->instanceName,
|
||||
"Alarm",
|
||||
AlarmIdToAlarmNameEn(alarmItem->id),
|
||||
AlarmIdToAlarmNameCh(alarmItem->id),
|
||||
"1",
|
||||
"0",
|
||||
"6",
|
||||
alarmItem->infoEn,
|
||||
alarmItem->infoCh);
|
||||
"Syslog MPPDB", // Syslog identification tag
|
||||
additionalParam->hostName, // Host name
|
||||
additionalParam->hostIP, // Host IP address
|
||||
"Database", // Database information
|
||||
"MppDB", // MppDB information
|
||||
additionalParam->logicClusterName,// Logic cluster name
|
||||
"SYSLOG", // Log type
|
||||
additionalParam->instanceName, // Instance name
|
||||
"Alarm", // Alarm category
|
||||
AlarmIdToAlarmNameEn(alarmItem->id), // Alarm name in English
|
||||
AlarmIdToAlarmNameCh(alarmItem->id), // Alarm name in Chinese
|
||||
"1", // Unknown parameter
|
||||
"0", // Unknown parameter
|
||||
"6", // Unknown parameter
|
||||
alarmItem->infoEn, // Alarm information in English
|
||||
alarmItem->infoCh); // Alarm information in Chinese
|
||||
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// Report the alarm information to the syslog using the LOG_ERR level
|
||||
syslog(LOG_ERR, "%s", reportInfo);
|
||||
}
|
||||
|
||||
|
||||
/* Check this line is comment line or not, which is in AlarmItem.conf file */
|
||||
static bool isValidScopeLine(const char* str)
|
||||
{
|
||||
|
|
@ -974,48 +1015,63 @@ static bool isValidScopeLine(const char* str)
|
|||
return false; /* not comment line */
|
||||
}
|
||||
|
||||
// This function initializes the alarm scope by reading and parsing a configuration file.
|
||||
|
||||
static void AlarmScopeInitialize(void)
|
||||
{
|
||||
char* gaussHomeDir = NULL;
|
||||
char* subStr = NULL;
|
||||
char* subStr1 = NULL;
|
||||
char* subStr2 = NULL;
|
||||
char* saveptr1 = NULL;
|
||||
char* saveptr2 = NULL;
|
||||
char alarmItemPath[MAXPGPATH];
|
||||
char buf[MAX_BUF_SIZE] = {0};
|
||||
errno_t nRet, rc;
|
||||
char* gaussHomeDir = NULL; // Pointer to store the value of the GAUSSHOME environment variable
|
||||
char* subStr = NULL; // Substring pointer
|
||||
char* subStr1 = NULL; // Substring pointer 1
|
||||
char* subStr2 = NULL; // Substring pointer 2
|
||||
char* saveptr1 = NULL; // Save pointer for strtok_r
|
||||
char* saveptr2 = NULL; // Save pointer for strtok_r
|
||||
char alarmItemPath[MAXPGPATH]; // Path to the alarm configuration file
|
||||
char buf[MAX_BUF_SIZE] = {0}; // Buffer to store a line from the configuration file
|
||||
errno_t nRet, rc; // Error code variables
|
||||
|
||||
// Retrieve the value of the GAUSSHOME environment variable
|
||||
if ((gaussHomeDir = gs_getenv_r("GAUSSHOME")) == NULL) {
|
||||
AlarmLog(ALM_LOG, "ERROR: environment variable $GAUSSHOME is not set!\n");
|
||||
return;
|
||||
}
|
||||
// Check for potential security issues with the environment variable
|
||||
check_input_for_security1(gaussHomeDir);
|
||||
|
||||
// Create the path to the alarm configuration file
|
||||
nRet = snprintf_s(alarmItemPath, MAXPGPATH, MAXPGPATH - 1, "%s/bin/alarmItem.conf", gaussHomeDir);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
canonicalize_path(alarmItemPath);
|
||||
|
||||
// Attempt to open the alarm configuration file for reading
|
||||
FILE* fd = fopen(alarmItemPath, "r");
|
||||
if (fd == NULL)
|
||||
return;
|
||||
|
||||
// Read each line from the configuration file
|
||||
while (!feof(fd)) {
|
||||
// Initialize the 'buf' buffer with zeros
|
||||
rc = memset_s(buf, MAX_BUF_SIZE, 0, MAX_BUF_SIZE);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Read a line from the configuration file into the 'buf' buffer
|
||||
if (fgets(buf, MAX_BUF_SIZE, fd) == NULL)
|
||||
continue;
|
||||
|
||||
// Check if the line is a valid scope line; if so, skip it
|
||||
if (isValidScopeLine(buf))
|
||||
continue;
|
||||
|
||||
// Search for the substring "alarm_scope" in the line
|
||||
subStr = strstr(buf, "alarm_scope");
|
||||
if (subStr == NULL)
|
||||
continue;
|
||||
|
||||
// Find the position of the equal sign '=' after "alarm_scope"
|
||||
subStr = strstr(subStr + strlen("alarm_scope"), "=");
|
||||
if (subStr == NULL || *(subStr + 1) == '\0') /* '=' is last char */
|
||||
if (subStr == NULL || *(subStr + 1) == '\0') /* '=' is the last character */
|
||||
continue;
|
||||
|
||||
// Move to the first non-blank character after the equal sign
|
||||
int ii = 1;
|
||||
for (;;) {
|
||||
if (*(subStr + ii) == ' ') {
|
||||
|
|
@ -1024,6 +1080,7 @@ static void AlarmScopeInitialize(void)
|
|||
break;
|
||||
}
|
||||
|
||||
// Extract the substring after the equal sign
|
||||
subStr = subStr + ii;
|
||||
subStr1 = strtok_r(subStr, "\n", &saveptr1);
|
||||
if (subStr1 == NULL)
|
||||
|
|
@ -1031,12 +1088,17 @@ static void AlarmScopeInitialize(void)
|
|||
subStr2 = strtok_r(subStr1, "\r", &saveptr2);
|
||||
if (subStr2 == NULL)
|
||||
continue;
|
||||
|
||||
// Copy the extracted alarm scope value to the 'g_alarm_scope' buffer
|
||||
rc = memcpy_s(g_alarm_scope, MAX_BUF_SIZE, subStr2, strlen(subStr2));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
}
|
||||
|
||||
// Close the configuration file
|
||||
fclose(fd);
|
||||
}
|
||||
|
||||
|
||||
void AlarmReporter(Alarm* alarmItem, AlarmType type, AlarmAdditionalParam* additionalParam)
|
||||
{
|
||||
if (NULL == alarmItem) {
|
||||
|
|
@ -1098,47 +1160,69 @@ Secondly, fill the report message(typedef struct AlarmAdditionalParam).
|
|||
Thirdly, invoke the AlarmReporter, report the alarm.
|
||||
---------------------------------------------------------------------------
|
||||
*/
|
||||
// This function performs a loop to check a list of alarms and report their status.
|
||||
|
||||
void AlarmCheckerLoop(Alarm* checkList, int checkListSize)
|
||||
{
|
||||
int i;
|
||||
AlarmAdditionalParam tempAdditionalParam;
|
||||
int i; // Loop counter
|
||||
AlarmAdditionalParam tempAdditionalParam; // Temporary storage for additional alarm parameters
|
||||
|
||||
// Check if the checkList is NULL or the checkListSize is invalid
|
||||
if (NULL == checkList || checkListSize <= 0) {
|
||||
AlarmLog(ALM_LOG, "AlarmCheckerLoop failed.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Iterate through the list of alarms to check each one
|
||||
for (i = 0; i < checkListSize; ++i) {
|
||||
Alarm* alarmItem = &(checkList[i]);
|
||||
AlarmCheckResult result = ALM_ACR_UnKnown;
|
||||
Alarm* alarmItem = &(checkList[i]); // Get the current alarm item
|
||||
AlarmCheckResult result = ALM_ACR_UnKnown; // Initialize the alarm check result to unknown
|
||||
|
||||
AlarmType type = ALM_AT_Fault;
|
||||
AlarmType type = ALM_AT_Fault; // Initialize the alarm type to fault
|
||||
|
||||
// Check if the alarm item has a checker function assigned
|
||||
if (alarmItem->checker != NULL) {
|
||||
// execute alarm check function and output check result
|
||||
// Execute the alarm check function and obtain the check result
|
||||
result = alarmItem->checker(alarmItem, &tempAdditionalParam);
|
||||
|
||||
// If the check result is unknown, continue to the next alarm
|
||||
if (ALM_ACR_UnKnown == result) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the check result is normal, set the alarm type to resume
|
||||
if (ALM_ACR_Normal == result) {
|
||||
type = ALM_AT_Resume;
|
||||
}
|
||||
|
||||
// Report the alarm status using the AlarmReporter function
|
||||
(void)AlarmReporter(alarmItem, type, &tempAdditionalParam);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// This function logs an alarm message with a specified log level and a variable number of arguments.
|
||||
|
||||
void AlarmLog(int level, const char* fmt, ...)
|
||||
{
|
||||
va_list args;
|
||||
char buf[MAXPGPATH] = {0}; /*enough for log module*/
|
||||
int nRet = 0;
|
||||
va_list args; // Variable argument list
|
||||
char buf[MAXPGPATH] = {0}; // Buffer to store the log message
|
||||
int nRet = 0; // Integer return value
|
||||
|
||||
// Start processing variable arguments with the 'fmt' format string
|
||||
(void)va_start(args, fmt);
|
||||
|
||||
// Format the log message with the specified format and variable arguments,
|
||||
// and store it in the 'buf' buffer
|
||||
nRet = vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, fmt, args);
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// End processing variable arguments
|
||||
va_end(args);
|
||||
|
||||
// Call the AlarmLogImplementation function to handle the logging with the specified log level,
|
||||
// a log prefix (AlarmLogPrefix), and the formatted log message
|
||||
AlarmLogImplementation(level, AlarmLogPrefix, buf);
|
||||
}
|
||||
|
||||
|
|
@ -1146,14 +1230,27 @@ void AlarmLog(int level, const char* fmt, ...)
|
|||
Initialize the alarm item
|
||||
reportTime: express the last time of alarm report. the default value is 0.
|
||||
*/
|
||||
// This function initializes an Alarm structure with the specified values.
|
||||
|
||||
void AlarmItemInitialize(
|
||||
Alarm* alarmItem, AlarmId alarmId, AlarmStat alarmStat, CheckerFunc checkerFunc, time_t reportTime, int reportCount)
|
||||
{
|
||||
// Set the checker function for the alarm item
|
||||
alarmItem->checker = checkerFunc;
|
||||
|
||||
// Set the ID of the alarm item
|
||||
alarmItem->id = alarmId;
|
||||
|
||||
// Set the initial alarm status (e.g., ALM_AS_Normal, ALM_AS_Fault)
|
||||
alarmItem->stat = alarmStat;
|
||||
|
||||
// Set the time of the last report for this alarm item
|
||||
alarmItem->lastReportTime = reportTime;
|
||||
|
||||
// Set the count of reports for this alarm item
|
||||
alarmItem->reportCount = reportCount;
|
||||
|
||||
// Initialize the start and end timestamps to 0 (may be updated during alarm handling)
|
||||
alarmItem->startTimeStamp = 0;
|
||||
alarmItem->endTimeStamp = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,10 @@
|
|||
/***
|
||||
* @Author: 王贤义
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-11 20:10:31
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
|
|
@ -21,6 +28,8 @@
|
|||
*
|
||||
* -------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <ctype.h>
|
||||
|
|
@ -78,20 +87,30 @@ static FILE* logfile_open(const char* filename, const char* mode)
|
|||
FILE* fh = NULL;
|
||||
mode_t oumask;
|
||||
|
||||
// Note we do not let Log_file_mode disable IWUSR, since we certainly want to be able to write the files ourselves.
|
||||
// Set the file permission mask to allow read, write, and execute permissions for the owner (user)
|
||||
// while preserving the permissions for the group and others.
|
||||
oumask = umask((mode_t)((~(mode_t)(S_IRUSR | S_IWUSR | S_IXUSR)) & (S_IRWXU | S_IRWXG | S_IRWXO)));
|
||||
|
||||
// Open the file with the specified filename and mode.
|
||||
fh = fopen(filename, mode);
|
||||
|
||||
// Restore the original file permission mask.
|
||||
(void)umask(oumask);
|
||||
|
||||
// If the file was successfully opened, set the buffering mode to line-buffered.
|
||||
if (fh != NULL) {
|
||||
setvbuf(fh, NULL, LBF_MODE, 0);
|
||||
|
||||
#ifdef WIN32
|
||||
/* use CRLF line endings on Windows */
|
||||
// On Windows, use CRLF line endings.
|
||||
_setmode(_fileno(fh), _O_TEXT);
|
||||
#endif
|
||||
} else {
|
||||
// If the file could not be opened, log an error message.
|
||||
AlarmLog(ALM_LOG, "could not open log file \"%s\"\n", filename);
|
||||
}
|
||||
|
||||
// Return the file handle.
|
||||
return fh;
|
||||
}
|
||||
|
||||
|
|
@ -103,32 +122,52 @@ static void create_new_alarm_log_file(const char* sys_log_path)
|
|||
char log_temp_name[MAXPGPATH] = {0};
|
||||
errno_t rc;
|
||||
|
||||
// Initialize the systm struct and log_create_time buffer
|
||||
rc = memset_s(&systm, sizeof(systm), 0, sizeof(systm));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
/* create new log file */
|
||||
|
||||
// Clear the system_alarm_log buffer
|
||||
rc = memset_s(system_alarm_log, MAXPGPATH, 0, MAXPGPATH);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Get the current time
|
||||
current_time = time(NULL);
|
||||
|
||||
// Convert the current time to a formatted string
|
||||
if (localtime_r(¤t_time, &systm) != NULL) {
|
||||
(void)strftime(log_create_time, LOG_MAX_TIMELEN, "-%Y-%m-%d_%H%M%S", &systm);
|
||||
} else {
|
||||
// Print an error message if getting the local time failed
|
||||
AlarmLog(ALM_LOG, "get localtime_r failed\n");
|
||||
}
|
||||
|
||||
// Create the temporary log file name
|
||||
rc = snprintf_s(
|
||||
log_temp_name, MAXPGPATH, MAXPGPATH - 1, "%s%s%s", SYSTEM_ALARM_LOG, log_create_time, CURLOGFILEMARK);
|
||||
securec_check_ss_c(rc, "\0", "\0");
|
||||
|
||||
// Create the full path of the new log file
|
||||
rc = snprintf_s(system_alarm_log, MAXPGPATH, MAXPGPATH - 1, "%s/%s", sys_log_path, log_temp_name);
|
||||
securec_check_ss_c(rc, "\0", "\0");
|
||||
|
||||
// Clear the system_alarm_log_name buffer
|
||||
rc = memset_s(system_alarm_log_name, MAXPGPATH, 0, MAXPGPATH);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Copy the temporary log file name to system_alarm_log_name
|
||||
rc = strncpy_s(system_alarm_log_name, MAXPGPATH, log_temp_name, strlen(log_temp_name));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Open the new log file in "append" mode
|
||||
alarmLogFile = logfile_open(system_alarm_log, "a");
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames the current alarm log file without the "CURLOGFILEMARK" suffix.
|
||||
*
|
||||
* @param sys_log_path The system log path.
|
||||
* @return True if the log file was successfully renamed, false otherwise.
|
||||
*/
|
||||
static bool rename_alarm_log_file(const char* sys_log_path)
|
||||
{
|
||||
int len_log_old_name, len_suffix_name, len_log_new_name;
|
||||
|
|
@ -137,25 +176,30 @@ static bool rename_alarm_log_file(const char* sys_log_path)
|
|||
errno_t rc;
|
||||
int ret;
|
||||
|
||||
/* renamed the current file without Mark */
|
||||
/* Get the lengths of the old log file name, the suffix name, and the new log file name */
|
||||
len_log_old_name = strlen(system_alarm_log_name);
|
||||
len_suffix_name = strlen(CURLOGFILEMARK);
|
||||
len_log_new_name = len_log_old_name - len_suffix_name;
|
||||
|
||||
/* Copy the old log file name to logFileBuff */
|
||||
rc = strncpy_s(logFileBuff, MAXPGPATH, system_alarm_log_name, len_log_new_name);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
/* Append the ".log" suffix to logFileBuff */
|
||||
rc = strncat_s(logFileBuff, MAXPGPATH, ".log", strlen(".log"));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
/* Create the full path of the new log file */
|
||||
rc = snprintf_s(log_new_name, MAXPGPATH, MAXPGPATH - 1, "%s/%s", sys_log_path, logFileBuff);
|
||||
securec_check_ss_c(rc, "\0", "\0");
|
||||
|
||||
/* close the current file */
|
||||
/* Close the current log file */
|
||||
if (alarmLogFile != NULL) {
|
||||
fclose(alarmLogFile);
|
||||
alarmLogFile = NULL;
|
||||
}
|
||||
|
||||
/* Rename the current log file to the new log file name */
|
||||
ret = rename(system_alarm_log, log_new_name);
|
||||
if (ret != 0) {
|
||||
AlarmLog(ALM_LOG, "ERROR: %s: rename log file %s failed! \n", system_alarm_log, system_alarm_log);
|
||||
|
|
@ -164,19 +208,28 @@ static bool rename_alarm_log_file(const char* sys_log_path)
|
|||
return true;
|
||||
}
|
||||
|
||||
/* write alarm info to alarm log file */
|
||||
|
||||
/**
|
||||
* Writes the given buffer to the alarm log file.
|
||||
*
|
||||
* @param buffer The buffer containing the data to be written.
|
||||
*/
|
||||
static void write_log_file(const char* buffer)
|
||||
{
|
||||
int rc;
|
||||
(void)pthread_rwlock_wrlock(&alarm_log_write_lock);
|
||||
|
||||
// Check if the alarm log file is not open
|
||||
if (alarmLogFile == NULL) {
|
||||
// If the current log file is "/dev/null", create a new system alarm log
|
||||
if (strncmp(system_alarm_log, "/dev/null", strlen("/dev/null")) == 0) {
|
||||
create_system_alarm_log(sys_alarm_log_path);
|
||||
}
|
||||
// Open the alarm log file in "append" mode
|
||||
alarmLogFile = logfile_open(system_alarm_log, "a");
|
||||
}
|
||||
|
||||
// Write the buffer to the alarm log file
|
||||
if (alarmLogFile != NULL) {
|
||||
int count = strlen(buffer);
|
||||
|
||||
|
|
@ -205,20 +258,25 @@ void create_system_alarm_log(const char* sys_log_path)
|
|||
char* name_ptr = NULL;
|
||||
errno_t rc;
|
||||
|
||||
// Check if the sys_alarm_log_path is empty
|
||||
if (strlen(sys_alarm_log_path) == 0) {
|
||||
// Copy the sys_log_path to sys_alarm_log_path
|
||||
rc = strncpy_s(sys_alarm_log_path, MAX_PATH_LEN, sys_log_path, strlen(sys_log_path));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
}
|
||||
|
||||
// Open the directory specified by sys_log_path
|
||||
if ((dir = opendir(sys_log_path)) == NULL) {
|
||||
// Print an error message if opendir fails
|
||||
AlarmLog(ALM_LOG, "opendir %s failed! \n", sys_log_path);
|
||||
rc = strncpy_s(system_alarm_log, MAXPGPATH, "/dev/null", strlen("/dev/null"));
|
||||
securec_check_ss_c(rc, "\0", "\0");
|
||||
return;
|
||||
}
|
||||
|
||||
// Iterate through the directory entries
|
||||
while ((de = readdir(dir)) != NULL) {
|
||||
/* exist current log file */
|
||||
// Check if the current log file exists
|
||||
if (strstr(de->d_name, SYSTEM_ALARM_LOG) != NULL) {
|
||||
name_ptr = strstr(de->d_name, CURLOGFILEMARK);
|
||||
if (name_ptr != NULL) {
|
||||
|
|
@ -230,13 +288,20 @@ void create_system_alarm_log(const char* sys_log_path)
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If the current log file exists
|
||||
if (is_exist) {
|
||||
// Clear the system_alarm_log_name and system_alarm_log buffers
|
||||
rc = memset_s(system_alarm_log_name, MAXPGPATH, 0, MAXPGPATH);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
rc = memset_s(system_alarm_log, MAXPGPATH, 0, MAXPGPATH);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Construct the new log file path
|
||||
rc = snprintf_s(system_alarm_log, MAXPGPATH, MAXPGPATH - 1, "%s/%s", sys_log_path, de->d_name);
|
||||
securec_check_ss_c(rc, "\0", "\0");
|
||||
|
||||
// Copy the log file name to system_alarm_log_name
|
||||
rc = strncpy_s(system_alarm_log_name, MAXPGPATH, de->d_name, strlen(de->d_name));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
} else {
|
||||
|
|
@ -248,49 +313,69 @@ void create_system_alarm_log(const char* sys_log_path)
|
|||
|
||||
void clean_system_alarm_log(const char* file_name, const char* sys_log_path)
|
||||
{
|
||||
// Assert that file_name is not NULL
|
||||
Assert(file_name != NULL);
|
||||
|
||||
unsigned long filesize = 0;
|
||||
struct stat statbuff;
|
||||
int ret;
|
||||
|
||||
// Initialize statbuff with zeros
|
||||
errno_t rc = memset_s(&statbuff, sizeof(statbuff), 0, sizeof(statbuff));
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Get the file status using stat
|
||||
ret = stat(file_name, &statbuff);
|
||||
|
||||
// Check if stat failed or if the file_name is "/dev/null"
|
||||
if (ret != 0 || (strncmp(file_name, "/dev/null", strlen("/dev/null")) == 0)) {
|
||||
// Print an error message and return if there is an error with stat or if the file_name is "/dev/null"
|
||||
AlarmLog(ALM_LOG, "ERROR: stat system alarm log %s error.ret=%d\n", file_name, ret);
|
||||
return;
|
||||
} else {
|
||||
// Get the file size from the statbuff
|
||||
filesize = statbuff.st_size;
|
||||
}
|
||||
|
||||
// Check if the file size is greater than MAX_SYSTEM_ALARM_LOG_SIZE
|
||||
if (filesize > MAX_SYSTEM_ALARM_LOG_SIZE) {
|
||||
// Acquire a write lock on alarm_log_write_lock
|
||||
(void)pthread_rwlock_wrlock(&alarm_log_write_lock);
|
||||
/* renamed the current file without Mark */
|
||||
|
||||
// Rename the current file without the Mark
|
||||
if (rename_alarm_log_file(sys_log_path)) {
|
||||
/* create new log file */
|
||||
// Create a new log file
|
||||
create_new_alarm_log_file(sys_log_path);
|
||||
}
|
||||
|
||||
// Release the write lock on alarm_log_write_lock
|
||||
(void)pthread_rwlock_unlock(&alarm_log_write_lock);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void write_alarm(Alarm* alarmItem, const char* alarmName, const char* alarmLevel, AlarmType type,
|
||||
AlarmAdditionalParam* additionalParam)
|
||||
{
|
||||
// Declare variables
|
||||
char command[COMMAND_SIZE];
|
||||
char reportInfo[REPORT_MSG_SIZE];
|
||||
errno_t rcs = 0;
|
||||
|
||||
// Check if system_alarm_log is empty, if so, return
|
||||
if (strlen(system_alarm_log) == 0)
|
||||
return;
|
||||
|
||||
// Initialize command and reportInfo buffers with zeros
|
||||
errno_t rc = memset_s(command, COMMAND_SIZE, 0, COMMAND_SIZE);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
rc = memset_s(reportInfo, REPORT_MSG_SIZE, 0, REPORT_MSG_SIZE);
|
||||
securec_check_c(rc, "\0", "\0");
|
||||
|
||||
// Check the type of the alarm
|
||||
if (type == ALM_AT_Fault || type == ALM_AT_Event) {
|
||||
// Construct the reportInfo string for fault or event alarms
|
||||
rcs = snprintf_s(reportInfo,
|
||||
REPORT_MSG_SIZE,
|
||||
REPORT_MSG_SIZE - 1,
|
||||
|
|
@ -307,20 +392,8 @@ void write_alarm(Alarm* alarmItem, const char* alarmName, const char* alarmLevel
|
|||
alarmLevel,
|
||||
g_alarm_scope,
|
||||
additionalParam->hostName,
|
||||
(strlen(additionalParam->instanceName) != 0) ? additionalParam->instanceName : additionalParam->clusterName,
|
||||
"firing",
|
||||
additionalParam->additionInfo,
|
||||
"ADAC",
|
||||
alarmItem->startTimeStamp,
|
||||
0);
|
||||
} else if (type == ALM_AT_Resume) {
|
||||
rcs = snprintf_s(reportInfo,
|
||||
REPORT_MSG_SIZE,
|
||||
REPORT_MSG_SIZE - 1,
|
||||
"{" SYSQUOTE "id" SYSQUOTE SYSCOLON SYSQUOTE "%016ld" SYSQUOTE SYSCOMMA SYSQUOTE
|
||||
"name" SYSQUOTE SYSCOLON SYSQUOTE "%s" SYSQUOTE SYSCOMMA SYSQUOTE "level" SYSQUOTE SYSCOLON SYSQUOTE
|
||||
"%s" SYSQUOTE SYSCOMMA SYSQUOTE "scope" SYSQUOTE SYSCOLON "%s" SYSCOMMA SYSQUOTE
|
||||
"source_tag" SYSQUOTE SYSCOLON SYSQUOTE "%s-%s" SYSQUOTE SYSCOMMA SYSQUOTE
|
||||
(strlen(additionalParam->instanceName) != 0) ? additionalParam->instanceName : additionalParam->cluster
|
||||
"ame" SYSQUOTE SYSCOLON SYSQUOTE "%s" SYSQUOTE SYSCOMMA SYSQUOTE
|
||||
"op_type" SYSQUOTE SYSCOLON SYSQUOTE "%s" SYSQUOTE SYSCOMMA SYSQUOTE "start_timestamp" SYSQUOTE SYSCOLON
|
||||
"%d" SYSCOMMA SYSQUOTE "end_timestamp" SYSQUOTE SYSCOLON "%ld"
|
||||
"}\n",
|
||||
|
|
@ -334,6 +407,10 @@ void write_alarm(Alarm* alarmItem, const char* alarmName, const char* alarmLevel
|
|||
0,
|
||||
alarmItem->endTimeStamp);
|
||||
}
|
||||
|
||||
// Check if the snprintf_s function succeeded
|
||||
securec_check_ss_c(rcs, "\0", "\0");
|
||||
|
||||
// Write the reportInfo to the log file
|
||||
write_log_file(reportInfo);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/***
|
||||
* @Author: 王贤义
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-11 20:25:05
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
|
|
@ -34,46 +41,92 @@
|
|||
* strdup() replacements that prints an error and exits
|
||||
* if something goes wrong. Can never return NULL.
|
||||
*/
|
||||
static char* xstrdup(const char* s)
|
||||
{
|
||||
char* result = NULL;
|
||||
|
||||
result = strdup(s);
|
||||
if (result == NULL) {
|
||||
printf("out of memory\n");
|
||||
exit(1);
|
||||
}
|
||||
return result;
|
||||
/**
|
||||
|
||||
This function duplicates a given string and returns the duplicated string.
|
||||
|
||||
@param s The string to be duplicated.
|
||||
|
||||
@return char* The duplicated string.
|
||||
*/
|
||||
static char xstrdup(const char* s)
|
||||
{
|
||||
char* result = NULL;
|
||||
|
||||
// Duplicate the string 's' using the strdup function
|
||||
result = strdup(s);
|
||||
|
||||
// Check if memory allocation failed
|
||||
if (result == NULL) {
|
||||
printf("out of memory\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Return the duplicated string
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This function takes an estimated time in seconds as input and converts it
|
||||
* into a formatted time string in the "HH:MM:SS" format. If the estimated_time
|
||||
* is -1, it returns "--:--:--" to represent an unknown time.
|
||||
*
|
||||
* @param estimated_time The estimated time in seconds.
|
||||
*
|
||||
* @return char* A dynamically allocated string representing the formatted time.
|
||||
*/
|
||||
char* show_estimated_time(int estimated_time)
|
||||
{
|
||||
// Create a character array to store the formatted time string, initialize to zero
|
||||
char time_string[MAXPGPATH] = {0};
|
||||
|
||||
// Declare variables to store hours, minutes, seconds, and a return value
|
||||
int hour = 0;
|
||||
int min = 0;
|
||||
int sec = 0;
|
||||
int nRet = 0;
|
||||
|
||||
// Check if estimated_time is -1, indicating an unknown time
|
||||
if (estimated_time == -1)
|
||||
return xstrdup("--:--:--");
|
||||
return xstrdup("--:--:--"); // Return a string representing unknown time
|
||||
|
||||
// Calculate hours, minutes, and seconds from the estimated_time
|
||||
hour = estimated_time / S_PER_H;
|
||||
min = (estimated_time % S_PER_H) / S_PER_MIN;
|
||||
sec = (estimated_time % S_PER_H) % S_PER_MIN;
|
||||
|
||||
// Format the calculated values into a string and store it in time_string
|
||||
nRet = snprintf_s(time_string, MAXPGPATH, MAXPGPATH - 1, "%.2d:%.2d:%.2d", hour, min, sec);
|
||||
|
||||
// Check for errors during string formatting using securec_check_ss_c
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// Return a dynamically allocated copy of the formatted time string
|
||||
return xstrdup(time_string);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This function takes a data size in bytes as input and converts it
|
||||
* into a formatted string with appropriate units (e.g., KB, MB, GB, TB).
|
||||
*
|
||||
* @param size The data size in bytes.
|
||||
*
|
||||
* @return char* A dynamically allocated string representing the formatted data size.
|
||||
*/
|
||||
char* show_datasize(uint64 size)
|
||||
{
|
||||
// Create a character array to store the formatted size string, initialize to zero
|
||||
char size_string[MAXPGPATH] = {0};
|
||||
|
||||
// Declare variables to store the size in a human-readable format and the unit string
|
||||
float showsize = 0;
|
||||
const char* unit = NULL;
|
||||
int nRet = 0;
|
||||
|
||||
// Check for the largest unit (TB, GB, MB, or KB) that is appropriate for the size
|
||||
if (size / KB_PER_TB != 0) {
|
||||
showsize = (float)size / KB_PER_TB;
|
||||
unit = "TB";
|
||||
|
|
@ -88,42 +141,70 @@ char* show_datasize(uint64 size)
|
|||
unit = "kB";
|
||||
}
|
||||
|
||||
// Format the calculated size and unit into a string and store it in size_string
|
||||
nRet = snprintf_s(size_string, MAXPGPATH, MAXPGPATH - 1, "%.2f%s", showsize, unit);
|
||||
|
||||
// Check for errors during string formatting using securec_check_ss_c
|
||||
securec_check_ss_c(nRet, "\0", "\0");
|
||||
|
||||
// Return a dynamically allocated copy of the formatted size string
|
||||
return xstrdup(size_string);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This function updates a database state file located at the specified path with
|
||||
* the data provided in the GaussState structure.
|
||||
*
|
||||
* @param path The path to the database state file to be updated.
|
||||
* @param state A pointer to the GaussState structure containing the data to be written.
|
||||
*/
|
||||
void UpdateDBStateFile(char* path, GaussState* state)
|
||||
{
|
||||
FILE* statef = NULL;
|
||||
char temppath[MAXPGPATH] = {0};
|
||||
int ret;
|
||||
FILE* statef = NULL; // File pointer for the state file
|
||||
char temppath[MAXPGPATH] = {0}; // Temporary file path for writing
|
||||
|
||||
int ret; // Return value from snprintf_s
|
||||
|
||||
// Check for NULL pointers and return if either is NULL
|
||||
if (NULL == state || path == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the temporary file path by appending ".temp" to the original path
|
||||
ret = snprintf_s(temppath, MAXPGPATH, MAXPGPATH - 1, "%s.temp", path);
|
||||
securec_check_ss_c(ret, "\0", "\0");
|
||||
|
||||
// Canonicalize the original path to ensure consistency
|
||||
canonicalize_path(path);
|
||||
|
||||
// Open the temporary file for writing
|
||||
statef = fopen(temppath, "w");
|
||||
|
||||
// Return if unable to open the temporary file
|
||||
if (statef == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the file permissions for the temporary file
|
||||
if (chmod(temppath, S_IRUSR | S_IWUSR) == -1) {
|
||||
/* Close file and Nullify the pointer for retry */
|
||||
fclose(statef);
|
||||
statef = NULL;
|
||||
return;
|
||||
}
|
||||
|
||||
// Write the contents of the GaussState structure to the temporary file
|
||||
if (0 == (fwrite(state, 1, sizeof(GaussState), statef))) {
|
||||
fclose(statef);
|
||||
statef = NULL;
|
||||
return;
|
||||
}
|
||||
|
||||
// Close the temporary file
|
||||
fclose(statef);
|
||||
|
||||
// Rename the temporary file to replace the original state file
|
||||
(void)rename(temppath, path);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/***
|
||||
* @Author: 王贤义
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-11 20:25:05
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* @file cm_cgroup.cpp
|
||||
* @brief
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,3 +1,10 @@
|
|||
/***
|
||||
* @Author: 王贤义
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-13 20:25:05
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* @file cm_path.cpp
|
||||
* @brief
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/***
|
||||
* @Author: 王贤义
|
||||
* @Team: 兰心开源
|
||||
* @Date: 2023-09-14 20:25:05
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* @file cm_stringinfo.cpp
|
||||
* @brief StringInfo provides an indefinitely-extensible string data type.
|
||||
|
|
|
|||
Loading…
Reference in New Issue