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