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