Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*-------------------------------------------------------------------------
 *
 * provider_ollama.c
 *      Ollama local embedding provider implementation
 *
 * Ollama allows running local embedding models. This provider connects to
 * a local Ollama instance (default: http://localhost:11434).
 *
 * Copyright (c) 2025 - 2026, pgEdge, Inc.
 *
 *-------------------------------------------------------------------------
 */
#include "vectorizer/pgedge_vectorizer.h"
 
#include <curl/curl.h>
 
#include "utils/memutils.h"
 
/*
 * Response buffer for libcurl
 */
typedef struct
{
    char *data;
    size_t size;
} ResponseBuffer;
 
/*
 * Static variables
 */
static bool provider_initialized = false;
 
/*
 * Forward declarations
 */
static bool ollama_init(char **error_msg);
static void ollama_cleanup(void);
static float *ollama_generate(const char *text, int *dim, char **error_msg);
static float **ollama_generate_batch(const char **texts, int count, int *dim, char **error_msg);
 
/* Helper functions */
static char *escape_json_string(const char *str);
static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp);
static float *parse_ollama_embedding_response(const char *json_response, int *dim, char **error_msg);
 
/*
 * Ollama Provider struct
 */
EmbeddingProvider OllamaProvider = {
    .name = "ollama",
    .init = ollama_init,
    .cleanup = ollama_cleanup,
    .generate = ollama_generate,
    .generate_batch = ollama_generate_batch
};
 
/*
 * Initialize Ollama provider
 */
static bool
ollama_init(char **error_msg)
{
    if (provider_initialized)
        return true;
 
    /* Initialize curl globally */
    curl_global_init(CURL_GLOBAL_DEFAULT);
 
    /* Ollama doesn't require API key, but we verify the endpoint is reachable */
    provider_initialized = true;
    elog(DEBUG1, "Ollama provider initialized successfully");
    return true;
}
 
/*
 * Cleanup Ollama provider
 */
static void
ollama_cleanup(void)
{
    if (!provider_initialized)
        return;
 
    curl_global_cleanup();
    provider_initialized = false;
    elog(DEBUG1, "Ollama provider cleaned up");
}
 
/*
 * Generate a single embedding
 */
static float *
ollama_generate(const char *text, int *dim, char **error_msg)
{
    CURL *curl;
    CURLcode res;
    struct curl_slist *headers = NULL;
    char *json_request;
    char *url;
    StringInfoData request_buf;
    ResponseBuffer response;
    float *embedding = NULL;
    long response_code;
    char *escaped;
 
    if (!provider_initialized)
    {
        if (!ollama_init(error_msg))
            return NULL;
    }
 
    /* Initialize response buffer */
    response.data = palloc(1);
    response.data[0] = '\0';
    response.size = 0;
 
    /* Build JSON request - Ollama API format */
    initStringInfo(&request_buf);
    escaped = escape_json_string(text);
    appendStringInfo(&request_buf, "{\"model\":\"%s\",\"prompt\":\"%s\"}",
                     pgedge_vectorizer_model, escaped);
    pfree(escaped);
    json_request = request_buf.data;
 
    /* Build URL */
    url = psprintf("%s/api/embeddings", pgedge_vectorizer_api_url);
 
    /* Initialize curl */
    curl = curl_easy_init();
    if (!curl)
    {
        *error_msg = pstrdup("Failed to initialize libcurl");
        pfree(response.data);
        return NULL;
    }
 
    /* Set up headers - Ollama doesn't require authentication */
    headers = curl_slist_append(headers, "Content-Type: application/json; charset=utf-8");
 
    /* Configure curl */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_request);
    /* flawfinder: ignore - json_request from cJSON is null-terminated */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(json_request));
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 300L);  /* 5 minute timeout */
 
    /* Perform the request */
    res = curl_easy_perform(curl);
 
    if (res != CURLE_OK)
    {
        *error_msg = psprintf("curl_easy_perform() failed: %s", curl_easy_strerror(res));
        goto cleanup;
    }
 
    /* Check HTTP response code */
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
    if (response_code != 200)
    {
        *error_msg = psprintf("Ollama API returned HTTP %ld: %s",
                              response_code, response.data);
        goto cleanup;
    }
 
    /* Parse the response */
    embedding = parse_ollama_embedding_response(response.data, dim, error_msg);
 
cleanup:
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    pfree(json_request);
    pfree(response.data);
 
    return embedding;
}
 
/*
 * Generate embeddings in batch
 *
 * Ollama API doesn't support batch requests, so we call the single
 * endpoint multiple times. This is less efficient but simpler.
 */
