Remove log message
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.122 2004-08-04 09:05:17 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #include <assert.h>
24 #include <stdio.h>
25 #ifdef WIN32
26 #include <io.h>
27 #include <process.h>
28 #include <direct.h>
29 #else
30 #include <unistd.h>
31 #endif
32
33 #include <yaz/diagbib1.h>
34 #include <yaz/pquery.h>
35 #include <yaz/sortspec.h>
36 #include "index.h"
37 #include <charmap.h>
38 #include "zebraapi.h"
39
40 /* simple asserts to validate the most essential input args */
41 #define ASSERTZH assert(zh && zh->service)
42 #define ASSERTZHRES assert(zh && zh->service && zh->res)
43 #define ASSERTZS assert(zs)
44
45 /* A simple log macro */
46 /* don't break with older yazen that lack log_app2 */
47 #ifdef LOG_APP2
48 #define LOG_API LOG_APP2
49 #else
50 #define LOG_API LOG_DEBUG
51 #endif
52
53 static Res zebra_open_res (ZebraHandle zh);
54 static void zebra_close_res (ZebraHandle zh);
55
56
57 static void zebra_chdir (ZebraService zs)
58 {
59     const char *dir ;
60     ASSERTZS;
61     yaz_log(LOG_API,"zebra_chdir");
62     dir = res_get (zs->global_res, "chdir");
63     if (!dir)
64         return;
65     logf (LOG_DEBUG, "chdir %s", dir);
66 #ifdef WIN32
67     _chdir(dir);
68 #else
69     chdir (dir);
70 #endif
71 }
72
73 static void zebra_flush_reg (ZebraHandle zh)
74 {
75     ASSERTZH;
76     yaz_log(LOG_API,"zebra_flush_reg");
77     zh->errCode=0;
78     zebraExplain_flush (zh->reg->zei, zh);
79     
80     extract_flushWriteKeys (zh,1 /* final */);
81     zebra_index_merge (zh );
82 }
83
84 static struct zebra_register *zebra_register_open (ZebraService zs, 
85                                                    const char *name,
86                                                    int rw, int useshadow,
87                                                    Res res,
88                                                    const char *reg_path);
89 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
90
91 ZebraHandle zebra_open (ZebraService zs)
92 {
93     ZebraHandle zh;
94     const char *default_encoding;
95     ASSERTZS;
96     yaz_log(LOG_API,"zebra_open");
97
98     if (!zs)
99         return 0;
100
101     zh = (ZebraHandle) xmalloc (sizeof(*zh));
102     yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
103
104     zh->service = zs;
105     zh->reg = 0;          /* no register attached yet */
106     zh->sets = 0;
107     zh->destroyed = 0;
108     zh->errCode = 0;
109     zh->errString = 0;
110     zh->res = 0; 
111     zh->user_perm = 0;
112
113     zh->reg_name = xstrdup ("");
114     zh->path_reg = 0;
115     zh->num_basenames = 0;
116     zh->basenames = 0;
117
118     zh->trans_no = 0;
119     zh->trans_w_no = 0;
120
121     zh->lock_normal = 0;
122     zh->lock_shadow = 0;
123
124     zh->shadow_enable = 1;
125
126     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
127     zh->record_encoding = xstrdup (default_encoding);
128
129     zh->iconv_to_utf8 =
130         yaz_iconv_open ("UTF-8", default_encoding);
131     if (zh->iconv_to_utf8 == 0)
132         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
133            default_encoding);
134     zh->iconv_from_utf8 =
135         yaz_iconv_open (default_encoding, "UTF-8");
136     if (zh->iconv_to_utf8 == 0)
137         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
138            default_encoding);
139
140     zebra_mutex_cond_lock (&zs->session_lock);
141
142     zh->next = zs->sessions;
143     zs->sessions = zh;
144
145     zebra_mutex_cond_unlock (&zs->session_lock);
146
147     return zh;
148 }
149
150 ZebraService zebra_start (const char *configName)
151 {
152     return zebra_start_res(configName, 0, 0);
153 }
154
155 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
156 {
157     Res res;
158
159     yaz_log(LOG_API|LOG_LOG,"zebra_start %s",configName);
160
161     if ((res = res_open (configName, def_res, over_res)))
162     {
163         ZebraService zh = xmalloc (sizeof(*zh));
164
165         yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
166         
167         zh->global_res = res;
168         zh->configName = xstrdup(configName);
169         zh->sessions = 0;
170         
171         zebra_chdir (zh);
172         
173         zebra_mutex_cond_init (&zh->session_lock);
174         if (!res_get (zh->global_res, "passwd"))
175             zh->passwd_db = NULL;
176         else
177         {
178             zh->passwd_db = passwd_db_open ();
179             if (!zh->passwd_db)
180                 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
181             else
182                 passwd_db_file (zh->passwd_db,
183                                 res_get (zh->global_res, "passwd"));
184         }
185         zh->path_root = res_get (zh->global_res, "root");
186         return zh;
187     }
188     return 0;
189 }
190
191
192 void zebra_pidfname(ZebraService zs, char *path)
193 {
194     zebra_lock_prefix (zs->global_res, path);
195     strcat(path, "zebrasrv.pid");
196 }
197
198 static
199 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
200                                             int rw, int useshadow, Res res,
201                                             const char *reg_path)
202 {
203     struct zebra_register *reg;
204     int record_compression = REC_COMPRESS_NONE;
205     const char *recordCompression = 0;
206     const char *profilePath;
207     char cwd[1024];
208
209     ASSERTZS;
210     
211     reg = xmalloc (sizeof(*reg));
212
213     assert (name);
214     reg->name = xstrdup (name);
215
216     reg->seqno = 0;
217     reg->last_val = 0;
218
219     assert (res);
220
221     yaz_log (LOG_LOG|LOG_API, "zebra_register_open rw = %d useshadow=%d p=%p,n=%s,rp=%s",
222              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
223     
224     reg->dh = data1_createx (DATA1_FLAG_XML);
225     if (!reg->dh)
226         return 0;
227     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
228     if (!reg->bfs)
229     {
230         data1_destroy(reg->dh);
231         return 0;
232     }
233     if (useshadow)
234         bf_cache (reg->bfs, res_get (res, "shadow"));
235
236     getcwd(cwd, sizeof(cwd)-1);
237     profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
238     yaz_log(LOG_LOG, "profilePath=%s cwd=%s", profilePath, cwd);
239
240     data1_set_tabpath (reg->dh, profilePath);
241     data1_set_tabroot (reg->dh, reg_path);
242     reg->recTypes = recTypes_init (reg->dh);
243     recTypes_default_handlers (reg->recTypes);
244
245     reg->zebra_maps = zebra_maps_open (res, reg_path);
246     reg->rank_classes = NULL;
247
248     reg->key_buf = 0;
249
250     reg->keys.buf_max = 0;
251     reg->keys.buf = 0;
252 #if IT_KEY_NEW
253     reg->keys.codec_handle = iscz1_start();
254 #endif
255
256     reg->sortKeys.buf = 0;
257     reg->sortKeys.buf_max = 0;
258
259     reg->records = 0;
260     reg->dict = 0;
261     reg->sortIdx = 0;
262     reg->isams = 0;
263     reg->matchDict = 0;
264     reg->isam = 0;
265     reg->isamc = 0;
266     reg->isamb = 0;
267     reg->zei = 0;
268     reg->matchDict = 0;
269     reg->key_file_no = 0;
270     reg->ptr_i=0;
271     
272     zebraRankInstall (reg, rank1_class);
273     zebraRankInstall (reg, rankzv_class);
274     zebraRankInstall (reg, rankliv_class);
275
276     recordCompression = res_get_def (res, "recordCompression", "none");
277     if (!strcmp (recordCompression, "none"))
278         record_compression = REC_COMPRESS_NONE;
279     if (!strcmp (recordCompression, "bzip2"))
280         record_compression = REC_COMPRESS_BZIP2;
281
282     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
283     {
284         logf (LOG_WARN, "rec_open");
285         return 0;
286     }
287     if (rw)
288     {
289         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
290     }
291     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
292     {
293         logf (LOG_WARN, "dict_open");
294         return 0;
295     }
296     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
297     {
298         logf (LOG_WARN, "sortIdx_open");
299         return 0;
300     }
301     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
302     {
303         struct ISAMS_M_s isams_m;
304         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
305                                       key_isams_m(res, &isams_m))))
306         {
307             logf (LOG_WARN, "isams_open");
308             return 0;
309         }
310     }
311     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
312     {
313         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
314                                   sizeof (struct it_key), res)))
315         {
316             logf (LOG_WARN, "is_open");
317             return 0;
318         }
319     }
320     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
321     {
322         struct ISAMC_M_s isamc_m;
323         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
324                                     rw, key_isamc_m(res, &isamc_m))))
325         {
326             logf (LOG_WARN, "isc_open");
327             return 0;
328         }
329     }
330     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
331     {
332         struct ISAMC_M_s isamc_m;
333         
334         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
335                                        rw, key_isamc_m(res, &isamc_m), 0)))
336         {
337             logf (LOG_WARN, "isamb_open");
338             return 0;
339         }
340     }
341     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
342     {
343         struct ISAMC_M_s isamc_m;
344         
345         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
346                                        rw, key_isamc_m(res, &isamc_m), 1)))
347         {
348             logf (LOG_WARN, "isamb_open");
349             return 0;
350         }
351     }
352     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
353     {
354         struct ISAMC_M_s isamc_m;
355         
356         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
357                                        rw, key_isamc_m(res, &isamc_m), -1)))
358         {
359             logf (LOG_WARN, "isamb_open");
360             return 0;
361         }
362     }
363     reg->zei = zebraExplain_open (reg->records, reg->dh,
364                                   res, rw, reg,
365                                   explain_extract);
366     if (!reg->zei)
367     {
368         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
369         return 0;
370     }
371     reg->active = 2;
372     yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
373     return reg;
374 }
375
376 int zebra_admin_shutdown (ZebraHandle zh)
377 {
378     ASSERTZH;
379     yaz_log(LOG_API,"zebra_admin_shutdown");
380     zh->errCode=0;
381
382     zebra_mutex_cond_lock (&zh->service->session_lock);
383     zh->service->stop_flag = 1;
384     zebra_mutex_cond_unlock (&zh->service->session_lock);
385     return 0;
386 }
387
388 int zebra_admin_start (ZebraHandle zh)
389 {
390     ZebraService zs;
391     ASSERTZH;
392     yaz_log(LOG_API,"zebra_admin_start");
393     zh->errCode=0;
394     zs = zh->service;
395     zebra_mutex_cond_lock (&zs->session_lock);
396     zebra_mutex_cond_unlock (&zs->session_lock);
397     return 0;
398 }
399
400 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
401 {
402     ASSERTZS;
403     yaz_log(LOG_LOG|LOG_API, "zebra_register_close p=%p", reg);
404     reg->stop_flag = 0;
405     zebra_chdir (zs);
406     if (reg->records)
407     {
408         zebraExplain_close (reg->zei);
409         dict_close (reg->dict);
410         if (reg->matchDict)
411             dict_close (reg->matchDict);
412         sortIdx_close (reg->sortIdx);
413         if (reg->isams)
414             isams_close (reg->isams);
415         if (reg->isam)
416             is_close (reg->isam);
417         if (reg->isamc)
418             isc_close (reg->isamc);
419         if (reg->isamb)
420             isamb_close (reg->isamb);
421         rec_close (&reg->records);
422     }
423
424     recTypes_destroy (reg->recTypes);
425     zebra_maps_close (reg->zebra_maps);
426     zebraRankDestroy (reg);
427     bfs_destroy (reg->bfs);
428     data1_destroy (reg->dh);
429
430     xfree (reg->sortKeys.buf);
431     xfree (reg->keys.buf);
432 #if IT_KEY_NEW
433     if (reg->keys.codec_handle)
434         iscz1_stop(reg->keys.codec_handle);
435 #endif
436
437     xfree (reg->key_buf);
438     xfree (reg->name);
439     xfree (reg);
440 }
441
442 int zebra_stop(ZebraService zs)
443 {
444     if (!zs)
445         return 0;
446     yaz_log (LOG_LOG|LOG_API, "zebra_stop");
447
448     while (zs->sessions)
449     {
450         zebra_close (zs->sessions);
451     }
452         
453     zebra_mutex_cond_destroy (&zs->session_lock);
454
455     if (zs->passwd_db)
456         passwd_db_close (zs->passwd_db);
457
458     res_close (zs->global_res);
459     xfree (zs->configName);
460     xfree (zs);
461     return 0;
462 }
463
464 int zebra_close (ZebraHandle zh)
465 {
466     ZebraService zs;
467     struct zebra_session **sp;
468     int i;
469
470     yaz_log(LOG_API,"zebra_close");
471     if (!zh)
472         return 0;
473     ASSERTZH;
474     zh->errCode=0;
475     
476     zs = zh->service;
477     yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
478     resultSetDestroy (zh, -1, 0, 0);
479
480     if (zh->reg)
481         zebra_register_close (zh->service, zh->reg);
482     zebra_close_res (zh);
483
484     xfree (zh->record_encoding);
485
486     for (i = 0; i < zh->num_basenames; i++)
487         xfree (zh->basenames[i]);
488     xfree (zh->basenames);
489
490     if (zh->iconv_to_utf8 != 0)
491         yaz_iconv_close (zh->iconv_to_utf8);
492     if (zh->iconv_from_utf8 != 0)
493         yaz_iconv_close (zh->iconv_from_utf8);
494
495     zebra_mutex_cond_lock (&zs->session_lock);
496     zebra_lock_destroy (zh->lock_normal);
497     zebra_lock_destroy (zh->lock_shadow);
498     sp = &zs->sessions;
499     while (1)
500     {
501         assert (*sp);
502         if (*sp == zh)
503         {
504             *sp = (*sp)->next;
505             break;
506         }
507         sp = &(*sp)->next;
508     }
509     zebra_mutex_cond_unlock (&zs->session_lock);
510     xfree (zh->reg_name);
511     xfree (zh->user_perm);
512     zh->service=0; /* more likely to trigger an assert */
513     xfree (zh->path_reg);
514     xfree (zh);
515     return 0;
516 }
517
518 struct map_baseinfo {
519     ZebraHandle zh;
520     NMEM mem;
521     int num_bases;
522     char **basenames;
523     int new_num_bases;
524     char **new_basenames;
525     int new_num_max;
526 };
527
528 static Res zebra_open_res (ZebraHandle zh)
529 {
530     Res res = 0;
531     char fname[512];
532     ASSERTZH;
533     zh->errCode=0;
534
535     if (zh->path_reg)
536     {
537         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
538         res = res_open (fname, zh->service->global_res, 0);
539         if (!res)
540             res = zh->service->global_res;
541     }
542     else if (*zh->reg_name == 0)
543     {
544         res = zh->service->global_res;
545     }
546     else
547     {
548         yaz_log (LOG_WARN, "no register root specified");
549         return 0;  /* no path for register - fail! */
550     }
551     return res;
552 }
553
554 static void zebra_close_res (ZebraHandle zh)
555 {
556     ASSERTZH;
557     zh->errCode=0;
558     if (zh->res != zh->service->global_res)
559         res_close (zh->res);
560     zh->res = 0;
561 }
562
563 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
564 {
565     ASSERTZH;
566     zh->errCode=0;
567     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
568         return 0;
569     if (!zh->res)
570     {
571         assert (zh->reg == 0);
572         assert (*zh->reg_name == 0);
573     }
574     else
575     {
576         if (zh->reg)
577         {
578             resultSetInvalidate (zh);
579             zebra_register_close (zh->service, zh->reg);
580             zh->reg = 0;
581         }
582         zebra_close_res(zh);
583     }
584     xfree (zh->reg_name);
585     zh->reg_name = xstrdup (new_reg);
586
587     xfree (zh->path_reg);
588     zh->path_reg = 0;
589     if (zh->service->path_root)
590     {
591         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
592                                 strlen(zh->reg_name) + 3);
593         strcpy (zh->path_reg, zh->service->path_root);
594         if (*zh->reg_name)
595         {
596             strcat (zh->path_reg, "/");
597             strcat (zh->path_reg, zh->reg_name);
598         }
599     }
600     zh->res = zebra_open_res (zh);
601     
602     if (zh->lock_normal)
603         zebra_lock_destroy (zh->lock_normal);
604     zh->lock_normal = 0;
605
606     if (zh->lock_shadow)
607         zebra_lock_destroy (zh->lock_shadow);
608     zh->lock_shadow = 0;
609
610     if (zh->res)
611     {
612         char fname[512];
613         const char *lock_area  =res_get (zh->res, "lockDir");
614         
615         if (!lock_area && zh->path_reg)
616             res_set (zh->res, "lockDir", zh->path_reg);
617         sprintf (fname, "norm.%s.LCK", zh->reg_name);
618         zh->lock_normal =
619             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
620         
621         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
622         zh->lock_shadow =
623             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
624
625     }
626     return 1;
627 }
628
629 void map_basenames_func (void *vp, const char *name, const char *value)
630 {
631     struct map_baseinfo *p = (struct map_baseinfo *) vp;
632     int i, no;
633     char fromdb[128], todb[8][128];
634     
635     no =
636         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
637                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
638                 todb[5], todb[6], todb[7]);
639     if (no < 2)
640         return ;
641     no--;
642     for (i = 0; i<p->num_bases; i++)
643         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
644         {
645             p->basenames[i] = 0;
646             for (i = 0; i < no; i++)
647             {
648                 if (p->new_num_bases == p->new_num_max)
649                     return;
650                 p->new_basenames[(p->new_num_bases)++] = 
651                     nmem_strdup (p->mem, todb[i]);
652             }
653             return;
654         }
655 }
656
657 void map_basenames (ZebraHandle zh, ODR stream,
658                     int *num_bases, char ***basenames)
659 {
660     struct map_baseinfo info;
661     struct map_baseinfo *p = &info;
662     int i;
663     ASSERTZH;
664     yaz_log(LOG_API,"map_basenames ");
665     zh->errCode=0;
666
667     info.zh = zh;
668     info.num_bases = *num_bases;
669     info.basenames = *basenames;
670     info.new_num_max = 128;
671     info.new_num_bases = 0;
672     info.new_basenames = (char **)
673         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
674     info.mem = stream->mem;
675
676     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
677     
678     for (i = 0; i<p->num_bases; i++)
679         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
680         {
681             p->new_basenames[(p->new_num_bases)++] = 
682                 nmem_strdup (p->mem, p->basenames[i]);
683         }
684     *num_bases = info.new_num_bases;
685     *basenames = info.new_basenames;
686     for (i = 0; i<*num_bases; i++)
687         logf (LOG_LOG, "base %s", (*basenames)[i]);
688 }
689
690 int zebra_select_database (ZebraHandle zh, const char *basename)
691 {
692     ASSERTZH;
693     yaz_log(LOG_API,"zebra_select_database %s",basename);
694     zh->errCode=0;
695     return zebra_select_databases (zh, 1, &basename);
696 }
697
698 int zebra_select_databases (ZebraHandle zh, int num_bases,
699                             const char **basenames)
700 {
701     int i;
702     const char *cp;
703     int len = 0;
704     char *new_reg = 0;
705     ASSERTZH;
706     yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
707                     num_bases,basenames[0]);
708     zh->errCode=0;
709     
710     if (num_bases < 1)
711     {
712         zh->errCode = 23;
713         return -1;
714     }
715     for (i = 0; i < zh->num_basenames; i++)
716         xfree (zh->basenames[i]);
717     xfree (zh->basenames);
718     
719     zh->num_basenames = num_bases;
720     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
721     for (i = 0; i < zh->num_basenames; i++)
722         zh->basenames[i] = xstrdup (basenames[i]);
723
724     cp = strrchr(basenames[0], '/');
725     if (cp)
726     {
727         len = cp - basenames[0];
728         new_reg = xmalloc (len + 1);
729         memcpy (new_reg, basenames[0], len);
730         new_reg[len] = '\0';
731     }
732     else
733         new_reg = xstrdup ("");
734     for (i = 1; i<num_bases; i++)
735     {
736         const char *cp1;
737
738         cp1 = strrchr (basenames[i], '/');
739         if (cp)
740         {
741             if (!cp1)
742             {
743                 zh->errCode = 23;
744                 return -1;
745             }
746             if (len != cp1 - basenames[i] ||
747                 memcmp (basenames[i], new_reg, len))
748             {
749                 zh->errCode = 23;
750                 return -1;
751             }
752         }
753         else
754         {
755             if (cp1)
756             {
757                 zh->errCode = 23;
758                 return -1;
759             }
760         }
761     }
762     zebra_select_register (zh, new_reg);
763     xfree (new_reg);
764     if (!zh->res)
765     {
766         zh->errCode = 109;
767         return -1;
768     }
769     if (!zh->lock_normal || !zh->lock_shadow)
770     {
771         zh->errCode = 2;
772         return -1;
773     }
774     return 0;
775 }
776
777 int zebra_search_RPN (ZebraHandle zh, ODR o,
778                        Z_RPNQuery *query, const char *setname, int *hits)
779 {
780     ASSERTZH;
781     yaz_log(LOG_API,"zebra_search_rpn");
782     zh->errCode=0;
783     zh->hits = 0;
784     *hits = 0;
785
786     if (zebra_begin_read (zh))
787         return 1;
788
789     zebra_livcode_transform(zh, query);
790
791     resultSetAddRPN (zh, odr_extract_mem(o), query, 
792                      zh->num_basenames, zh->basenames, setname);
793
794     zebra_end_read (zh);
795
796     *hits = zh->hits;
797     return 0;
798 }
799
800 int zebra_records_retrieve (ZebraHandle zh, ODR stream,
801                              const char *setname, Z_RecordComposition *comp,
802                              oid_value input_format, int num_recs,
803                              ZebraRetrievalRecord *recs)
804 {
805     ZebraPosSet poset;
806     int i, *pos_array, ret = 0;
807     ASSERTZH;
808     yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
809     zh->errCode=0;
810
811     if (!zh->res)
812     {
813         zh->errCode = 30;
814         zh->errString = odr_strdup (stream, setname);
815         return -1;
816     }
817     
818     zh->errCode = 0;
819
820     if (zebra_begin_read (zh))
821         return -1;
822
823     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
824     for (i = 0; i<num_recs; i++)
825         pos_array[i] = recs[i].position;
826     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
827     if (!poset)
828     {
829         logf (LOG_DEBUG, "zebraPosSetCreate error");
830         zh->errCode = 30;
831         zh->errString = nmem_strdup (stream->mem, setname);
832         ret = -1;
833     }
834     else
835     {
836         for (i = 0; i<num_recs; i++)
837         {
838             if (poset[i].term)
839             {
840                 recs[i].errCode = 0;
841                 recs[i].format = VAL_SUTRS;
842                 recs[i].len = strlen(poset[i].term);
843                 recs[i].buf = poset[i].term;
844                 recs[i].base = poset[i].db;
845             }
846             else if (poset[i].sysno)
847             {
848                 recs[i].errCode =
849                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
850                                         stream, input_format, comp,
851                                         &recs[i].format, &recs[i].buf,
852                                         &recs[i].len,
853                                         &recs[i].base);
854                 recs[i].errString = NULL;
855             }
856             else
857             {
858                 char num_str[20];
859
860                 sprintf (num_str, "%d", pos_array[i]);  
861                 zh->errCode = 13;
862                 zh->errString = odr_strdup (stream, num_str);
863                 ret = -1;
864                 break;
865             }
866         }
867         zebraPosSetDestroy (zh, poset, num_recs);
868     }
869     zebra_end_read (zh);
870     xfree (pos_array);
871     return ret;
872 }
873
874 int zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
875                  oid_value attributeset,
876                  int *position, int *num_entries, ZebraScanEntry **entries,
877                  int *is_partial)
878 {
879     ASSERTZH;
880     yaz_log(LOG_API,"zebra_scan");
881     zh->errCode=0;
882     if (zebra_begin_read (zh))
883     {
884         *entries = 0;
885         *num_entries = 0;
886         return 1;
887     }
888     rpn_scan (zh, stream, zapt, attributeset,
889               zh->num_basenames, zh->basenames, position,
890               num_entries, entries, is_partial, 0, 0);
891     zebra_end_read (zh);
892     return 0;
893 }
894
895 int zebra_sort (ZebraHandle zh, ODR stream,
896                  int num_input_setnames, const char **input_setnames,
897                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
898                  int *sort_status)
899 {
900     ASSERTZH;
901     yaz_log(LOG_API,"zebra_sort");
902     zh->errCode=0;
903     if (zebra_begin_read (zh))
904         return 1;
905     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
906                    output_setname, sort_sequence, sort_status);
907     zebra_end_read(zh);
908     return 0;
909 }
910
911 int zebra_deleleResultSet(ZebraHandle zh, int function,
912                           int num_setnames, char **setnames,
913                           int *statuses)
914 {
915     int i, status;
916     ASSERTZH;
917     yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
918     zh->errCode=0;
919     if (zebra_begin_read(zh))
920         return Z_DeleteStatus_systemProblemAtTarget;
921     switch (function)
922     {
923     case Z_DeleteResultSetRequest_list:
924         resultSetDestroy (zh, num_setnames, setnames, statuses);
925         break;
926     case Z_DeleteResultSetRequest_all:
927         resultSetDestroy (zh, -1, 0, statuses);
928         break;
929     }
930     zebra_end_read (zh);
931     status = Z_DeleteStatus_success;
932     for (i = 0; i<num_setnames; i++)
933         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
934             status = statuses[i];
935     return status;
936 }
937
938 int zebra_errCode (ZebraHandle zh)
939 {
940     if (zh)
941     {
942         yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
943         return zh->errCode;
944     }
945     yaz_log(LOG_API,"zebra_errCode: o");
946     return 0; 
947 }
948
949 const char *zebra_errString (ZebraHandle zh)
950 {
951     const char *e="";
952     if (zh)
953         e= diagbib1_str (zh->errCode);
954     yaz_log(LOG_API,"zebra_errString: %s",e);
955     return e;
956 }
957
958 char *zebra_errAdd (ZebraHandle zh)
959 {
960     char *a="";
961     if (zh)
962         a= zh->errString;
963     yaz_log(LOG_API,"zebra_errAdd: %s",a);
964     return a;
965 }
966
967 void zebra_clearError(ZebraHandle zh)
968 {
969     if (zh)
970     {
971         zh->errCode=0;
972         zh->errString="";
973     }
974 }
975
976 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
977 {
978     const char *p;
979     char u[40];
980     ZebraService zs;
981
982     ASSERTZH;
983     zh->errCode=0;
984     zs= zh->service;
985     
986     sprintf(u, "perm.%.30s", user ? user : "anonymous");
987     p = res_get(zs->global_res, u);
988     xfree (zh->user_perm);
989     zh->user_perm = xstrdup(p ? p : "r");
990
991     /* users that don't require a password .. */
992     if (zh->user_perm && strchr(zh->user_perm, 'a'))
993         return 0;
994     
995     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
996         return 0;
997     return 1;
998 }
999
1000 int zebra_admin_import_begin (ZebraHandle zh, const char *database,
1001                                const char *record_type)
1002 {
1003     ASSERTZH;
1004     yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s", 
1005                      database, record_type);
1006     zh->errCode=0;
1007     if (zebra_select_database(zh, database))
1008         return 1;
1009     if (zebra_begin_trans (zh, 1))
1010         return 1;
1011     return 0;
1012 }
1013
1014 int zebra_admin_import_end (ZebraHandle zh)
1015 {
1016     ASSERTZH;
1017     yaz_log(LOG_API,"zebra_admin_import_end");
1018     zh->errCode=0;
1019     zebra_end_trans (zh);
1020     return 0;
1021 }
1022
1023 int zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1024 {
1025     SYSNO sysno;
1026     int i;
1027     ASSERTZH;
1028     yaz_log(LOG_API,"zebra_admin_import_segment");
1029     zh->errCode=0;
1030     for (i = 0; i<segment->num_segmentRecords; i++)
1031     {
1032         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1033
1034         printf ("--------------%d--------------------\n", i);
1035         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1036         {
1037             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1038             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1039             {
1040                 Odr_oct *oct = fragment->u.notExternallyTagged;
1041                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1042                         oct->buf);
1043                 
1044                 sysno = 0;
1045                 
1046                 zebra_update_record(zh, 
1047                                     0, /* record Type */
1048                                     &sysno,
1049                                     0, /* match */
1050                                     0, /* fname */
1051                                     oct->buf, oct->len,
1052                                     0);
1053             }
1054         }
1055     }
1056     return 0;
1057 }
1058
1059 int zebra_admin_exchange_record (ZebraHandle zh,
1060                                  const char *rec_buf,
1061                                  size_t rec_len,
1062                                  const char *recid_buf, size_t recid_len,
1063                                  int action)
1064     /* 1 = insert. Fail it already exists */
1065     /* 2 = replace. Fail it does not exist */
1066     /* 3 = delete. Fail if does not exist */
1067     /* 4 = update. Insert/replace */
1068 {
1069     SYSNO sysno = 0;
1070     char *rinfo = 0;
1071     char recid_z[256];
1072     ASSERTZH;
1073     yaz_log(LOG_API,"zebra_admin_exchange_record ac=%d", action);
1074     zh->errCode=0;
1075
1076     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1077         return -1;
1078     memcpy (recid_z, recid_buf, recid_len);
1079     recid_z[recid_len] = 0;
1080
1081     if (zebra_begin_trans(zh, 1))
1082         return -1;
1083
1084     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1085     if (rinfo)
1086     {
1087         if (action == 1)  /* fail if insert */
1088         {
1089              zebra_end_trans(zh);
1090              return -1;
1091         }
1092
1093         memcpy (&sysno, rinfo+1, sizeof(sysno));
1094     }
1095     else
1096     {
1097         if (action == 2 || action == 3) /* fail if delete or update */
1098         {
1099             zebra_end_trans(zh);
1100             return -1;
1101         }
1102         action = 1;  /* make it an insert (if it's an update).. */
1103     }
1104     buffer_extract_record (zh, rec_buf, rec_len,
1105                            action == 3 ? 1 : 0 /* delete flag */,
1106                            0, /* test mode */
1107                            0, /* recordType */
1108                            &sysno, 
1109                            0, /* match */
1110                            0, /* fname */
1111                            0, /* force update */
1112                            1  /* allow update */
1113         );
1114     if (action == 1)
1115     {
1116         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1117     }
1118     else if (action == 3)
1119     {
1120         dict_delete (zh->reg->matchDict, recid_z);
1121     }
1122     zebra_end_trans(zh);
1123     return 0;
1124 }
1125
1126 int delete_w_handle(const char *info, void *handle)
1127 {
1128     ZebraHandle zh = (ZebraHandle) handle;
1129     ISAMC_P pos;
1130
1131     if (*info == sizeof(pos))
1132     {
1133         memcpy (&pos, info+1, sizeof(pos));
1134         isamb_unlink(zh->reg->isamb, pos);
1135     }
1136     return 0;
1137 }
1138
1139 static int delete_SU_handle(void *handle, int ord)
1140 {
1141     ZebraHandle zh = (ZebraHandle) handle;
1142     char ord_buf[20];
1143     int ord_len;
1144
1145     ord_len = key_SU_encode (ord, ord_buf);
1146     ord_buf[ord_len] = '\0';
1147
1148     assert (zh->reg->isamb);
1149     dict_delete_subtree(zh->reg->dict, ord_buf,
1150                         zh, delete_w_handle);
1151     return 0;
1152 }
1153
1154 int zebra_drop_database  (ZebraHandle zh, const char *database)
1155 {
1156     int ret = 0;
1157     ASSERTZH;
1158     yaz_log(LOG_API,"zebra_drop_database");
1159     zh->errCode = 0;
1160
1161     if (zebra_select_database (zh, database))
1162         return -1;
1163     if (zebra_begin_trans (zh, 1))
1164         return -1;
1165     if (zh->reg->isamb)
1166     {
1167         zebraExplain_curDatabase (zh->reg->zei, database);
1168         
1169         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1170         zebraExplain_removeDatabase(zh->reg->zei, zh);
1171     }
1172     else
1173     {
1174         yaz_log(LOG_WARN, "drop database only supported for isam:b");
1175         ret = -1;
1176     }
1177     zebra_end_trans (zh);
1178     return ret;
1179 }
1180
1181 int zebra_create_database (ZebraHandle zh, const char *database)
1182 {
1183     ASSERTZH;
1184     yaz_log(LOG_API,"zebra_create_database");
1185     zh->errCode=0;
1186
1187     if (zebra_select_database (zh, database))
1188         return -1;
1189     if (zebra_begin_trans (zh, 1))
1190         return -1;
1191
1192     /* announce database */
1193     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1194                                   /* explainDatabase */))
1195     {
1196         zebra_end_trans (zh);
1197         zh->errCode = 224;
1198         zh->errString = "database already exist";
1199         return -1;
1200     }
1201     zebra_end_trans (zh);
1202     return 0;
1203 }
1204
1205 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1206                        const char *input_str, int input_len,
1207                        char *output_str, int output_len)
1208 {
1209     WRBUF wrbuf;
1210     ASSERTZH;
1211     yaz_log(LOG_API,"zebra_string_norm ");
1212     zh->errCode=0;
1213     if (!zh->reg->zebra_maps)
1214         return -1;
1215     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1216                           input_str, input_len);
1217     if (!wrbuf)
1218         return -2;
1219     if (wrbuf_len(wrbuf) >= output_len)
1220         return -3;
1221     if (wrbuf_len(wrbuf))
1222         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1223     output_str[wrbuf_len(wrbuf)] = '\0';
1224     return wrbuf_len(wrbuf);
1225 }
1226
1227
1228 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1229 {
1230     char state_fname[256];
1231     char *fname;
1232     long p = getpid();
1233     FILE *f;
1234     ASSERTZH;
1235     yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1236     zh->errCode=0;
1237
1238     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1239     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1240     f = fopen (fname, "w");
1241
1242     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1243     fprintf (f, "%c %d %ld\n", val, seqno, p);
1244     fclose (f);
1245     xfree (fname);
1246     return 0;
1247 }
1248
1249 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1250 {
1251     char state_fname[256];
1252     char *fname;
1253     FILE *f;
1254
1255     ASSERTZH;
1256     yaz_log(LOG_API,"zebra_get_state ");
1257     zh->errCode=0;
1258     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1259     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1260     f = fopen (fname, "r");
1261     *val = 'o';
1262     *seqno = 0;
1263
1264     if (f)
1265     {
1266         fscanf (f, "%c %d", val, seqno);
1267         fclose (f);
1268     }
1269     xfree (fname);
1270     return 0;
1271 }
1272
1273 int zebra_begin_read (ZebraHandle zh)
1274 {
1275     return zebra_begin_trans(zh, 0);
1276 }
1277
1278 int zebra_end_read (ZebraHandle zh)
1279 {
1280     return zebra_end_trans(zh);
1281 }
1282
1283 static void read_res_for_transaction(ZebraHandle zh)
1284 {
1285     const char *group = res_get(zh->res, "group");
1286     const char *v;
1287     
1288     zh->m_group = group;
1289     v = res_get_prefix(zh->res, "followLinks", group, "1");
1290     zh->m_follow_links = atoi(v);
1291
1292     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1293     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1294
1295     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1296     zh->m_store_keys = atoi(v);
1297
1298     v = res_get_prefix(zh->res, "storeData", group, "1");
1299     zh->m_store_data = atoi(v);
1300
1301     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1302     zh->m_explain_database = atoi(v);
1303
1304     v = res_get_prefix(zh->res, "openRW", group, "1");
1305     zh->m_flag_rw = atoi(v);
1306
1307     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1308     zh->m_file_verbose_limit = atoi(v);
1309 }
1310
1311 int zebra_begin_trans (ZebraHandle zh, int rw)
1312 {
1313     if (!zh->res)
1314     {
1315         zh->errCode = 2;
1316         zh->errString = "zebra_begin_trans: no database selected";
1317         return -1;
1318     }
1319     ASSERTZHRES;
1320     yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1321
1322     if (zh->user_perm)
1323     {
1324         if (rw && !strchr(zh->user_perm, 'w'))
1325         {
1326             zh->errCode = 223;
1327             zh->errString = 0;
1328             return -1;
1329         }
1330     }
1331
1332     assert (zh->res);
1333     if (rw)
1334     {
1335         int pass;
1336         int seqno = 0;
1337         char val = '?';
1338         const char *rval = 0;
1339         
1340         (zh->trans_no++);
1341         if (zh->trans_w_no)
1342         {
1343             read_res_for_transaction(zh);
1344             return 0;
1345         }
1346         if (zh->trans_no != 1)
1347         {
1348             zh->errCode = 2;
1349             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1350             return -1;
1351         }
1352         if (zh->reg)
1353         {
1354             resultSetInvalidate (zh);
1355             zebra_register_close (zh->service, zh->reg);
1356         }
1357         zh->trans_w_no = zh->trans_no;
1358
1359         zh->errCode=0;
1360         
1361         zh->records_inserted = 0;
1362         zh->records_updated = 0;
1363         zh->records_deleted = 0;
1364         zh->records_processed = 0;
1365         
1366 #if HAVE_SYS_TIMES_H
1367         times (&zh->tms1);
1368 #endif
1369         /* lock */
1370         if (zh->shadow_enable)
1371             rval = res_get (zh->res, "shadow");
1372         
1373         for (pass = 0; pass < 2; pass++)
1374         {
1375             if (rval)
1376             {
1377                 zebra_lock_r (zh->lock_normal);
1378                 zebra_lock_w (zh->lock_shadow);
1379             }
1380             else
1381             {
1382                 zebra_lock_w (zh->lock_normal);
1383                 zebra_lock_w (zh->lock_shadow);
1384             }
1385             
1386             zebra_get_state (zh, &val, &seqno);
1387             if (val == 'c')
1388             {
1389                 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1390                 zebra_unlock (zh->lock_shadow);
1391                 zebra_unlock (zh->lock_normal);
1392                 zebra_commit (zh);
1393                 continue;
1394             }
1395             else if (val == 'd')
1396             {
1397                 if (rval)
1398                 {
1399                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1400                                              zh->path_reg);
1401                     yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1402                     bf_commitClean (bfs, rval);
1403                     bfs_destroy (bfs);
1404             }
1405                 else
1406                 {
1407                     yaz_log (LOG_WARN, "your previous transaction didn't finish");
1408                 }
1409             }
1410             break;
1411         }
1412         if (pass == 2)
1413         {
1414             yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1415             abort();
1416             return -1;
1417         }
1418         zebra_set_state (zh, 'd', seqno);
1419         
1420         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1421                                        1, rval ? 1 : 0, zh->res,
1422                                        zh->path_reg);
1423         if (zh->reg)
1424             zh->reg->seqno = seqno;
1425         else
1426         {
1427             zebra_set_state (zh, 'o', seqno);
1428             
1429             zebra_unlock (zh->lock_shadow);
1430             zebra_unlock (zh->lock_normal);
1431
1432             zh->trans_no--;
1433             zh->trans_w_no = 0;
1434
1435             zh->errCode = 2;
1436             zh->errString = "zebra_begin_trans: cannot open register";
1437             yaz_log(LOG_FATAL, zh->errString);
1438             return -1;
1439         }
1440     }
1441     else
1442     {
1443         int dirty = 0;
1444         char val;
1445         int seqno;
1446         
1447         (zh->trans_no)++;
1448         
1449         if (zh->trans_no != 1)
1450         {
1451             zebra_flush_reg (zh);
1452             return 0;
1453         }
1454         zh->errCode=0;
1455 #if HAVE_SYS_TIMES_H
1456         times (&zh->tms1);
1457 #endif
1458         if (!zh->res)
1459         {
1460             (zh->trans_no)--;
1461             zh->errCode = 109;
1462             return -1;
1463         }
1464         if (!zh->lock_normal || !zh->lock_shadow)
1465         {
1466             (zh->trans_no)--;
1467             zh->errCode = 2;
1468             return -1;
1469         }
1470         zebra_get_state (zh, &val, &seqno);
1471         if (val == 'd')
1472             val = 'o';
1473         
1474         if (!zh->reg)
1475             dirty = 1;
1476         else if (seqno != zh->reg->seqno)
1477         {
1478             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1479                      seqno, zh->reg->seqno);
1480             dirty = 1;
1481         }
1482         else if (zh->reg->last_val != val)
1483         {
1484             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1485                      val, zh->reg->last_val);
1486             dirty = 1;
1487         }
1488         if (!dirty)
1489             return 0;
1490         
1491         if (val == 'c')
1492             zebra_lock_r (zh->lock_shadow);
1493         else
1494             zebra_lock_r (zh->lock_normal);
1495         
1496         if (zh->reg)
1497         {
1498             resultSetInvalidate (zh);
1499             zebra_register_close (zh->service, zh->reg);
1500         }
1501         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1502                                        0, val == 'c' ? 1 : 0,
1503                                        zh->res, zh->path_reg);
1504         if (!zh->reg)
1505         {
1506             zebra_unlock (zh->lock_normal);
1507             zebra_unlock (zh->lock_shadow);
1508             zh->trans_no--;
1509             zh->errCode = 109;
1510             return -1;
1511         }
1512         zh->reg->last_val = val;
1513         zh->reg->seqno = seqno;
1514     }
1515     read_res_for_transaction(zh);
1516     return 0;
1517 }
1518
1519 int zebra_end_trans (ZebraHandle zh)
1520 {
1521     ZebraTransactionStatus dummy;
1522     yaz_log(LOG_API,"zebra_end_trans");
1523     return zebra_end_transaction(zh, &dummy);
1524 }
1525
1526 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1527 {
1528     char val;
1529     int seqno;
1530     const char *rval;
1531
1532     ASSERTZH;
1533     yaz_log(LOG_API,"zebra_end_transaction");
1534
1535     status->processed = 0;
1536     status->inserted  = 0;
1537     status->updated   = 0;
1538     status->deleted   = 0;
1539     status->utime     = 0;
1540     status->stime     = 0;
1541
1542     if (!zh->res || !zh->reg)
1543     {
1544         zh->errCode = 2;
1545         zh->errString = "zebra_end_trans: no open transaction";
1546         return -1;
1547     }
1548     if (zh->trans_no != zh->trans_w_no)
1549     {
1550         zh->trans_no--;
1551         if (zh->trans_no != 0)
1552             return 0;
1553
1554         /* release read lock */
1555
1556         zebra_unlock (zh->lock_normal);
1557         zebra_unlock (zh->lock_shadow);
1558     }
1559     else
1560     {   /* release write lock */
1561         zh->trans_no--;
1562         zh->trans_w_no = 0;
1563         
1564         yaz_log (LOG_LOG, "zebra_end_trans");
1565         rval = res_get (zh->res, "shadow");
1566         
1567         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1568         
1569         zebra_flush_reg (zh);
1570         
1571         resultSetInvalidate (zh);
1572
1573         zebra_register_close (zh->service, zh->reg);
1574         zh->reg = 0;
1575         
1576         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1577                  zh->records_processed, zh->records_inserted,
1578                  zh->records_updated, zh->records_deleted);
1579         
1580         status->processed = zh->records_processed;
1581         status->inserted = zh->records_inserted;
1582         status->updated = zh->records_updated;
1583         status->deleted = zh->records_deleted;
1584         
1585         zebra_get_state (zh, &val, &seqno);
1586         if (val != 'd')
1587         {
1588             BFiles bfs = bfs_create (rval, zh->path_reg);
1589             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1590             bf_commitClean (bfs, rval);
1591             bfs_destroy (bfs);
1592         }
1593         if (!rval)
1594             seqno++;
1595         zebra_set_state (zh, 'o', seqno);
1596         
1597         zebra_unlock (zh->lock_shadow);
1598         zebra_unlock (zh->lock_normal);
1599         
1600     }
1601 #if HAVE_SYS_TIMES_H
1602     times (&zh->tms2);
1603     logf (LOG_LOG, "user/system: %ld/%ld",
1604           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1605           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1606     
1607     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1608     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1609 #endif
1610     return 0;
1611 }
1612
1613 int zebra_repository_update (ZebraHandle zh, const char *path)
1614 {
1615     ASSERTZH;
1616     zh->errCode=0;
1617     logf (LOG_LOG|LOG_API, "updating %s", path);
1618     repositoryUpdate (zh, path);
1619     return zh->errCode;
1620 }
1621
1622 int zebra_repository_delete (ZebraHandle zh, const char *path)
1623 {
1624     ASSERTZH;
1625     zh->errCode=0;
1626     logf (LOG_LOG|LOG_API, "deleting %s", path);
1627     repositoryDelete (zh, path);
1628     return zh->errCode;
1629 }
1630
1631 int zebra_repository_show (ZebraHandle zh, const char *path)
1632 {
1633     ASSERTZH;
1634     yaz_log(LOG_API,"zebra_repository_show");
1635     zh->errCode=0;
1636     repositoryShow (zh, path);
1637     return zh->errCode;
1638 }
1639
1640 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1641 {
1642     int seqno;
1643     char val;
1644     const char *rval;
1645     BFiles bfs;
1646     ASSERTZH;
1647     zh->errCode=0;
1648
1649     if (!zh->res)
1650     {
1651         zh->errCode = 109;
1652         return -1;
1653     }
1654     rval = res_get (zh->res, "shadow");    
1655     if (!rval)
1656     {
1657         logf (LOG_WARN, "Cannot perform commit");
1658         logf (LOG_WARN, "No shadow area defined");
1659         return 0;
1660     }
1661
1662     zebra_lock_w (zh->lock_normal);
1663     zebra_lock_r (zh->lock_shadow);
1664
1665     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1666
1667     zebra_get_state (zh, &val, &seqno);
1668
1669     if (rval && *rval)
1670         bf_cache (bfs, rval);
1671     if (bf_commitExists (bfs))
1672     {
1673         if (clean_only)
1674             zebra_set_state (zh, 'd', seqno);
1675         else
1676         {
1677             zebra_set_state (zh, 'c', seqno);
1678             
1679             logf (LOG_LOG, "commit start");
1680             bf_commitExec (bfs);
1681 #ifndef WIN32
1682             sync ();
1683 #endif
1684         }
1685         logf (LOG_LOG, "commit clean");
1686         bf_commitClean (bfs, rval);
1687         seqno++;
1688         zebra_set_state (zh, 'o', seqno);
1689     }
1690     else
1691     {
1692         logf (LOG_LOG, "nothing to commit");
1693     }
1694     bfs_destroy (bfs);
1695
1696     zebra_unlock (zh->lock_shadow);
1697     zebra_unlock (zh->lock_normal);
1698     return 0;
1699 }
1700
1701 int zebra_clean (ZebraHandle zh)
1702 {
1703     yaz_log(LOG_API,"zebra_clean");
1704     return zebra_commit_ex(zh, 1);
1705 }
1706
1707 int zebra_commit (ZebraHandle zh)
1708 {
1709     yaz_log(LOG_API,"zebra_commit");
1710     return zebra_commit_ex(zh, 0);
1711 }
1712
1713 int zebra_init (ZebraHandle zh)
1714 {
1715     const char *rval;
1716     BFiles bfs = 0;
1717     ASSERTZH;
1718     yaz_log(LOG_API,"zebra_init");
1719     zh->errCode=0;
1720
1721     if (!zh->res)
1722     {
1723         zh->errCode = 109;
1724         return -1;
1725     }
1726     rval = res_get (zh->res, "shadow");
1727
1728     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1729                       zh->path_reg);
1730     if (rval && *rval)
1731         bf_cache (bfs, rval);
1732     
1733     bf_reset (bfs);
1734     bfs_destroy (bfs);
1735     zebra_set_state (zh, 'o', 0);
1736     return 0;
1737 }
1738
1739 int zebra_compact (ZebraHandle zh)
1740 {
1741     BFiles bfs;
1742     ASSERTZH;
1743     yaz_log(LOG_API,"zebra_compact");
1744     zh->errCode=0;
1745     if (!zh->res)
1746     {
1747         zh->errCode = 109;
1748         return -1;
1749     }
1750     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1751     inv_compact (bfs);
1752     bfs_destroy (bfs);
1753     return 0;
1754 }
1755
1756 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1757 {
1758     ASSERTZH;
1759     yaz_log(LOG_API,"zebra_result");
1760     *code = zh->errCode;
1761     *addinfo = zh->errString;
1762     return 0;
1763 }
1764
1765 int zebra_shadow_enable (ZebraHandle zh, int value)
1766 {
1767     ASSERTZH;
1768     yaz_log(LOG_API,"zebra_shadow_enable");
1769     zh->errCode=0;
1770     zh->shadow_enable = value;
1771     return 0;
1772 }
1773
1774 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1775 {
1776     ASSERTZH;
1777     yaz_log(LOG_API,"zebra_record_encoding");
1778     zh->errCode=0;
1779     xfree (zh->record_encoding);
1780
1781     /*
1782      * Fixme!
1783      * Something about charset aliases. Oleg???
1784      */
1785
1786     if (zh->iconv_to_utf8 != 0)
1787         yaz_iconv_close(zh->iconv_to_utf8);
1788     if (zh->iconv_from_utf8 != 0)
1789         yaz_iconv_close(zh->iconv_from_utf8);
1790     
1791     zh->record_encoding = xstrdup (encoding);
1792     
1793     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1794     
1795     zh->iconv_to_utf8 =
1796         yaz_iconv_open ("UTF-8", encoding);
1797     if (zh->iconv_to_utf8 == 0)
1798         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1799     zh->iconv_from_utf8 =
1800         yaz_iconv_open (encoding, "UTF-8");
1801     if (zh->iconv_to_utf8 == 0)
1802         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1803
1804     return 0;
1805 }
1806
1807 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1808 {
1809     ASSERTZH;
1810     yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1811     zh->errCode=0;
1812     res_set(zh->res, name, value);
1813     return 0;
1814 }
1815
1816 const char *zebra_get_resource(ZebraHandle zh,
1817                                const char *name, const char *defaultvalue)
1818 {
1819     const char *v;
1820     ASSERTZH;
1821     v= res_get_def( zh->res, name, (char *)defaultvalue);
1822     zh->errCode=0;
1823     yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1824     return v;
1825 }
1826
1827 /* moved from zebra_api_ext.c by pop */
1828 /* FIXME: Should this really be public??? -Heikki */
1829
1830 int zebra_trans_no (ZebraHandle zh)
1831 {
1832     ASSERTZH;
1833     yaz_log(LOG_API,"zebra_trans_no");
1834     return zh->trans_no;
1835 }
1836
1837 int zebra_get_shadow_enable (ZebraHandle zh)
1838 {
1839     yaz_log(LOG_API,"zebra_get_shadow_enable");
1840     return (zh->shadow_enable);
1841 }
1842
1843 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1844 {
1845     yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1846     zh->shadow_enable = value;
1847     return 0;
1848 }
1849
1850 /* almost the same as zebra_records_retrieve ... but how did it work? 
1851    I mean for multiple records ??? CHECK ??? */
1852 void api_records_retrieve (ZebraHandle zh, ODR stream,
1853                            const char *setname, Z_RecordComposition *comp,
1854                            oid_value input_format, int num_recs,
1855                            ZebraRetrievalRecord *recs)
1856 {
1857     ZebraPosSet poset;
1858     int i, *pos_array;
1859     yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1860
1861     if (!zh->res)
1862     {
1863         zh->errCode = 30;
1864         zh->errString = odr_strdup (stream, setname);
1865         return;
1866     }
1867     
1868     zh->errCode = 0; 
1869
1870     if (zebra_begin_read (zh))
1871         return;
1872
1873     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1874     for (i = 0; i<num_recs; i++)
1875         pos_array[i] = recs[i].position;
1876     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1877     if (!poset)
1878     {
1879         logf (LOG_DEBUG, "zebraPosSetCreate error");
1880         zh->errCode = 30;
1881         zh->errString = nmem_strdup (stream->mem, setname);
1882     }
1883     else
1884     {
1885         for (i = 0; i<num_recs; i++)
1886         {
1887             if (poset[i].term)
1888             {
1889                 recs[i].errCode = 0;
1890                 recs[i].format = VAL_SUTRS;
1891                 recs[i].len = strlen(poset[i].term);
1892                 recs[i].buf = poset[i].term;
1893                 recs[i].base = poset[i].db;
1894                 recs[i].sysno = 0;
1895             
1896             }
1897             else if (poset[i].sysno)
1898             {
1899               /* changed here ??? CHECK ??? */
1900               char *b;
1901                 recs[i].errCode =
1902                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1903                                         stream, input_format, comp,
1904                                         &recs[i].format, 
1905                                         &b,
1906                                         &recs[i].len,
1907                                         &recs[i].base);
1908                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1909                 memcpy(recs[i].buf, b, recs[i].len);
1910                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1911                 recs[i].sysno = poset[i].sysno;
1912                 recs[i].score = poset[i].score;
1913             }
1914             else
1915             {
1916                 char num_str[20];
1917
1918                 sprintf (num_str, "%d", pos_array[i]);  
1919                 zh->errCode = 13;
1920                 zh->errString = odr_strdup (stream, num_str);
1921                 break;
1922             }
1923
1924         }
1925         zebraPosSetDestroy (zh, poset, num_recs);
1926     }
1927     zebra_end_read (zh);
1928     xfree (pos_array);
1929 }
1930
1931
1932 /* ---------------------------------------------------------------------------
1933   Record insert(=update), delete 
1934
1935   If sysno is provided, then it's used to identify the record.
1936   If not, and match_criteria is provided, then sysno is guessed
1937   If not, and a record is provided, then sysno is got from there
1938 NOTE: Now returns 0 at success and updates sysno, which is an int*
1939   20-jun-2003 Heikki
1940 */
1941
1942 int zebra_add_record(ZebraHandle zh,
1943                      const char *buf, int buf_size)
1944 {
1945     SYSNO sysno = 0;
1946     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
1947 }
1948
1949 int zebra_insert_record (ZebraHandle zh, 
1950                          const char *recordType,
1951                          SYSNO *sysno, const char *match, const char *fname,
1952                          const char *buf, int buf_size, int force_update)
1953 {
1954     int res;
1955     yaz_log(LOG_API,"zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
1956
1957     if (buf_size < 1) buf_size = strlen(buf);
1958
1959     if (zebra_begin_trans(zh, 1))
1960         return 1;
1961     res = buffer_extract_record (zh, buf, buf_size, 
1962                                  0, /* delete_flag  */
1963                                  0, /* test_mode */
1964                                  recordType,
1965                                  sysno,   
1966                                  match, fname,
1967                                  0, 
1968                                  0); /* allow_update */
1969     zebra_end_trans(zh); 
1970     return res; 
1971 }
1972
1973 int zebra_update_record (ZebraHandle zh, 
1974                          const char *recordType,
1975                          SYSNO* sysno, const char *match, const char *fname,
1976                          const char *buf, int buf_size,
1977                          int force_update)
1978 {
1979     int res;
1980
1981     yaz_log(LOG_API,"zebra_update_record sysno=" ZINT_FORMAT, *sysno);
1982
1983     if (buf_size < 1) buf_size = strlen(buf);
1984
1985     if (zebra_begin_trans(zh, 1))
1986         return 1;
1987     res = buffer_extract_record (zh, buf, buf_size, 
1988                                  0, /* delete_flag */
1989                                  0, /* test_mode */
1990                                  recordType,
1991                                  sysno,   
1992                                  match, fname,
1993                                  force_update, 
1994                                  1); /* allow_update */
1995     zebra_end_trans(zh); 
1996     return res; 
1997 }
1998
1999 int zebra_delete_record (ZebraHandle zh, 
2000                          const char *recordType,
2001                          SYSNO *sysno, const char *match, const char *fname,
2002                          const char *buf, int buf_size,
2003                          int force_update) 
2004 {
2005     int res;
2006     yaz_log(LOG_API,"zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2007
2008     if (buf_size < 1) buf_size = strlen(buf);
2009
2010     if (zebra_begin_trans(zh, 1))
2011         return 1;
2012     res = buffer_extract_record (zh, buf, buf_size,
2013                                  1, /* delete_flag */
2014                                  0, /* test_mode */
2015                                  recordType,
2016                                  sysno,
2017                                  match,fname,
2018                                  force_update,
2019                                  1); /* allow_update */
2020     zebra_end_trans(zh);
2021     return res;   
2022 }
2023
2024 /* ---------------------------------------------------------------------------
2025   Searching 
2026 */
2027
2028 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2029                       const char *setname, int *numhits)
2030 {
2031     int hits = 0;
2032     int res=-1;
2033     Z_RPNQuery *query;
2034     ODR odr = odr_createmem(ODR_ENCODE);
2035
2036     yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2037     
2038     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2039     
2040     if (!query)
2041         yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2042     else
2043         res=zebra_search_RPN (zh, odr, query, setname, &hits);
2044     
2045     odr_destroy(odr);
2046
2047     yaz_log(LOG_API,"Hits: %d",hits);
2048
2049     if (numhits)
2050         *numhits=hits;
2051
2052     return res;
2053 }
2054
2055 /* ---------------------------------------------------------------------------
2056   Sort - a simplified interface, with optional read locks.
2057   FIXME - This is a horrible name, will conflict with half the applications
2058 */
2059 int zebra_sort_by_specstr (ZebraHandle zh, 
2060                            ODR stream,
2061                            const char *sort_spec,
2062                            const char *output_setname,
2063                            const char **input_setnames) 
2064 {
2065     int num_input_setnames = 0;
2066     int sort_status = 0;
2067     Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2068     yaz_log(LOG_API,"sort (FIXME) ");
2069     if (!sort_sequence)
2070     {
2071         logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2072         zh->errCode = 207;
2073         return -1;
2074     }
2075     
2076     /* we can do this, since the perl typemap code for char** will 
2077        put a NULL at the end of list */
2078     while (input_setnames[num_input_setnames]) num_input_setnames++;
2079
2080     if (zebra_begin_read (zh))
2081         return -1;
2082     
2083     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2084                    output_setname, sort_sequence, &sort_status);
2085     
2086     zebra_end_read(zh);
2087     return sort_status;
2088 }
2089