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