Fixed a bug in zebrash and a warning in zebraapi
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.112 2003-07-07 14:56:04 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 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, ret = 0;
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         ret = -1;
823     }
824     else
825     {
826         for (i = 0; i<num_recs; i++)
827         {
828             if (poset[i].term)
829             {
830                 recs[i].errCode = 0;
831                 recs[i].format = VAL_SUTRS;
832                 recs[i].len = strlen(poset[i].term);
833                 recs[i].buf = poset[i].term;
834                 recs[i].base = poset[i].db;
835             }
836             else if (poset[i].sysno)
837             {
838                 recs[i].errCode =
839                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
840                                         stream, input_format, comp,
841                                         &recs[i].format, &recs[i].buf,
842                                         &recs[i].len,
843                                         &recs[i].base);
844                 recs[i].errString = NULL;
845             }
846             else
847             {
848                 char num_str[20];
849
850                 sprintf (num_str, "%d", pos_array[i]);  
851                 zh->errCode = 13;
852                 zh->errString = odr_strdup (stream, num_str);
853                 ret = -1;
854                 break;
855             }
856         }
857         zebraPosSetDestroy (zh, poset, num_recs);
858     }
859     zebra_end_read (zh);
860     xfree (pos_array);
861     return ret;
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     zebra_begin_trans(zh,1);
1068
1069     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1070     if (rinfo)
1071     {
1072         if (action == 1)  /* fail if insert */
1073         {
1074              zebra_end_trans(zh);
1075              return -1;
1076         }
1077
1078         memcpy (&sysno, rinfo+1, sizeof(sysno));
1079     }
1080     else
1081     {
1082         if (action == 2 || action == 3) /* fail if delete or update */
1083         {
1084             zebra_end_trans(zh);
1085             return -1;
1086         }
1087     }
1088     extract_rec_in_mem (zh, "grs.sgml", rec_buf, rec_len, database,
1089                         action == 3 ? 1 : 0 /* delete flag */,
1090                         0, &sysno, 1, 1, 0);
1091     if (action == 1)
1092     {
1093         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1094     }
1095     else if (action == 3)
1096     {
1097         dict_delete (zh->reg->matchDict, recid_z);
1098     }
1099     zebra_end_trans(zh);
1100     return 0;
1101 }
1102
1103 int delete_w_handle(const char *info, void *handle)
1104 {
1105     ZebraHandle zh = (ZebraHandle) handle;
1106     ISAMC_P pos;
1107
1108     if (*info == sizeof(pos))
1109     {
1110         memcpy (&pos, info+1, sizeof(pos));
1111         isamb_unlink(zh->reg->isamb, pos);
1112     }
1113     return 0;
1114 }
1115
1116 static int delete_SU_handle(void *handle, int ord)
1117 {
1118     ZebraHandle zh = (ZebraHandle) handle;
1119     char ord_buf[20];
1120     int ord_len;
1121
1122     ord_len = key_SU_encode (ord, ord_buf);
1123     ord_buf[ord_len] = '\0';
1124
1125     assert (zh->reg->isamb);
1126     dict_delete_subtree(zh->reg->dict, ord_buf,
1127                         zh, delete_w_handle);
1128     return 0;
1129 }
1130
1131 int zebra_drop_database  (ZebraHandle zh, const char *database)
1132 {
1133     ASSERTZH;
1134     yaz_log(LOG_API,"zebra_drop_database");
1135     zh->errCode = 0;
1136
1137     if (zebra_select_database (zh, database))
1138         return -1;
1139     if (zebra_begin_trans (zh, 1))
1140         return -1;
1141     if (zh->reg->isamb)
1142     {
1143         zebraExplain_curDatabase (zh->reg->zei, database);
1144         
1145         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1146         zebraExplain_removeDatabase(zh->reg->zei, zh);
1147     }
1148     zebra_end_trans (zh);
1149     return 0;
1150 }
1151
1152 int zebra_create_database (ZebraHandle zh, const char *database)
1153 {
1154     ASSERTZH;
1155     yaz_log(LOG_API,"zebra_create_database");
1156     zh->errCode=0;
1157
1158     if (zebra_select_database (zh, database))
1159         return -1;
1160     if (zebra_begin_trans (zh, 1))
1161         return -1;
1162
1163     /* announce database */
1164     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1165                                   /* explainDatabase */))
1166     {
1167         zebra_end_trans (zh);
1168         zh->errCode = 224;
1169         zh->errString = "database already exist";
1170         return -1;
1171     }
1172     zebra_end_trans (zh);
1173     return 0;
1174 }
1175
1176 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1177                        const char *input_str, int input_len,
1178                        char *output_str, int output_len)
1179 {
1180     WRBUF wrbuf;
1181     ASSERTZH;
1182     yaz_log(LOG_API,"zebra_string_norm ");
1183     zh->errCode=0;
1184     if (!zh->reg->zebra_maps)
1185         return -1;
1186     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1187                           input_str, input_len);
1188     if (!wrbuf)
1189         return -2;
1190     if (wrbuf_len(wrbuf) >= output_len)
1191         return -3;
1192     if (wrbuf_len(wrbuf))
1193         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1194     output_str[wrbuf_len(wrbuf)] = '\0';
1195     return wrbuf_len(wrbuf);
1196 }
1197
1198
1199 int zebra_set_state (ZebraHandle zh, int val, int seqno)
1200 {
1201     char state_fname[256];
1202     char *fname;
1203     long p = getpid();
1204     FILE *f;
1205     ASSERTZH;
1206     yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1207     zh->errCode=0;
1208
1209     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1210     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1211     f = fopen (fname, "w");
1212
1213     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1214     fprintf (f, "%c %d %ld\n", val, seqno, p);
1215     fclose (f);
1216     xfree (fname);
1217     return 0;
1218 }
1219
1220 int zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1221 {
1222     char state_fname[256];
1223     char *fname;
1224     FILE *f;
1225
1226     ASSERTZH;
1227     yaz_log(LOG_API,"zebra_get_state ");
1228     zh->errCode=0;
1229     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1230     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1231     f = fopen (fname, "r");
1232     *val = 'o';
1233     *seqno = 0;
1234
1235     if (f)
1236     {
1237         fscanf (f, "%c %d", val, seqno);
1238         fclose (f);
1239     }
1240     xfree (fname);
1241     return 0;
1242 }
1243
1244 int zebra_begin_read (ZebraHandle zh)
1245 {
1246     return zebra_begin_trans(zh, 0);
1247 }
1248
1249 int zebra_end_read (ZebraHandle zh)
1250 {
1251     return zebra_end_trans(zh);
1252 }
1253
1254 int zebra_begin_trans (ZebraHandle zh, int rw)
1255 {
1256     yaz_log(LOG_LOG, "zebra_begin_trans rw=%d trans=%d", rw, zh->trans_no);
1257     if (!zh->res)
1258     {
1259         zh->errCode = 2;
1260         zh->errString = "zebra_begin_trans: no database selected";
1261         return -1;
1262     }
1263     ASSERTZHRES;
1264     yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1265     assert (zh->res);
1266     if (rw)
1267     {
1268         int pass;
1269         int seqno = 0;
1270         char val = '?';
1271         const char *rval = 0;
1272         
1273         (zh->trans_no++);
1274         if (zh->trans_w_no)
1275             return 0;
1276         if (zh->trans_no != 1)
1277         {
1278             zh->errCode = 2;
1279             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1280             return -1;
1281         }
1282         if (zh->reg)
1283         {
1284             resultSetInvalidate (zh);
1285             zebra_register_close (zh->service, zh->reg);
1286         }
1287         zh->trans_w_no = zh->trans_no;
1288
1289         zh->errCode=0;
1290         
1291         zh->records_inserted = 0;
1292         zh->records_updated = 0;
1293         zh->records_deleted = 0;
1294         zh->records_processed = 0;
1295         
1296 #if HAVE_SYS_TIMES_H
1297         times (&zh->tms1);
1298 #endif
1299         /* lock */
1300         if (zh->shadow_enable)
1301             rval = res_get (zh->res, "shadow");
1302         
1303         for (pass = 0; pass < 2; pass++)
1304         {
1305             if (rval)
1306             {
1307                 zebra_lock_r (zh->lock_normal);
1308                 zebra_lock_w (zh->lock_shadow);
1309             }
1310             else
1311             {
1312                 zebra_lock_w (zh->lock_normal);
1313                 zebra_lock_w (zh->lock_shadow);
1314             }
1315             
1316             zebra_get_state (zh, &val, &seqno);
1317             if (val == 'c')
1318             {
1319                 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1320                 zebra_unlock (zh->lock_shadow);
1321                 zebra_unlock (zh->lock_normal);
1322                 zebra_commit (zh);
1323                 continue;
1324             }
1325             else if (val == 'd')
1326             {
1327                 if (rval)
1328                 {
1329                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1330                                              zh->path_reg);
1331                     yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1332                     bf_commitClean (bfs, rval);
1333                     bfs_destroy (bfs);
1334             }
1335                 else
1336                 {
1337                     yaz_log (LOG_WARN, "your previous transaction didn't finish");
1338                 }
1339             }
1340             break;
1341         }
1342         if (pass == 2)
1343         {
1344             yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1345             abort();
1346             return -1;
1347         }
1348         zebra_set_state (zh, 'd', seqno);
1349         
1350         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1351                                        1, rval ? 1 : 0, zh->res,
1352                                        zh->path_reg);
1353         if (zh->reg)
1354             zh->reg->seqno = seqno;
1355         else
1356         {
1357             zebra_set_state (zh, 'o', seqno);
1358             
1359             zebra_unlock (zh->lock_shadow);
1360             zebra_unlock (zh->lock_normal);
1361
1362             zh->trans_no--;
1363             zh->trans_w_no = 0;
1364
1365             zh->errCode = 2;
1366             zh->errString = "zebra_begin_trans: cannot open register";
1367             yaz_log(LOG_FATAL, zh->errString);
1368             return -1;
1369         }
1370     }
1371     else
1372     {
1373         int dirty = 0;
1374         char val;
1375         int seqno;
1376         
1377         (zh->trans_no)++;
1378         
1379         if (zh->trans_no != 1)
1380         {
1381             zebra_flush_reg (zh);
1382             return 0;
1383         }
1384         zh->errCode=0;
1385 #if HAVE_SYS_TIMES_H
1386         times (&zh->tms1);
1387 #endif
1388         if (!zh->res)
1389         {
1390             (zh->trans_no)--;
1391             zh->errCode = 109;
1392             return -1;
1393         }
1394         if (!zh->lock_normal || !zh->lock_shadow)
1395         {
1396             (zh->trans_no)--;
1397             zh->errCode = 2;
1398             return -1;
1399         }
1400         zebra_get_state (zh, &val, &seqno);
1401         if (val == 'd')
1402             val = 'o';
1403         
1404         if (!zh->reg)
1405             dirty = 1;
1406         else if (seqno != zh->reg->seqno)
1407         {
1408             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1409                      seqno, zh->reg->seqno);
1410             dirty = 1;
1411         }
1412         else if (zh->reg->last_val != val)
1413         {
1414             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1415                      val, zh->reg->last_val);
1416             dirty = 1;
1417         }
1418         if (!dirty)
1419             return 0;
1420         
1421         if (val == 'c')
1422             zebra_lock_r (zh->lock_shadow);
1423         else
1424             zebra_lock_r (zh->lock_normal);
1425         
1426         if (zh->reg)
1427             zebra_register_close (zh->service, zh->reg);
1428         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1429                                        0, val == 'c' ? 1 : 0,
1430                                        zh->res, zh->path_reg);
1431         if (!zh->reg)
1432         {
1433             zebra_unlock (zh->lock_normal);
1434             zebra_unlock (zh->lock_shadow);
1435             zh->trans_no--;
1436             zh->errCode = 109;
1437             return -1;
1438         }
1439         zh->reg->last_val = val;
1440         zh->reg->seqno = seqno;
1441     }
1442     return 0;
1443 }
1444
1445 int zebra_end_trans (ZebraHandle zh)
1446 {
1447     ZebraTransactionStatus dummy;
1448     yaz_log(LOG_API,"zebra_end_trans");
1449     return zebra_end_transaction(zh, &dummy);
1450 }
1451
1452 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1453 {
1454     char val;
1455     int seqno;
1456     const char *rval;
1457
1458     ASSERTZH;
1459     yaz_log(LOG_API,"zebra_end_transaction");
1460
1461     status->processed = 0;
1462     status->inserted  = 0;
1463     status->updated   = 0;
1464     status->deleted   = 0;
1465     status->utime     = 0;
1466     status->stime     = 0;
1467
1468     if (!zh->res || !zh->reg)
1469     {
1470         zh->errCode = 2;
1471         zh->errString = "zebra_end_trans: no open transaction";
1472         return -1;
1473     }
1474     if (zh->trans_no != zh->trans_w_no)
1475     {
1476         zh->trans_no--;
1477         if (zh->trans_no != 0)
1478             return 0;
1479
1480         /* release read lock */
1481
1482         zebra_unlock (zh->lock_normal);
1483         zebra_unlock (zh->lock_shadow);
1484     }
1485     else
1486     {   /* release write lock */
1487         zh->trans_no--;
1488         zh->trans_w_no = 0;
1489         
1490         yaz_log (LOG_LOG, "zebra_end_trans");
1491         rval = res_get (zh->res, "shadow");
1492         
1493         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1494         
1495         zebra_flush_reg (zh);
1496         
1497         resultSetInvalidate (zh);
1498
1499         zebra_register_close (zh->service, zh->reg);
1500         zh->reg = 0;
1501         
1502         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1503                  zh->records_processed, zh->records_inserted,
1504                  zh->records_updated, zh->records_deleted);
1505         
1506         status->processed = zh->records_processed;
1507         status->inserted = zh->records_inserted;
1508         status->updated = zh->records_updated;
1509         status->deleted = zh->records_deleted;
1510         
1511         zebra_get_state (zh, &val, &seqno);
1512         if (val != 'd')
1513         {
1514             BFiles bfs = bfs_create (rval, zh->path_reg);
1515             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1516             bf_commitClean (bfs, rval);
1517             bfs_destroy (bfs);
1518         }
1519         if (!rval)
1520             seqno++;
1521         zebra_set_state (zh, 'o', seqno);
1522         
1523         zebra_unlock (zh->lock_shadow);
1524         zebra_unlock (zh->lock_normal);
1525         
1526     }
1527 #if HAVE_SYS_TIMES_H
1528     times (&zh->tms2);
1529     logf (LOG_LOG, "user/system: %ld/%ld",
1530           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1531           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1532     
1533     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1534     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1535 #endif
1536     return 0;
1537 }
1538
1539 int zebra_repository_update (ZebraHandle zh)
1540 {
1541     ASSERTZH;
1542     zh->errCode=0;
1543     logf (LOG_LOG|LOG_API, "updating %s", zh->rGroup.path);
1544     repositoryUpdate (zh);    
1545     return zh->errCode;
1546 }
1547
1548 int zebra_repository_delete (ZebraHandle zh)
1549 {
1550     ASSERTZH;
1551     zh->errCode=0;
1552     logf (LOG_LOG|LOG_API, "deleting %s", zh->rGroup.path);
1553     repositoryDelete (zh);
1554     return zh->errCode;
1555 }
1556
1557 int zebra_repository_show (ZebraHandle zh)
1558 {
1559     ASSERTZH;
1560     yaz_log(LOG_API,"zebra_repository_show");
1561     zh->errCode=0;
1562     repositoryShow (zh);
1563     return zh->errCode;
1564 }
1565
1566 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1567 {
1568     int seqno;
1569     char val;
1570     const char *rval;
1571     BFiles bfs;
1572     ASSERTZH;
1573     zh->errCode=0;
1574
1575     if (!zh->res)
1576     {
1577         zh->errCode = 109;
1578         return -1;
1579     }
1580     rval = res_get (zh->res, "shadow");    
1581     if (!rval)
1582     {
1583         logf (LOG_WARN, "Cannot perform commit");
1584         logf (LOG_WARN, "No shadow area defined");
1585         return 0;
1586     }
1587
1588     zebra_lock_w (zh->lock_normal);
1589     zebra_lock_r (zh->lock_shadow);
1590
1591     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1592
1593     zebra_get_state (zh, &val, &seqno);
1594
1595     if (rval && *rval)
1596         bf_cache (bfs, rval);
1597     if (bf_commitExists (bfs))
1598     {
1599         if (clean_only)
1600             zebra_set_state (zh, 'd', seqno);
1601         else
1602         {
1603             zebra_set_state (zh, 'c', seqno);
1604             
1605             logf (LOG_LOG, "commit start");
1606             bf_commitExec (bfs);
1607 #ifndef WIN32
1608             sync ();
1609 #endif
1610         }
1611         logf (LOG_LOG, "commit clean");
1612         bf_commitClean (bfs, rval);
1613         seqno++;
1614         zebra_set_state (zh, 'o', seqno);
1615     }
1616     else
1617     {
1618         logf (LOG_LOG, "nothing to commit");
1619     }
1620     bfs_destroy (bfs);
1621
1622     zebra_unlock (zh->lock_shadow);
1623     zebra_unlock (zh->lock_normal);
1624     return 0;
1625 }
1626
1627 int zebra_clean (ZebraHandle zh)
1628 {
1629     yaz_log(LOG_API,"zebra_clean");
1630     return zebra_commit_ex(zh, 1);
1631 }
1632
1633 int zebra_commit (ZebraHandle zh)
1634 {
1635     yaz_log(LOG_API,"zebra_commit");
1636     return zebra_commit_ex(zh, 0);
1637 }
1638
1639 int zebra_init (ZebraHandle zh)
1640 {
1641     const char *rval;
1642     BFiles bfs = 0;
1643     ASSERTZH;
1644     yaz_log(LOG_API,"zebra_init");
1645     zh->errCode=0;
1646
1647     if (!zh->res)
1648     {
1649         zh->errCode = 109;
1650         return -1;
1651     }
1652     rval = res_get (zh->res, "shadow");
1653
1654     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1655                       zh->path_reg);
1656     if (rval && *rval)
1657         bf_cache (bfs, rval);
1658     
1659     bf_reset (bfs);
1660     bfs_destroy (bfs);
1661     zebra_set_state (zh, 'o', 0);
1662     return 0;
1663 }
1664
1665 int zebra_compact (ZebraHandle zh)
1666 {
1667     BFiles bfs;
1668     ASSERTZH;
1669     yaz_log(LOG_API,"zebra_compact");
1670     zh->errCode=0;
1671     if (!zh->res)
1672     {
1673         zh->errCode = 109;
1674         return -1;
1675     }
1676     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1677     inv_compact (bfs);
1678     bfs_destroy (bfs);
1679     return 0;
1680 }
1681
1682 int zebra_record_insert (ZebraHandle zh, const char *buf, int len, int *sysno)
1683 {
1684     int sysn=0;
1685     ASSERTZH;
1686     yaz_log(LOG_API,"zebra_record_insert");
1687     if (sysno)
1688         *sysno=0;
1689     zh->errCode=0;
1690     if (zebra_begin_trans (zh, 1))
1691         return -1;
1692     extract_rec_in_mem (zh, "grs.sgml",
1693                         buf, len,
1694                         "Default",  /* database */
1695                         0 /* delete_flag */,
1696                         0 /* test_mode */,
1697                         &sysn /* sysno */,
1698                         1 /* store_keys */,
1699                         1 /* store_data */,
1700                         0 /* match criteria */);
1701     if (zebra_end_trans (zh))
1702         return -1;
1703     if (sysno)
1704         *sysno=sysn;
1705     return 0;
1706 }
1707
1708 int zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1709 {
1710     ASSERTZH;
1711     yaz_log(LOG_API,"zebra_set_group");
1712     zh->errCode=0;
1713     memcpy (&zh->rGroup, rg, sizeof(*rg));
1714     return 0;
1715 }
1716
1717 int zebra_result (ZebraHandle zh, int *code, char **addinfo)
1718 {
1719     ASSERTZH;
1720     yaz_log(LOG_API,"zebra_result");
1721     *code = zh->errCode;
1722     *addinfo = zh->errString;
1723     return 0;
1724 }
1725
1726 int zebra_shadow_enable (ZebraHandle zh, int value)
1727 {
1728     ASSERTZH;
1729     yaz_log(LOG_API,"zebra_shadow_enable");
1730     zh->errCode=0;
1731     zh->shadow_enable = value;
1732     return 0;
1733 }
1734
1735 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1736 {
1737     ASSERTZH;
1738     yaz_log(LOG_API,"zebra_record_encoding");
1739     zh->errCode=0;
1740     xfree (zh->record_encoding);
1741
1742     /*
1743      * Fixme!
1744      * Something about charset aliases. Oleg???
1745      */
1746
1747     if (zh->iconv_to_utf8 != 0)
1748         yaz_iconv_close(zh->iconv_to_utf8);
1749     if (zh->iconv_from_utf8 != 0)
1750         yaz_iconv_close(zh->iconv_from_utf8);
1751     
1752     zh->record_encoding = xstrdup (encoding);
1753     
1754     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1755     
1756     zh->iconv_to_utf8 =
1757         yaz_iconv_open ("UTF-8", encoding);
1758     if (zh->iconv_to_utf8 == 0)
1759         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1760     zh->iconv_from_utf8 =
1761         yaz_iconv_open (encoding, "UTF-8");
1762     if (zh->iconv_to_utf8 == 0)
1763         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1764
1765     return 0;
1766 }
1767
1768 int zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1769 {
1770     ASSERTZH;
1771     yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1772     zh->errCode=0;
1773     res_put(zh->res, name, value);
1774     return 0;
1775 }
1776
1777 const char *zebra_get_resource(ZebraHandle zh,
1778                                const char *name, const char *defaultvalue)
1779 {
1780     const char *v;
1781     ASSERTZH;
1782     v= res_get_def( zh->res, name, (char *)defaultvalue);
1783     zh->errCode=0;
1784     yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1785     return v;
1786 }
1787
1788 /* moved from zebra_api_ext.c by pop */
1789 /* FIXME: Should this really be public??? -Heikki */
1790
1791 int zebra_trans_no (ZebraHandle zh)
1792 {
1793     ASSERTZH;
1794     yaz_log(LOG_API,"zebra_trans_no");
1795     return zh->trans_no;
1796 }
1797
1798 int zebra_get_shadow_enable (ZebraHandle zh)
1799 {
1800     yaz_log(LOG_API,"zebra_get_shadow_enable");
1801     return (zh->shadow_enable);
1802 }
1803
1804 int zebra_set_shadow_enable (ZebraHandle zh, int value)
1805 {
1806     yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1807     zh->shadow_enable = value;
1808     return 0;
1809 }
1810
1811 int init_recordGroup (struct recordGroup *rg)
1812 {
1813     assert(rg);
1814     yaz_log(LOG_API,"init_recordGroup");
1815     rg->groupName = NULL;
1816     rg->databaseName = NULL;
1817     rg->path = NULL;
1818     rg->recordId = NULL;
1819     rg->recordType = NULL;
1820     rg->flagStoreData = -1;
1821     rg->flagStoreKeys = -1; 
1822     rg->flagRw = 1;
1823     rg->databaseNamePath = 0;
1824     rg->explainDatabase = 0; 
1825     rg->fileVerboseLimit = 100000; 
1826     rg->followLinks = -1;
1827     return 0;
1828
1829
1830
1831 /* This is from extract.c... it seems useful, when extract_rec_in mem is 
1832    called... and in general... Should be moved to somewhere else */
1833 void res_get_recordGroup (ZebraHandle zh,
1834                           struct recordGroup *rGroup,
1835                           const char *ext)
1836 {
1837     char gprefix[128];
1838     char ext_res[128]; 
1839     
1840     yaz_log(LOG_API,"res_get_recordGroup e=%s",ext);
1841     if (!rGroup->groupName || !*rGroup->groupName)
1842         *gprefix = '\0';
1843     else 
1844         sprintf (gprefix, "%s.", rGroup->groupName);
1845     
1846     /* determine file type - depending on extension */
1847     if (!rGroup->recordType) {
1848         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1849         if (!(rGroup->recordType = res_get (zh->res, ext_res))) {
1850             sprintf (ext_res, "%srecordType", gprefix);
1851             rGroup->recordType = res_get (zh->res, ext_res);
1852         }
1853     }
1854     /* determine match criteria */
1855     if (!rGroup->recordId) { 
1856         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1857         if (!(rGroup->recordId = res_get (zh->res, ext_res))) {
1858             sprintf (ext_res, "%srecordId", gprefix);
1859             rGroup->recordId = res_get (zh->res, ext_res);
1860         }
1861     } 
1862     
1863     /* determine database name */
1864     if (!rGroup->databaseName) {
1865         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1866         if (!(rGroup->databaseName = res_get (zh->res, ext_res))) { 
1867             sprintf (ext_res, "%sdatabase", gprefix);
1868             rGroup->databaseName = res_get (zh->res, ext_res);
1869         }
1870     }
1871     if (!rGroup->databaseName)
1872         rGroup->databaseName = "Default";
1873     
1874     /* determine if explain database */
1875     sprintf (ext_res, "%sexplainDatabase", gprefix);
1876     rGroup->explainDatabase =
1877         atoi (res_get_def (zh->res, ext_res, "0"));
1878     
1879     /* storeData */
1880     if (rGroup->flagStoreData == -1)
1881     {
1882         const char *sval;
1883         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1884         if (!(sval = res_get (zh->res, ext_res)))
1885         {
1886             sprintf (ext_res, "%sstoreData", gprefix);
1887             sval = res_get (zh->res, ext_res);
1888         }
1889         if (sval)
1890             rGroup->flagStoreData = atoi (sval);
1891     }
1892     if (rGroup->flagStoreData == -1) 
1893         rGroup->flagStoreData = 0;
1894     
1895     /* storeKeys */
1896     if (rGroup->flagStoreKeys == -1)
1897     {
1898         const char *sval;
1899         
1900         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1901         sval = res_get (zh->res, ext_res);
1902         if (!sval)
1903         {
1904             sprintf (ext_res, "%sstoreKeys", gprefix);
1905             sval = res_get (zh->res, ext_res);
1906         }
1907         if (!sval)
1908             sval = res_get (zh->res, "storeKeys");
1909         if (sval)
1910             rGroup->flagStoreKeys = atoi (sval);
1911     }
1912     if (rGroup->flagStoreKeys == -1)
1913         rGroup->flagStoreKeys = 0;
1914
1915
1916
1917 /* almost the same as zebra_records_retrieve ... but how did it work? 
1918    I mean for multiple records ??? CHECK ??? */
1919 void api_records_retrieve (ZebraHandle zh, ODR stream,
1920                            const char *setname, Z_RecordComposition *comp,
1921                            oid_value input_format, int num_recs,
1922                            ZebraRetrievalRecord *recs)
1923 {
1924     ZebraPosSet poset;
1925     int i, *pos_array;
1926     yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1927
1928     if (!zh->res)
1929     {
1930         zh->errCode = 30;
1931         zh->errString = odr_strdup (stream, setname);
1932         return;
1933     }
1934     
1935     zh->errCode = 0; 
1936
1937     if (zebra_begin_read (zh))
1938         return;
1939
1940     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1941     for (i = 0; i<num_recs; i++)
1942         pos_array[i] = recs[i].position;
1943     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1944     if (!poset)
1945     {
1946         logf (LOG_DEBUG, "zebraPosSetCreate error");
1947         zh->errCode = 30;
1948         zh->errString = nmem_strdup (stream->mem, setname);
1949     }
1950     else
1951     {
1952         for (i = 0; i<num_recs; i++)
1953         {
1954             if (poset[i].term)
1955             {
1956                 recs[i].errCode = 0;
1957                 recs[i].format = VAL_SUTRS;
1958                 recs[i].len = strlen(poset[i].term);
1959                 recs[i].buf = poset[i].term;
1960                 recs[i].base = poset[i].db;
1961                 recs[i].sysno = 0;
1962             
1963             }
1964             else if (poset[i].sysno)
1965             {
1966               /* changed here ??? CHECK ??? */
1967               char *b;
1968                 recs[i].errCode =
1969                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1970                                         stream, input_format, comp,
1971                                         &recs[i].format, 
1972                                         &b,
1973                                         &recs[i].len,
1974                                         &recs[i].base);
1975                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1976                 memcpy(recs[i].buf, b, recs[i].len);
1977                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1978                 recs[i].sysno = poset[i].sysno;
1979                 recs[i].score = poset[i].score;
1980             }
1981             else
1982             {
1983                 char num_str[20];
1984
1985                 sprintf (num_str, "%d", pos_array[i]);  
1986                 zh->errCode = 13;
1987                 zh->errString = odr_strdup (stream, num_str);
1988                 break;
1989             }
1990
1991         }
1992         zebraPosSetDestroy (zh, poset, num_recs);
1993     }
1994     zebra_end_read (zh);
1995     xfree (pos_array);
1996 }
1997
1998
1999 /* ---------------------------------------------------------------------------
2000   Record insert(=update), delete 
2001
2002   If sysno is provided, then it's used to identify the reocord.
2003   If not, and match_criteria is provided, then sysno is guessed
2004   If not, and a record is provided, then sysno is got from there
2005 NOTE: Now returns 0 at success and updates sysno, which is an int*
2006   20-jun-2003 Heikki
2007 */
2008
2009 int zebra_insert_record (ZebraHandle zh, 
2010                          struct recordGroup *rGroup,
2011                          const char *recordType,
2012                          int *sysno, const char *match, const char *fname,
2013                          const char *buf, int buf_size,
2014                          int force_update) /* This one is ignored */
2015  
2016 {
2017     int res;
2018     yaz_log(LOG_API,"zebra_insert_record sysno=%d", *sysno);
2019
2020     if (buf_size < 1) buf_size = strlen(buf);
2021
2022     zebra_begin_trans(zh, 1);
2023     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
2024                              0, /* delete_flag  */
2025                              0, /* test_mode */
2026                              recordType,
2027                              sysno,   
2028                              match, fname,
2029                              force_update, 
2030                              0); /* allow_update */
2031     zebra_end_trans(zh); 
2032     if (res < 0) return (res);
2033     return res; 
2034 }
2035
2036 int zebra_update_record (ZebraHandle zh, 
2037                          struct recordGroup *rGroup,
2038                          const char *recordType,
2039                          int* sysno, const char *match, const char *fname,
2040                          const char *buf, int buf_size,
2041                          int force_update)
2042 {
2043     int res;
2044
2045     yaz_log(LOG_API,"zebra_update_record sysno=%d", *sysno);
2046
2047     if (buf_size < 1) buf_size = strlen(buf);
2048
2049     zebra_begin_trans(zh, 1);
2050     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
2051                              0, /* delete_flag */
2052                              0, /* test_mode */
2053                              recordType,
2054                              sysno,   
2055                              match, fname,
2056                              force_update, 
2057                              1); /* allow_update */
2058     zebra_end_trans(zh); 
2059     return res; 
2060 }
2061
2062 int zebra_delete_record (ZebraHandle zh, 
2063                          struct recordGroup *rGroup, 
2064                          const char *recordType,
2065                          int *sysno, const char *match, const char *fname,
2066                          const char *buf, int buf_size,
2067                          int force_update) 
2068 {
2069     int res;
2070     yaz_log(LOG_API,"zebra_delete_record sysno=%d", *sysno);
2071
2072     if (buf_size < 1) buf_size = strlen(buf);
2073
2074     zebra_begin_trans(zh, 1);
2075     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
2076                              1, /* delete_flag */
2077                              0, /* test_mode */
2078                              recordType,
2079                              sysno,
2080                              match,fname,
2081                              force_update,
2082                              1); /* allow_update */
2083     zebra_end_trans(zh);
2084     return res;   
2085 }
2086
2087 /* ---------------------------------------------------------------------------
2088   Searching 
2089 */
2090
2091 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
2092                       const char *setname, int *numhits)
2093 {
2094     int hits = 0;
2095     int res=-1;
2096     Z_RPNQuery *query;
2097     ODR odr = odr_createmem(ODR_ENCODE);
2098
2099     yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
2100     
2101     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2102     
2103     if (!query)
2104         yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
2105     else
2106         res=zebra_search_RPN (zh, odr, query, setname, &hits);
2107     
2108     odr_destroy(odr);
2109
2110     yaz_log(LOG_API,"Hits: %d",hits);
2111
2112     if (numhits)
2113         *numhits=hits;
2114
2115     return res;
2116 }
2117
2118 /* ---------------------------------------------------------------------------
2119   Sort - a simplified interface, with optional read locks.
2120   FIXME - This is a horrible name, will conflict with half the applications
2121 */
2122 int zebra_sort_by_specstr (ZebraHandle zh, 
2123                            ODR stream,
2124                            const char *sort_spec,
2125                            const char *output_setname,
2126                            const char **input_setnames) 
2127 {
2128     int num_input_setnames = 0;
2129     int sort_status = 0;
2130     Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2131     yaz_log(LOG_API,"sort (FIXME) ");
2132     if (!sort_sequence)
2133     {
2134         logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2135         zh->errCode = 207;
2136         return -1;
2137     }
2138     
2139     /* we can do this, since the perl typemap code for char** will 
2140        put a NULL at the end of list */
2141     while (input_setnames[num_input_setnames]) num_input_setnames++;
2142
2143     if (zebra_begin_read (zh))
2144         return -1;
2145     
2146     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2147                    output_setname, sort_sequence, &sort_status);
2148     
2149     zebra_end_read(zh);
2150     return sort_status;
2151 }