static float **
ollama_generate_batch(const char **texts, int count, int *dim, char **error_msg)
{
    float **embeddings;
    int i;
 
    if (!provider_initialized)
    {
        if (!ollama_init(error_msg))
            return NULL;
    }
 
    /* Allocate array for embeddings */
    embeddings = (float **) palloc0(sizeof(float *) * count);
 
    /* Generate each embedding individually */
    for (i = 0; i < count; i++)
    {
        embeddings[i] = ollama_generate(texts[i], dim, error_msg);
        if (embeddings[i] == NULL)
        {
            /* Clean up on error */
            for (int j = 0; j < i; j++)
            {
                if (embeddings[j] != NULL)
                    pfree(embeddings[j]);
            }
            pfree(embeddings);
            return NULL;
        }
    }
 
    return embeddings;
}
 
/*
 * Curl write callback
 */
static size_t
write_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    ResponseBuffer *mem = (ResponseBuffer *) userp;
 
    char *ptr = repalloc(mem->data, mem->size + realsize + 1);
    if (!ptr)
        return 0;  /* Out of memory */
 
    mem->data = ptr;
    /* flawfinder: ignore - buffer was realloced to mem->size + realsize + 1 */
    memcpy(&(mem->data[mem->size]), contents, realsize);  /* nosemgrep */
    mem->size += realsize;
    mem->data[mem->size] = 0;
 
    return realsize;
}
 
/*
 * Escape a string for JSON
 */
static char *
escape_json_string(const char *str)
{
    StringInfoData buf;
    const char *p;
 
    initStringInfo(&buf);
 
    for (p = str; *p; p++)
    {
        switch (*p)
        {
            case '"':
                appendStringInfoString(&buf, "\\\"");
                break;
            case '\\':
                appendStringInfoString(&buf, "\\\\");
                break;
            case '\b':
                appendStringInfoString(&buf, "\\b");
                break;
            case '\f':
                appendStringInfoString(&buf, "\\f");
                break;
            case '\n':
                appendStringInfoString(&buf, "\\n");
                break;
            case '\r':
                appendStringInfoString(&buf, "\\r");
                break;
            case '\t':
                appendStringInfoString(&buf, "\\t");
                break;
            default:
                if ((unsigned char) *p < 32)
                    appendStringInfo(&buf, "\\u%04x", (unsigned char) *p);
                else
                    appendStringInfoChar(&buf, *p);
                break;
        }
    }
 
    return buf.data;
}
 
/*
 * Parse Ollama embedding response
 *
 * Expected format:
 * {"embedding":[0.1,0.2,0.3,...]}
 */
static float *
parse_ollama_embedding_response(const char *json_response, int *dim, char **error_msg)
{
    const char *p;
    float *embedding = NULL;
    int value_idx = 0;
    char value_buf[32];
    int value_pos;
 
    /* Find "embedding" array */
    p = strstr(json_response, "\"embedding\"");
    if (p == NULL)
    {
        *error_msg = pstrdup("Invalid response: 'embedding' field not found");
        return NULL;
    }
 
    /* Find opening bracket */
    p = strchr(p, '[');
    if (p == NULL)
    {
        *error_msg = pstrdup("Invalid response: embedding array not found");
        return NULL;
    }
    p++;
 
    /* Count dimensions if not known */
    if (*dim == 0)
    {
        const char *temp = p;
        int comma_count = 0;
        while (*temp && *temp != ']')
        {
            if (*temp == ',')
                comma_count++;
            temp++;
        }
        *dim = comma_count + 1;
    }
 
    /* Allocate array for embedding */
    embedding = (float *) palloc(sizeof(float) * (*dim));
 
    /* Parse values */
    while (value_idx < *dim && *p && *p != ']')
    {
        /* Skip whitespace and commas */
        while (*p && (*p == ' ' || *p == ',' || *p == '\t' || *p == '\n'))
            p++;
 
        if (*p == ']')
            break;
 
        /* Read numeric value */
        value_pos = 0;
        while (*p && (isdigit(*p) || *p == '.' || *p == '-' || *p == '+' || *p == 'e' || *p == 'E'))
        {
            if (value_pos < sizeof(value_buf) - 1)
                value_buf[value_pos++] = *p;
            p++;
        }
        value_buf[value_pos] = '\0';
 
        if (value_pos > 0)
        {
            embedding[value_idx] = atof(value_buf);
            value_idx++;
        }
    }
 
    if (value_idx != *dim)
    {
        *error_msg = psprintf("Dimension mismatch: expected %d, got %d", *dim, value_idx);
        pfree(embedding);
        return NULL;
    }
 
    return embedding;
}