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