/* [PG_CUSTOM: DBMS_SCHEDULER] BEGIN
|
* Календарная строка — чистая функция от двух дат.
|
* Нулевой INTERVAL на стенде считается как 1. Значение больше 99 стенд принимает.
|
*/
|
extern "C"
|
{
|
#include "postgres.h"
|
#include "fmgr.h"
|
#include "catalog/pg_type_d.h"
|
#include "executor/spi.h"
|
#include "miscadmin.h"
|
#include "utils/acl.h"
|
#include "utils/builtins.h"
|
#include "utils/datetime.h"
|
#include "utils/timestamp.h"
|
}
|
|
#include <cstdlib>
|
#include <cstring>
|
#include <cstdio>
|
|
#include "dbms_scheduler_log.h"
|
|
namespace DbmsScheduler
|
{
|
|
enum Freq
|
{
|
FREQ_YEARLY = 0,
|
FREQ_MONTHLY,
|
FREQ_WEEKLY,
|
FREQ_DAILY,
|
FREQ_HOURLY,
|
FREQ_MINUTELY,
|
FREQ_SECONDLY
|
};
|
|
struct Civil
|
{
|
int year_;
|
int month_;
|
int day_;
|
int hour_;
|
int minute_;
|
int second_;
|
};
|
|
static const int64 SEARCH_STEPS = 100000;
|
|
static int
|
weekdayOf(int year, int month, int day)
|
{
|
return j2day(date2j(year, month, day));
|
}
|
|
static int
|
daysInMonth(int year, int month)
|
{
|
static const int kDays[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
int days = kDays[month];
|
bool leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
|
|
if (month == 2 && leap)
|
days = 29;
|
return days;
|
}
|
|
static int64
|
epochSeconds(const Civil &c)
|
{
|
int64 days = (int64) date2j(c.year_, c.month_, c.day_);
|
|
return days * 86400
|
+ (int64) c.hour_ * 3600
|
+ (int64) c.minute_ * 60
|
+ (int64) c.second_;
|
}
|
|
static Civil
|
fromSeconds(int64 seconds)
|
{
|
Civil c;
|
int64 days;
|
int sod;
|
|
days = seconds / 86400;
|
sod = (int) (seconds % 86400);
|
if (sod < 0) {
|
sod += 86400;
|
days--;
|
}
|
j2date((int) days, &c.year_, &c.month_, &c.day_);
|
c.hour_ = sod / 3600;
|
c.minute_ = (sod % 3600) / 60;
|
c.second_ = sod % 60;
|
return c;
|
}
|
|
static Civil
|
fromTs(TimestampTz ts)
|
{
|
struct pg_tm tm;
|
fsec_t fsec;
|
Civil c;
|
|
if (timestamp2tm(ts, NULL, &tm, &fsec, NULL, NULL) != 0) {
|
ereport(ERROR,
|
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
|
errmsg("calendar date is out of range")));
|
}
|
c.year_ = tm.tm_year;
|
c.month_ = tm.tm_mon;
|
c.day_ = tm.tm_mday;
|
c.hour_ = tm.tm_hour;
|
c.minute_ = tm.tm_min;
|
c.second_ = tm.tm_sec;
|
return c;
|
}
|
|
static TimestampTz
|
toTs(const Civil &c)
|
{
|
struct pg_tm tm;
|
Timestamp result;
|
fsec_t fsec = 0;
|
|
memset(&tm, 0, sizeof(tm));
|
tm.tm_year = c.year_;
|
tm.tm_mon = c.month_;
|
tm.tm_mday = c.day_;
|
tm.tm_hour = c.hour_;
|
tm.tm_min = c.minute_;
|
tm.tm_sec = c.second_;
|
if (tm2timestamp(&tm, fsec, NULL, &result) != 0) {
|
ereport(ERROR,
|
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
|
errmsg("calendar date is out of range")));
|
}
|
return (TimestampTz) result;
|
}
|
|
static void
|
badCalendar(const char *detail)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid calendar string"),
|
errdetail_internal("%s", detail)));
|
}
|
|
static bool
|
containsInt(const int *vals, int n, int needle)
|
{
|
int i;
|
|
for (i = 0; i < n; i++) {
|
if (vals[i] == needle)
|
return true;
|
}
|
return false;
|
}
|
|
static void
|
sortUnique(int *vals, int *n)
|
{
|
int i;
|
int j;
|
int count = *n;
|
|
for (i = 1; i < count; i++) {
|
int key = vals[i];
|
|
j = i;
|
while (j > 0 && vals[j - 1] > key) {
|
vals[j] = vals[j - 1];
|
j--;
|
}
|
vals[j] = key;
|
}
|
j = 0;
|
for (i = 0; i < count; i++) {
|
if (j == 0 || vals[j - 1] != vals[i])
|
vals[j++] = vals[i];
|
}
|
*n = j;
|
}
|
|
static int64
|
alignUp(int64 idx, int interval)
|
{
|
int64 rem;
|
|
if (idx < 0)
|
return 0;
|
rem = idx % interval;
|
if (rem == 0)
|
return idx;
|
return idx + (interval - rem);
|
}
|
|
struct ByDate
|
{
|
int year_;
|
int month_;
|
int day_;
|
};
|
|
class Calendar
|
{
|
public:
|
Calendar()
|
: empty_(false),
|
freq_(FREQ_DAILY),
|
interval_(1),
|
nMonth_(0),
|
nMonthDay_(0),
|
nWeekday_(0),
|
nHour_(0),
|
nMinute_(0),
|
nSecond_(0),
|
nWeekNo_(0),
|
nYearDay_(0),
|
nByDate_(0),
|
nSetPos_(0)
|
{
|
}
|
|
bool evaluate(const char *text, TimestampTz startAt, TimestampTz afterAt, TimestampTz *next);
|
|
private:
|
bool empty_;
|
int freq_;
|
int interval_;
|
int nMonth_;
|
int months_[12];
|
int nMonthDay_;
|
int monthDays_[62];
|
int nWeekday_;
|
int weekdays_[7];
|
int nHour_;
|
int hours_[24];
|
int nMinute_;
|
int minutes_[60];
|
int nSecond_;
|
int seconds_[60];
|
int nWeekNo_;
|
int weekNos_[106];
|
int nYearDay_;
|
int yearDays_[732];
|
int nByDate_;
|
ByDate byDates_[512];
|
int nSetPos_;
|
int setPos_[64];
|
|
void parse(char *text);
|
void parseClause(char *clause);
|
void parseList(char *value, int *dest, int *count, int cap, int minVal, int maxVal, const char *what);
|
void parseWeekdays(char *value);
|
void parseByDate(char *value);
|
void addByDate(int year, int month, int day);
|
int resolveDay(int year, int month, int spec) const;
|
bool candidateDay(int year, int month, int day, const Civil &anchor) const;
|
bool searchExtra(TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const;
|
bool accept(const Civil &stamp, TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const;
|
bool tryTimes(const Civil &day, const Civil &anchor, bool varyHour,
|
TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const;
|
bool search(TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const;
|
};
|
|
void
|
Calendar::parseList(char *value, int *dest, int *count, int cap, int minVal, int maxVal, const char *what)
|
{
|
char *cursor = value;
|
|
if (*count > 0)
|
badCalendar(what);
|
while (cursor != NULL && *cursor != '\0') {
|
char *comma = strchr(cursor, ',');
|
char *end = NULL;
|
long num;
|
|
if (comma != NULL)
|
*comma = '\0';
|
while (*cursor == ' ' || *cursor == '\t')
|
cursor++;
|
if (*cursor == '\0')
|
badCalendar(what);
|
num = strtol(cursor, &end, 10);
|
if (end == cursor || (*end != '\0' && *end != ' ' && *end != '\t'))
|
badCalendar(what);
|
if (num < minVal || num > maxVal || (num == 0 && minVal < 0))
|
badCalendar(what);
|
if (*count >= cap)
|
badCalendar(what);
|
dest[(*count)++] = (int) num;
|
if (comma == NULL)
|
break;
|
cursor = comma + 1;
|
}
|
if (*count == 0)
|
badCalendar(what);
|
sortUnique(dest, count);
|
}
|
|
void
|
Calendar::parseWeekdays(char *value)
|
{
|
char *cursor = value;
|
|
if (nWeekday_ > 0)
|
badCalendar("BYDAY");
|
while (cursor != NULL && *cursor != '\0') {
|
char token[8];
|
int len = 0;
|
char *comma = strchr(cursor, ',');
|
int wday = -1;
|
|
if (comma != NULL)
|
*comma = '\0';
|
while (*cursor == ' ' || *cursor == '\t')
|
cursor++;
|
while (cursor[len] != '\0' && cursor[len] != ' ' && cursor[len] != '\t' && len < 7) {
|
token[len] = cursor[len];
|
len++;
|
}
|
token[len] = '\0';
|
if (strcmp(token, "SUN") == 0 || strcmp(token, "SU") == 0)
|
wday = 0;
|
else if (strcmp(token, "MON") == 0 || strcmp(token, "MO") == 0)
|
wday = 1;
|
else if (strcmp(token, "TUE") == 0 || strcmp(token, "TU") == 0)
|
wday = 2;
|
else if (strcmp(token, "WED") == 0 || strcmp(token, "WE") == 0)
|
wday = 3;
|
else if (strcmp(token, "THU") == 0 || strcmp(token, "TH") == 0)
|
wday = 4;
|
else if (strcmp(token, "FRI") == 0 || strcmp(token, "FR") == 0)
|
wday = 5;
|
else if (strcmp(token, "SAT") == 0 || strcmp(token, "SA") == 0)
|
wday = 6;
|
else
|
badCalendar("BYDAY");
|
if (nWeekday_ >= 7)
|
badCalendar("BYDAY");
|
weekdays_[nWeekday_++] = wday;
|
if (comma == NULL)
|
break;
|
cursor = comma + 1;
|
}
|
if (nWeekday_ == 0)
|
badCalendar("BYDAY");
|
sortUnique(weekdays_, &nWeekday_);
|
}
|
|
void
|
Calendar::parseClause(char *clause)
|
{
|
char *eq;
|
char *key;
|
char *value;
|
|
while (*clause == ' ' || *clause == '\t')
|
clause++;
|
if (*clause == '\0')
|
return;
|
eq = strchr(clause, '=');
|
if (eq == NULL)
|
badCalendar("clause");
|
*eq = '\0';
|
key = clause;
|
value = eq + 1;
|
while (*value == ' ' || *value == '\t')
|
value++;
|
if (strcmp(key, "FREQ") == 0) {
|
if (strcmp(value, "YEARLY") == 0)
|
freq_ = FREQ_YEARLY;
|
else if (strcmp(value, "MONTHLY") == 0)
|
freq_ = FREQ_MONTHLY;
|
else if (strcmp(value, "WEEKLY") == 0)
|
freq_ = FREQ_WEEKLY;
|
else if (strcmp(value, "DAILY") == 0)
|
freq_ = FREQ_DAILY;
|
else if (strcmp(value, "HOURLY") == 0)
|
freq_ = FREQ_HOURLY;
|
else if (strcmp(value, "MINUTELY") == 0)
|
freq_ = FREQ_MINUTELY;
|
else if (strcmp(value, "SECONDLY") == 0)
|
freq_ = FREQ_SECONDLY;
|
else
|
badCalendar("FREQ");
|
} else if (strcmp(key, "INTERVAL") == 0) {
|
char *end = NULL;
|
long num = strtol(value, &end, 10);
|
|
if (end == value || *end != '\0')
|
badCalendar("INTERVAL");
|
if (num < 0)
|
badCalendar("INTERVAL");
|
interval_ = (num == 0) ? 1 : (int) num;
|
} else if (strcmp(key, "BYMONTH") == 0) {
|
parseList(value, months_, &nMonth_, 12, 1, 12, "BYMONTH");
|
} else if (strcmp(key, "BYMONTHDAY") == 0) {
|
parseList(value, monthDays_, &nMonthDay_, 62, -31, 31, "BYMONTHDAY");
|
} else if (strcmp(key, "BYDAY") == 0) {
|
parseWeekdays(value);
|
} else if (strcmp(key, "BYHOUR") == 0) {
|
parseList(value, hours_, &nHour_, 24, 0, 23, "BYHOUR");
|
} else if (strcmp(key, "BYMINUTE") == 0) {
|
parseList(value, minutes_, &nMinute_, 60, 0, 59, "BYMINUTE");
|
} else if (strcmp(key, "BYSECOND") == 0) {
|
parseList(value, seconds_, &nSecond_, 60, 0, 59, "BYSECOND");
|
} else if (strcmp(key, "BYWEEKNO") == 0) {
|
parseList(value, weekNos_, &nWeekNo_, 106, -53, 53, "BYWEEKNO");
|
} else if (strcmp(key, "BYYEARDAY") == 0) {
|
parseList(value, yearDays_, &nYearDay_, 732, -366, 366, "BYYEARDAY");
|
} else if (strcmp(key, "BYDATE") == 0) {
|
parseByDate(value);
|
} else if (strcmp(key, "BYSETPOS") == 0) {
|
parseList(value, setPos_, &nSetPos_, 64, -9999, 9999, "BYSETPOS");
|
} else {
|
badCalendar(key);
|
}
|
}
|
|
void
|
Calendar::parse(char *text)
|
{
|
char *cursor = text;
|
bool sawFreq = false;
|
bool any = false;
|
|
while (*cursor == ' ' || *cursor == '\t')
|
cursor++;
|
if (*cursor == '\0') {
|
empty_ = true;
|
return;
|
}
|
while (cursor != NULL && *cursor != '\0') {
|
char *semi = strchr(cursor, ';');
|
|
if (semi != NULL)
|
*semi = '\0';
|
if (*cursor != '\0') {
|
char *key = cursor;
|
|
while (*key == ' ' || *key == '\t')
|
key++;
|
if (*key != '\0') {
|
any = true;
|
if (strncmp(key, "FREQ", 4) == 0)
|
sawFreq = true;
|
parseClause(cursor);
|
}
|
}
|
if (semi == NULL)
|
break;
|
cursor = semi + 1;
|
}
|
if (!any) {
|
empty_ = true;
|
return;
|
}
|
if (!sawFreq)
|
badCalendar("FREQ");
|
if (nWeekNo_ > 0 && freq_ != FREQ_YEARLY)
|
badCalendar("BYWEEKNO");
|
if (nYearDay_ > 0 && freq_ != FREQ_YEARLY)
|
badCalendar("BYYEARDAY");
|
if (nByDate_ > 0 && freq_ != FREQ_YEARLY)
|
badCalendar("BYDATE");
|
if (nSetPos_ > 0 && freq_ != FREQ_MONTHLY && freq_ != FREQ_YEARLY)
|
badCalendar("BYSETPOS");
|
}
|
|
int
|
Calendar::resolveDay(int year, int month, int spec) const
|
{
|
int dim = daysInMonth(year, month);
|
int day;
|
|
if (spec > 0) {
|
if (spec > dim)
|
return -1;
|
return spec;
|
}
|
day = dim + spec + 1;
|
if (day < 1)
|
return -1;
|
return day;
|
}
|
|
bool
|
Calendar::accept(const Civil &stamp, TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const
|
{
|
TimestampTz ts = toTs(stamp);
|
|
/*
|
* toTs обнуляет доли секунды. Первое срабатывание — это сам start_date,
|
* включая микросекунды, иначе вхождение в ту же секунду отвергается.
|
*/
|
if (startAt > afterAt && ts <= startAt && (startAt - ts) < USECS_PER_SEC) {
|
*next = startAt;
|
return true;
|
}
|
if (ts > afterAt && ts >= startAt) {
|
*next = ts;
|
return true;
|
}
|
return false;
|
}
|
|
bool
|
Calendar::tryTimes(const Civil &day, const Civil &anchor, bool varyHour,
|
TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const
|
{
|
int hourVals[24];
|
int minuteVals[60];
|
int secondVals[60];
|
int nHour;
|
int nMinute;
|
int nSecond;
|
int h;
|
int m;
|
int s;
|
|
if (nHour_ > 0) {
|
memcpy(hourVals, hours_, sizeof(int) * nHour_);
|
nHour = nHour_;
|
} else if (varyHour) {
|
hourVals[0] = anchor.hour_;
|
nHour = 1;
|
} else {
|
hourVals[0] = day.hour_;
|
nHour = 1;
|
}
|
if (nMinute_ > 0) {
|
memcpy(minuteVals, minutes_, sizeof(int) * nMinute_);
|
nMinute = nMinute_;
|
} else if (freq_ == FREQ_MINUTELY || freq_ == FREQ_SECONDLY) {
|
minuteVals[0] = day.minute_;
|
nMinute = 1;
|
} else {
|
minuteVals[0] = anchor.minute_;
|
nMinute = 1;
|
}
|
if (nSecond_ > 0) {
|
memcpy(secondVals, seconds_, sizeof(int) * nSecond_);
|
nSecond = nSecond_;
|
} else if (freq_ == FREQ_SECONDLY) {
|
secondVals[0] = day.second_;
|
nSecond = 1;
|
} else {
|
secondVals[0] = anchor.second_;
|
nSecond = 1;
|
}
|
|
for (h = 0; h < nHour; h++) {
|
for (m = 0; m < nMinute; m++) {
|
for (s = 0; s < nSecond; s++) {
|
Civil stamp = day;
|
|
stamp.hour_ = hourVals[h];
|
stamp.minute_ = minuteVals[m];
|
stamp.second_ = secondVals[s];
|
if (accept(stamp, startAt, afterAt, next))
|
return true;
|
}
|
}
|
}
|
return false;
|
}
|
|
void
|
Calendar::addByDate(int year, int month, int day)
|
{
|
if (nByDate_ >= 512)
|
badCalendar("BYDATE");
|
byDates_[nByDate_].year_ = year;
|
byDates_[nByDate_].month_ = month;
|
byDates_[nByDate_].day_ = day;
|
nByDate_++;
|
}
|
|
static int
|
shiftDate(int year, int month, int day, int delta, int *outYear, int *outMonth, int *outDay)
|
{
|
int baseYear = (year == 0) ? 2020 : year;
|
int jd;
|
|
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(baseYear, month))
|
return -1;
|
jd = date2j(baseYear, month, day) + delta;
|
j2date(jd, outYear, outMonth, outDay);
|
return 0;
|
}
|
|
static void
|
isoWeekOf(int year, int month, int day, int *isoYear, int *week)
|
{
|
int jd = date2j(year, month, day);
|
int wday = weekdayOf(year, month, day);
|
int monday = jd - ((wday == 0) ? 6 : wday - 1);
|
int thursday = monday + 3;
|
int ty;
|
int tm;
|
int td;
|
int jan4;
|
int jan4w;
|
int week1monday;
|
|
j2date(thursday, &ty, &tm, &td);
|
jan4 = date2j(ty, 1, 4);
|
jan4w = weekdayOf(ty, 1, 4);
|
week1monday = jan4 - ((jan4w == 0) ? 6 : jan4w - 1);
|
*isoYear = ty;
|
*week = (monday - week1monday) / 7 + 1;
|
}
|
|
static int
|
isoWeeksIn(int isoYear)
|
{
|
int week;
|
int year;
|
|
isoWeekOf(isoYear, 12, 28, &year, &week);
|
return week;
|
}
|
|
static void
|
keepSetPos(const int *specs, int nSpec, Civil *hits, int *nHits)
|
{
|
Civil kept[366];
|
bool used[366];
|
int n = *nHits;
|
int i;
|
int keptCount = 0;
|
|
if (nSpec == 0 || n == 0)
|
return;
|
memset(used, 0, sizeof(used));
|
for (i = 0; i < nSpec; i++) {
|
int idx = (specs[i] > 0) ? specs[i] - 1 : n + specs[i];
|
|
if (idx >= 0 && idx < n && idx < 366)
|
used[idx] = true;
|
}
|
for (i = 0; i < n && i < 366; i++) {
|
if (used[i])
|
kept[keptCount++] = hits[i];
|
}
|
for (i = 0; i < keptCount; i++)
|
hits[i] = kept[i];
|
*nHits = keptCount;
|
}
|
|
void
|
Calendar::parseByDate(char *value)
|
{
|
char *cursor = value;
|
|
if (nByDate_ > 0)
|
badCalendar("BYDATE");
|
while (cursor != NULL && *cursor != '\0') {
|
char *comma = strchr(cursor, ',');
|
char *token;
|
int digits = 0;
|
int year = 0;
|
int month;
|
int day;
|
int num = 0;
|
char sign;
|
bool span;
|
int delta;
|
int i;
|
|
if (comma != NULL)
|
*comma = '\0';
|
while (*cursor == ' ' || *cursor == '\t')
|
cursor++;
|
token = cursor;
|
while (token[digits] >= '0' && token[digits] <= '9')
|
digits++;
|
if (digits != 4 && digits != 8)
|
badCalendar("BYDATE");
|
if (digits == 8) {
|
year = (token[0] - '0') * 1000 + (token[1] - '0') * 100
|
+ (token[2] - '0') * 10 + (token[3] - '0');
|
month = (token[4] - '0') * 10 + (token[5] - '0');
|
day = (token[6] - '0') * 10 + (token[7] - '0');
|
} else {
|
month = (token[0] - '0') * 10 + (token[1] - '0');
|
day = (token[2] - '0') * 10 + (token[3] - '0');
|
}
|
cursor = token + digits;
|
while (*cursor == ' ' || *cursor == '\t')
|
cursor++;
|
if (*cursor == '\0') {
|
int outYear;
|
int outMonth;
|
int outDay;
|
|
if (shiftDate(year, month, day, 0, &outYear, &outMonth, &outDay) != 0)
|
badCalendar("BYDATE");
|
addByDate(year, month, day);
|
} else {
|
sign = *cursor;
|
if (sign != '+' && sign != '-')
|
badCalendar("BYDATE");
|
cursor++;
|
span = false;
|
if (strncmp(cursor, "SPAN:", 5) == 0) {
|
span = true;
|
cursor += 5;
|
} else if (strncmp(cursor, "OFFSET:", 7) == 0) {
|
cursor += 7;
|
}
|
if (*cursor < '0' || *cursor > '9')
|
badCalendar("BYDATE");
|
while (*cursor >= '0' && *cursor <= '9') {
|
num = num * 10 + (*cursor - '0');
|
cursor++;
|
}
|
if (*cursor != 'D' && *cursor != 'W')
|
badCalendar("BYDATE");
|
if (*cursor == 'W') {
|
if (num < 1 || num > 53)
|
badCalendar("BYDATE");
|
delta = num * 7;
|
} else {
|
if (num < 1 || num > 376)
|
badCalendar("BYDATE");
|
delta = num;
|
}
|
cursor++;
|
while (*cursor == ' ' || *cursor == '\t')
|
cursor++;
|
if (*cursor != '\0')
|
badCalendar("BYDATE");
|
if (sign == '-')
|
delta = -delta;
|
if (span) {
|
int nDays = (delta < 0) ? -delta : delta;
|
int startDelta = (delta < 0) ? delta + 1 : 0;
|
|
for (i = 0; i < nDays; i++) {
|
int outYear;
|
int outMonth;
|
int outDay;
|
|
if (shiftDate(year, month, day, startDelta + i, &outYear, &outMonth, &outDay) != 0)
|
badCalendar("BYDATE");
|
addByDate(year == 0 ? 0 : outYear, outMonth, outDay);
|
}
|
} else {
|
int outYear;
|
int outMonth;
|
int outDay;
|
|
if (shiftDate(year, month, day, delta, &outYear, &outMonth, &outDay) != 0)
|
badCalendar("BYDATE");
|
addByDate(year == 0 ? 0 : outYear, outMonth, outDay);
|
}
|
}
|
if (comma == NULL)
|
break;
|
cursor = comma + 1;
|
}
|
if (nByDate_ == 0)
|
badCalendar("BYDATE");
|
}
|
|
bool
|
Calendar::candidateDay(int year, int month, int day, const Civil &anchor) const
|
{
|
int i;
|
|
if (day < 1 || day > daysInMonth(year, month))
|
return false;
|
if (nMonth_ > 0 && !containsInt(months_, nMonth_, month))
|
return false;
|
if (nWeekday_ > 0 && !containsInt(weekdays_, nWeekday_, weekdayOf(year, month, day)))
|
return false;
|
if (nMonthDay_ > 0) {
|
bool dayOk = false;
|
|
for (i = 0; i < nMonthDay_; i++) {
|
if (resolveDay(year, month, monthDays_[i]) == day)
|
dayOk = true;
|
}
|
if (!dayOk)
|
return false;
|
}
|
if (nWeekNo_ > 0) {
|
int isoYear;
|
int week;
|
int count;
|
bool weekOk = false;
|
|
isoWeekOf(year, month, day, &isoYear, &week);
|
count = isoWeeksIn(isoYear);
|
for (i = 0; i < nWeekNo_; i++) {
|
int resolved = weekNos_[i];
|
|
if (resolved < 0)
|
resolved = count + resolved + 1;
|
if (resolved == week)
|
weekOk = true;
|
}
|
if (!weekOk)
|
return false;
|
}
|
if (nYearDay_ > 0) {
|
int dayOfYear = date2j(year, month, day) - date2j(year, 1, 1) + 1;
|
int daysInYear = date2j(year, 12, 31) - date2j(year, 1, 1) + 1;
|
bool yearOk = false;
|
|
for (i = 0; i < nYearDay_; i++) {
|
int resolved = yearDays_[i];
|
|
if (resolved < 0)
|
resolved = daysInYear + resolved + 1;
|
if (resolved == dayOfYear)
|
yearOk = true;
|
}
|
if (!yearOk)
|
return false;
|
}
|
if (nByDate_ > 0) {
|
bool dateOk = false;
|
|
for (i = 0; i < nByDate_; i++) {
|
if (byDates_[i].year_ != 0 && byDates_[i].year_ != year)
|
continue;
|
if (byDates_[i].month_ == month && byDates_[i].day_ == day)
|
dateOk = true;
|
}
|
if (!dateOk)
|
return false;
|
}
|
if (nWeekNo_ == 0 && nYearDay_ == 0 && nByDate_ == 0 && nWeekday_ == 0 && nMonthDay_ == 0) {
|
if (freq_ == FREQ_MONTHLY)
|
return day == anchor.day_;
|
return month == anchor.month_ && day == anchor.day_;
|
}
|
return true;
|
}
|
|
bool
|
Calendar::searchExtra(TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const
|
{
|
Civil anchor = fromTs(startAt);
|
Civil after = fromTs(afterAt);
|
int64 steps = 0;
|
|
if (freq_ == FREQ_MONTHLY) {
|
int64 monthIdx = alignUp(
|
(int64) (after.year_ - anchor.year_) * 12 + (after.month_ - anchor.month_),
|
interval_);
|
|
for (; steps < SEARCH_STEPS; monthIdx += interval_, steps++) {
|
int total = (anchor.month_ - 1) + (int) monthIdx;
|
int year = anchor.year_ + total / 12;
|
int month = total % 12 + 1;
|
int dim = daysInMonth(year, month);
|
int day;
|
Civil hits[366];
|
int nHits = 0;
|
int i;
|
|
if (nMonth_ > 0 && !containsInt(months_, nMonth_, month))
|
continue;
|
for (day = 1; day <= dim; day++) {
|
if (!candidateDay(year, month, day, anchor))
|
continue;
|
hits[nHits].year_ = year;
|
hits[nHits].month_ = month;
|
hits[nHits].day_ = day;
|
hits[nHits].hour_ = 0;
|
hits[nHits].minute_ = 0;
|
hits[nHits].second_ = 0;
|
nHits++;
|
}
|
keepSetPos(setPos_, nSetPos_, hits, &nHits);
|
for (i = 0; i < nHits; i++) {
|
if (tryTimes(hits[i], anchor, true, startAt, afterAt, next))
|
return true;
|
}
|
}
|
return false;
|
}
|
|
if (freq_ == FREQ_YEARLY) {
|
int year0 = anchor.year_ - 1;
|
int year;
|
|
for (year = year0; year < year0 + 4000; year++) {
|
int64 rel = (int64) year - (int64) anchor.year_;
|
int dim = (daysInMonth(year, 2) == 29) ? 366 : 365;
|
int doy;
|
Civil hits[366];
|
int nHits = 0;
|
int i;
|
|
if (interval_ > 1 && (rel < 0 || (rel % interval_) != 0))
|
continue;
|
for (doy = 1; doy <= dim; doy++) {
|
Civil day = fromSeconds(((int64) date2j(year, 1, 1) + doy - 1) * 86400);
|
|
if (!candidateDay(day.year_, day.month_, day.day_, anchor))
|
continue;
|
hits[nHits] = day;
|
hits[nHits].hour_ = 0;
|
hits[nHits].minute_ = 0;
|
hits[nHits].second_ = 0;
|
nHits++;
|
}
|
keepSetPos(setPos_, nSetPos_, hits, &nHits);
|
for (i = 0; i < nHits; i++) {
|
if (tryTimes(hits[i], anchor, true, startAt, afterAt, next))
|
return true;
|
}
|
}
|
return false;
|
}
|
|
badCalendar("FREQ");
|
return false;
|
}
|
|
bool
|
Calendar::search(TimestampTz startAt, TimestampTz afterAt, TimestampTz *next) const
|
{
|
if (nWeekNo_ > 0 || nYearDay_ > 0 || nByDate_ > 0 || nSetPos_ > 0)
|
return searchExtra(startAt, afterAt, next);
|
|
Civil anchor = fromTs(startAt);
|
Civil after = fromTs(afterAt);
|
int64 anchorSec = epochSeconds(anchor);
|
int64 afterSec = epochSeconds(after);
|
int64 steps = 0;
|
|
if (freq_ == FREQ_SECONDLY || freq_ == FREQ_MINUTELY || freq_ == FREQ_HOURLY) {
|
int64 unit = (freq_ == FREQ_HOURLY) ? 3600 : ((freq_ == FREQ_MINUTELY) ? 60 : 1);
|
int64 diff = afterSec - anchorSec;
|
int64 idx0 = 0;
|
|
if (diff > 0)
|
idx0 = diff / unit;
|
idx0 = alignUp(idx0, interval_);
|
for (int64 idx = idx0; steps < SEARCH_STEPS; idx += interval_, steps++) {
|
Civil stamp = fromSeconds(anchorSec + idx * unit);
|
|
if (nMonth_ > 0 && !containsInt(months_, nMonth_, stamp.month_))
|
continue;
|
if (nMonthDay_ > 0) {
|
bool dayOk = false;
|
int i;
|
|
for (i = 0; i < nMonthDay_ && !dayOk; i++) {
|
if (resolveDay(stamp.year_, stamp.month_, monthDays_[i]) == stamp.day_)
|
dayOk = true;
|
}
|
if (!dayOk)
|
continue;
|
}
|
if (nWeekday_ > 0 && !containsInt(weekdays_, nWeekday_, weekdayOf(stamp.year_, stamp.month_, stamp.day_)))
|
continue;
|
if (freq_ == FREQ_HOURLY && nHour_ > 0 && !containsInt(hours_, nHour_, stamp.hour_))
|
continue;
|
if (tryTimes(stamp, anchor, false, startAt, afterAt, next))
|
return true;
|
}
|
return false;
|
}
|
|
if (freq_ == FREQ_DAILY) {
|
int anchorJd = date2j(anchor.year_, anchor.month_, anchor.day_);
|
int afterJd = date2j(after.year_, after.month_, after.day_);
|
int64 idx = alignUp((int64) afterJd - anchorJd, interval_);
|
|
for (; steps < SEARCH_STEPS; idx += interval_, steps++) {
|
Civil day;
|
|
j2date(anchorJd + (int) idx, &day.year_, &day.month_, &day.day_);
|
day.hour_ = 0;
|
day.minute_ = 0;
|
day.second_ = 0;
|
if (nMonth_ > 0 && !containsInt(months_, nMonth_, day.month_))
|
continue;
|
if (nMonthDay_ > 0) {
|
bool dayOk = false;
|
int i;
|
|
for (i = 0; i < nMonthDay_; i++) {
|
if (resolveDay(day.year_, day.month_, monthDays_[i]) == day.day_)
|
dayOk = true;
|
}
|
if (!dayOk)
|
continue;
|
}
|
if (nWeekday_ > 0 && !containsInt(weekdays_, nWeekday_, weekdayOf(day.year_, day.month_, day.day_)))
|
continue;
|
if (tryTimes(day, anchor, true, startAt, afterAt, next))
|
return true;
|
}
|
return false;
|
}
|
|
if (freq_ == FREQ_WEEKLY) {
|
int anchorJd = date2j(anchor.year_, anchor.month_, anchor.day_);
|
int afterJd = date2j(after.year_, after.month_, after.day_);
|
int anchorWday = weekdayOf(anchor.year_, anchor.month_, anchor.day_);
|
int mondayShift = (anchorWday == 0) ? 6 : anchorWday - 1;
|
int week0 = anchorJd - mondayShift;
|
int afterWday = weekdayOf(after.year_, after.month_, after.day_);
|
int afterShift = (afterWday == 0) ? 6 : afterWday - 1;
|
int64 weekIdx = alignUp((int64) ((afterJd - afterShift) - week0) / 7, interval_);
|
int dayList[7];
|
int nDays;
|
int fromMon;
|
|
if (nWeekday_ > 0) {
|
memcpy(dayList, weekdays_, sizeof(int) * nWeekday_);
|
nDays = nWeekday_;
|
} else {
|
dayList[0] = anchorWday;
|
nDays = 1;
|
}
|
for (; steps < SEARCH_STEPS; weekIdx += interval_, steps++) {
|
for (fromMon = 0; fromMon < 7; fromMon++) {
|
int wday = (fromMon + 1) % 7;
|
Civil day;
|
int jd;
|
|
if (!containsInt(dayList, nDays, wday))
|
continue;
|
jd = week0 + (int) weekIdx * 7 + fromMon;
|
|
j2date(jd, &day.year_, &day.month_, &day.day_);
|
day.hour_ = 0;
|
day.minute_ = 0;
|
day.second_ = 0;
|
if (nMonth_ > 0 && !containsInt(months_, nMonth_, day.month_))
|
continue;
|
if (nMonthDay_ > 0) {
|
bool dayOk = false;
|
int i;
|
|
for (i = 0; i < nMonthDay_; i++) {
|
if (resolveDay(day.year_, day.month_, monthDays_[i]) == day.day_)
|
dayOk = true;
|
}
|
if (!dayOk)
|
continue;
|
}
|
if (tryTimes(day, anchor, true, startAt, afterAt, next))
|
return true;
|
}
|
}
|
return false;
|
}
|
|
if (freq_ == FREQ_MONTHLY) {
|
int64 monthIdx = alignUp(
|
(int64) (after.year_ - anchor.year_) * 12 + (after.month_ - anchor.month_),
|
interval_);
|
int dayList[62];
|
int nDays;
|
|
if (nMonthDay_ > 0) {
|
memcpy(dayList, monthDays_, sizeof(int) * nMonthDay_);
|
nDays = nMonthDay_;
|
} else {
|
dayList[0] = anchor.day_;
|
nDays = 1;
|
}
|
for (; steps < SEARCH_STEPS; monthIdx += interval_, steps++) {
|
int total = (anchor.month_ - 1) + (int) monthIdx;
|
int year = anchor.year_ + total / 12;
|
int month = total % 12 + 1;
|
int d;
|
|
if (nMonth_ > 0 && !containsInt(months_, nMonth_, month))
|
continue;
|
for (d = 0; d < nDays; d++) {
|
int dayNum = resolveDay(year, month, dayList[d]);
|
Civil day;
|
|
if (dayNum < 0)
|
continue;
|
if (nWeekday_ > 0 && !containsInt(weekdays_, nWeekday_, weekdayOf(year, month, dayNum)))
|
continue;
|
day.year_ = year;
|
day.month_ = month;
|
day.day_ = dayNum;
|
day.hour_ = 0;
|
day.minute_ = 0;
|
day.second_ = 0;
|
if (tryTimes(day, anchor, true, startAt, afterAt, next))
|
return true;
|
}
|
}
|
return false;
|
}
|
|
{
|
int64 yearIdx = alignUp((int64) after.year_ - anchor.year_, interval_);
|
int monthList[12];
|
int dayList[62];
|
int nMonths;
|
int nDays;
|
|
if (nMonth_ > 0) {
|
memcpy(monthList, months_, sizeof(int) * nMonth_);
|
nMonths = nMonth_;
|
} else {
|
monthList[0] = anchor.month_;
|
nMonths = 1;
|
}
|
if (nMonthDay_ > 0) {
|
memcpy(dayList, monthDays_, sizeof(int) * nMonthDay_);
|
nDays = nMonthDay_;
|
} else {
|
dayList[0] = anchor.day_;
|
nDays = 1;
|
}
|
for (; steps < SEARCH_STEPS; yearIdx += interval_, steps++) {
|
int year = anchor.year_ + (int) yearIdx;
|
int mi;
|
int di;
|
|
for (mi = 0; mi < nMonths; mi++) {
|
for (di = 0; di < nDays; di++) {
|
int dayNum = resolveDay(year, monthList[mi], dayList[di]);
|
Civil day;
|
|
if (dayNum < 0)
|
continue;
|
if (nWeekday_ > 0 && !containsInt(weekdays_, nWeekday_, weekdayOf(year, monthList[mi], dayNum)))
|
continue;
|
day.year_ = year;
|
day.month_ = monthList[mi];
|
day.day_ = dayNum;
|
day.hour_ = 0;
|
day.minute_ = 0;
|
day.second_ = 0;
|
if (tryTimes(day, anchor, true, startAt, afterAt, next))
|
return true;
|
}
|
}
|
}
|
}
|
return false;
|
}
|
|
static bool
|
nameStart(char c)
|
{
|
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
|
}
|
|
static bool
|
nameChar(char c)
|
{
|
return nameStart(c) || (c >= '0' && c <= '9');
|
}
|
|
static bool
|
scheduleNameText(const char *text, const char **begin_out, const char **end_out)
|
{
|
const char *begin;
|
const char *end;
|
const char *cursor;
|
int parts = 0;
|
|
if (text == NULL)
|
return false;
|
begin = text;
|
while (*begin == ' ' || *begin == '\t')
|
begin++;
|
end = begin + strlen(begin);
|
while (end > begin && (end[-1] == ' ' || end[-1] == '\t'))
|
end--;
|
cursor = begin;
|
while (cursor < end) {
|
if (!nameStart(*cursor))
|
return false;
|
cursor++;
|
while (cursor < end && nameChar(*cursor))
|
cursor++;
|
parts++;
|
if (cursor < end && *cursor == '.') {
|
if (parts >= 2)
|
return false;
|
cursor++;
|
continue;
|
}
|
break;
|
}
|
if (cursor != end || parts < 1)
|
return false;
|
*begin_out = begin;
|
*end_out = end;
|
return true;
|
}
|
|
static char *
|
lookupScheduleRepeat(const char *schedule_name)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
MemoryContext caller;
|
char *owner;
|
char *repeat = NULL;
|
int rc;
|
bool isnull;
|
|
owner = GetUserNameFromId(GetUserId(), false);
|
values[0] = CStringGetTextDatum(owner);
|
values[1] = CStringGetTextDatum(schedule_name);
|
caller = CurrentMemoryContext;
|
if (SPI_connect() != SPI_OK_CONNECT)
|
return NULL;
|
rc = SPI_execute_with_args(
|
"SELECT repeat_interval FROM pg_catalog.dbms_scheduler_schedule "
|
"WHERE owner = $1 AND lower(schedule_name) = lower($2)",
|
2, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1) {
|
Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
|
if (!isnull)
|
repeat = MemoryContextStrdup(caller, TextDatumGetCString(value));
|
}
|
SPI_finish();
|
return repeat;
|
}
|
|
bool
|
Calendar::evaluate(const char *text, TimestampTz startAt, TimestampTz afterAt, TimestampTz *next)
|
{
|
const char *nameBegin;
|
const char *nameEnd;
|
char *copy;
|
size_t i;
|
size_t len;
|
|
if (text == NULL)
|
return false;
|
if (scheduleNameText(text, &nameBegin, &nameEnd)) {
|
char *name = pnstrdup(nameBegin, (size_t) (nameEnd - nameBegin));
|
char *repeat = lookupScheduleRepeat(name);
|
|
pfree(name);
|
if (repeat != NULL) {
|
bool found = evaluate(repeat, startAt, afterAt, next);
|
|
pfree(repeat);
|
return found;
|
}
|
}
|
len = strlen(text);
|
copy = (char *) palloc(len + 1);
|
for (i = 0; i < len; i++) {
|
unsigned char ch = (unsigned char) text[i];
|
|
copy[i] = (char) ((ch >= 'a' && ch <= 'z') ? ch - 32 : ch);
|
}
|
copy[len] = '\0';
|
parse(copy);
|
pfree(copy);
|
if (empty_)
|
return false;
|
return search(startAt, afterAt, next);
|
}
|
|
} // namespace DbmsScheduler
|
|
extern "C"
|
{
|
|
PG_FUNCTION_INFO_V1(c_evaluateCalendarString);
|
|
Datum
|
c_evaluateCalendarString(PG_FUNCTION_ARGS)
|
{
|
char *calendarText = NULL;
|
TimestampTz startAt;
|
TimestampTz afterAt;
|
TimestampTz next;
|
bool found;
|
DbmsScheduler::Calendar calendar;
|
|
if (PG_ARGISNULL(0)) {
|
DbmsScheduler::logEventf("вход календаря", "[Calendar: -]");
|
PG_RETURN_NULL();
|
}
|
calendarText = text_to_cstring(DatumGetTextPP(PG_GETARG_DATUM(0)));
|
DbmsScheduler::logEventf("вход календаря", "[Calendar: %s]", calendarText);
|
if (PG_ARGISNULL(2))
|
afterAt = GetCurrentTimestamp();
|
else
|
afterAt = PG_GETARG_TIMESTAMPTZ(2);
|
if (PG_ARGISNULL(1))
|
startAt = afterAt;
|
else
|
startAt = PG_GETARG_TIMESTAMPTZ(1);
|
|
found = calendar.evaluate(calendarText, startAt, afterAt, &next);
|
pfree(calendarText);
|
if (!found)
|
PG_RETURN_NULL();
|
PG_RETURN_TIMESTAMPTZ(next);
|
}
|
|
bool
|
rudb_scheduler_calendar_next(const char *calendar_text, TimestampTz start_at,
|
TimestampTz after_at, TimestampTz *next_out)
|
{
|
DbmsScheduler::Calendar calendar;
|
|
if (calendar_text == NULL || next_out == NULL)
|
return false;
|
return calendar.evaluate(calendar_text, start_at, after_at, next_out);
|
}
|
|
} // extern "C"
|