/* * SPDX-FileCopyrightText: 2023 jordi fita mas * * SPDX-License-Identifier: PostgreSQL */ #include #include #include #include "es.h" PG_MODULE_MAGIC; static bool string2vatin(const char *str, text **result) { const char *r = str; char *vatin = NULL; size_t len; char country[2]; int i; for (; *r == ' '; r++); if (*r == 0) { goto invalidvatin; } len = strlen(r); for (; *(r + len - 1) == ' '; len--); if (len < 3) { goto invalidvatin; } for(i = 0; i < 2; i++, r++, len--) { country[i] = toupper(*r); } if (country[0] == 'E' && country[1] == 'S') { vatin = check_es_vat(r, len); if (vatin == NULL) { goto invalidvatin; } } else { // For countries without validation yet assume it is correct vatin = pstrdup(r); } *result = (text *)palloc(2 + len + VARHDRSZ); SET_VARSIZE(*result, 2 + len + VARHDRSZ); memcpy(VARDATA(*result), country, 2); memcpy(VARDATA(*result) + 2, vatin, len); pfree(vatin); return true; invalidvatin: ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for VAT number: \"%s\"", str))); return false; } PG_FUNCTION_INFO_V1(vatin_in); Datum vatin_in(PG_FUNCTION_ARGS) { const char *str = PG_GETARG_CSTRING(0); text *result = NULL; if (!string2vatin(str, &result)) { PG_RETURN_NULL(); } PG_RETURN_TEXT_P(result); }