-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandomstring.c
More file actions
68 lines (53 loc) · 1.45 KB
/
randomstring.c
File metadata and controls
68 lines (53 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "postgres.h"
#include "utils/datum.h"
#include "utils/array.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/numeric.h"
#include "utils/builtins.h"
#include "utils/palloc.h"
#include "utils/elog.h"
#include "catalog/pg_type.h"
#include "nodes/execnodes.h"
#include "access/tupmacs.h"
#include "utils/pg_crc.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(random_string);
PG_FUNCTION_INFO_V1(random_bytea);
Datum
random_string(PG_FUNCTION_ARGS)
{
int i;
int32 len = PG_GETARG_INT32(0);
char *str;
char *chars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+={}[];:'\"\\|/?.>,<~`";
/* some basic sanity checks */
if (len <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("length must be a non-negative integer")));
str = palloc(len + 1);
for (i = 0; i < len; i++)
str[i] = chars[random() % 62];
str[len] = '\0';
PG_RETURN_TEXT_P(cstring_to_text(str));
}
Datum
random_bytea(PG_FUNCTION_ARGS)
{
int i;
int32 len = PG_GETARG_INT32(0);
bytea *val;
unsigned char *ptr;
/* some basic sanity checks */
if (len <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("length must be a non-negative integer")));
val = palloc(VARHDRSZ + len);
SET_VARSIZE(val, VARHDRSZ + len);
ptr = (unsigned char *) VARDATA(val);
for (i = 0; i < len; i++)
ptr[i] = (unsigned char) (random() % 255);
PG_RETURN_BYTEA_P(val);
}