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