]> andersk Git - moira.git/blob - server/qrtn.dc
use com_err to print error messages.
[moira.git] / server / qrtn.dc
1 /*
2  *      $Source$
3  *      $Author$
4  *      $Header$
5  *
6  *      Copyright (C) 1987, 1988 by the Massachusetts Institute of Technology
7  *      For copying and distribution information, please see the file
8  *      <mit-copyright.h>.
9  * 
10  */
11
12 #ifndef lint
13 static char *rcsid_qrtn_dc = "$Header$";
14 #endif lint
15
16 #include <mit-copyright.h>
17 #include <string.h>
18 #include "mr_server.h"
19 #include "query.h"
20 EXEC SQL INCLUDE sqlca;  /* SQL Communications Area */
21 EXEC SQL INCLUDE sqlda;  /* SQL Descriptor Area */
22 #include "qrtn.h"
23
24 SQLDA *mr_sqlda;
25 EXEC SQL BEGIN DECLARE SECTION; 
26 int mr_sig_length;
27 int idummy;                            
28 char cdummy[MR_CDUMMY_LEN];            
29 char stmt_buf[MR_STMTBUF_LEN];
30 EXEC SQL END DECLARE SECTION; 
31
32 char *Argv[QMAXARGS];
33 extern char *table_name[];
34 extern char *sqlbuffer[QMAXARGS];
35
36 int dbms_errno = 0;
37 int mr_errcode = 0;
38 EXEC SQL BEGIN DECLARE SECTION; 
39 int query_timeout = 30;
40 char *database = "moira";
41 EXEC SQL END DECLARE SECTION;
42 extern char *whoami;
43 extern FILE *journal;
44
45 int mr_verify_query(client *cl, struct query *q, int argc, char *argv_ro[]);
46 int do_retrieve(struct query *q, char *pqual, char *psort,
47                 int (*action)(), char *actarg);
48 int do_update(struct query *q, char *argv[], char *qual,
49               int (*action)(), char *actarg);
50 int do_append(struct query *q, char *argv[], char *pqual,
51               int (*action)(), char *actarg);
52 int do_delete(struct query *q, char *qual,
53               int (*action)(), char *actarg);
54 void build_sql_stmt(char *result_buf, char *cmd, char *targetlist,
55                     char *argv[], char *qual);
56 char *build_sort(struct validate *v, char *sort);
57
58 /* from qvalidate.dc */
59 int validate_fields(struct query *q, char *argv[], struct valobj *vo, int n);
60 int validate_row(struct query *q, char *argv[], struct validate *v);
61
62
63 /*
64  * dbmserr: Called when the DBMS indicates an error.
65  */
66
67 void dbmserr(void)
68 {
69     EXEC SQL BEGIN DECLARE SECTION; 
70     char err_msg[256];
71     EXEC SQL END DECLARE SECTION;
72     int bufsize=256, msglength=0;
73
74     dbms_errno = -sqlca.sqlcode;
75     mr_errcode = MR_DBMS_ERR;
76     com_err(whoami, MR_DBMS_ERR, " code %d\n", dbms_errno);
77     sqlglm(err_msg, &bufsize, &msglength);
78     err_msg[msglength]=0;
79     com_err(whoami, 0, "SQL error text = %s", err_msg);
80     critical_alert("MOIRA", "Moira server encountered DBMS ERROR %d\n%s",
81                        dbms_errno, err_msg);
82 }
83
84 /* This is declarative, not executed.  Applies from here on, in this file. */
85 EXEC SQL WHENEVER SQLERROR DO dbmserr();
86
87 int mr_open_database(void)
88 {
89     register int i;
90     SQLDA *mr_alloc_sqlda();
91     static first_open = 1;
92
93     if (first_open) {
94         first_open = 0;
95
96         /* initialize local argv */
97         for (i = 0; i < 16; i++)
98           Argv[i] = malloc(ARGLEN);
99
100         mr_sqlda = mr_alloc_sqlda();       
101
102         incremental_init();
103         flush_cache();
104     }
105         
106     dbms_errno = 0;
107     mr_errcode = 0;
108
109     /* open the database */
110     EXEC SQL CONNECT :database IDENTIFIED BY :database;
111
112     if(dbms_errno) 
113         return(mr_errcode);
114
115     EXEC SQL SELECT data_length INTO :mr_sig_length FROM user_tab_columns WHERE table_name='USERS' and column_name='SIGNATURE';
116     EXEC SQL COMMIT WORK;
117     if(dbms_errno)
118         return(mr_errcode);
119
120     return(MR_SUCCESS);
121 }
122
123 void mr_close_database(void)
124 {
125     flush_cache();
126     EXEC SQL COMMIT RELEASE;
127 }
128
129 int mr_check_access(cl, name, argc, argv_ro)
130      client *cl;
131      char *name, *argv_ro[];
132      int argc;
133 {
134     struct query *q;
135
136     dbms_errno = 0;
137     mr_errcode = 0;
138
139     q = get_query_by_name(name, cl->args->mr_version_no);
140     if (q == (struct query *)0)
141         return(MR_NO_HANDLE);
142
143     return(mr_verify_query(cl, q, argc, argv_ro));    
144 }
145
146 int mr_process_query(cl, name, argc, argv_ro, action, actarg)
147      client *cl;
148      char *name, *argv_ro[], *actarg;
149      int argc, (*action)();
150 {
151     register struct query *q;
152     register int status;
153     register struct validate *v;
154     char qual[256];
155     char sort[32];
156     char *pqual;
157     char *psort;
158     EXEC SQL BEGIN DECLARE SECTION; 
159     char *table;
160     EXEC SQL END DECLARE SECTION; 
161     struct save_queue *sq;
162
163     dbms_errno = 0;
164     mr_errcode = 0;
165
166     /* list queries command */
167     if (!strcmp(name, "_list_queries")) {
168         list_queries(cl->args->mr_version_no, action, actarg);
169         return(MR_SUCCESS);
170     }
171
172     /* help query command */
173     if (!strcmp(name, "_help")) {
174         if (argc < 1)
175             return(MR_ARGS);
176         q = get_query_by_name(argv_ro[0], cl->args->mr_version_no);
177         if (q == (struct query *)0) return(MR_NO_HANDLE);
178         help_query(q, action, actarg);
179         return(MR_SUCCESS);
180     }
181
182     /* get query structure, return error if named query does not exist */
183     q = get_query_by_name(name, cl->args->mr_version_no);
184     if (q == (struct query *)0) return(MR_NO_HANDLE);
185     v = q->validate;
186
187     /* setup argument vector, verify access and arguments */
188     if ((status = mr_verify_query(cl, q, argc, argv_ro)) != MR_SUCCESS)
189         goto out;
190
191     /* perform any special query pre-processing */
192     if (v && v->pre_rtn) {
193         status = (*v->pre_rtn)(q, Argv, cl, 0);
194         if (status != MR_SUCCESS)
195             goto out;
196     }
197
198     switch (q->type) {
199     case RETRIEVE:
200         /* for queries that do not permit wildcarding, check if row
201            uniquely exists */
202         if (v && v->field) {
203             status = validate_row(q, Argv, v); 
204             if (status != MR_EXISTS) break;
205         }
206
207         /* build "where" clause if needed */
208         if (q->qual) {
209             build_qual(q->qual, q->argc, Argv, qual); 
210             pqual = qual;
211         } else {
212             pqual = 0;
213         }
214
215         /* build "sort" clause if needed */
216         if (v && v->valobj) {
217             psort = build_sort(v, sort);
218         } else {
219             psort = 0;
220         }
221
222         /* if there is a followup routine, then we must save the results */
223         /* of the first query for use by the followup routine */
224         /* if q->rvar = NULL, perform post_rtn only */
225         if (q->rvar) {
226             if (v && v->post_rtn) {
227                 sq = sq_create();
228                 status = do_retrieve(q, pqual, psort, sq_save_args, sq);
229                 if (status != MR_SUCCESS) {
230                     sq_destroy(sq);
231                     break;
232                 }
233                 status = (*v->post_rtn)(q, sq, v, action, actarg, cl);
234             } else {
235                 /* normal retrieve */
236                 status = do_retrieve(q, pqual, psort, action, actarg);
237             }
238             if (status != MR_SUCCESS) break;
239         } else {
240             status = (*v->post_rtn)(q, Argv, cl, action, actarg);
241         }
242
243         break;
244
245     case UPDATE:
246         /* see if row already exists */
247         if (v->field) {
248             status = validate_row(q, Argv, v);
249             if (status != MR_EXISTS) break;
250         }
251
252         /* build "where" clause and perform update */
253         /* if q->rvar = NULL, perform post_rtn only */
254         if (q->rvar) {
255             build_qual(q->qual, q->argc, Argv, qual);
256             incremental_before(q->rtable, qual, argv_ro);
257             status = do_update(q, &Argv[q->argc], qual, action, actarg);
258             incremental_after(q->rtable, qual, argv_ro);
259             if (status != MR_SUCCESS) break;
260             flush_name(argv_ro[0], q->rtable);
261             table = table_name[q->rtable];
262             if (strcmp(q->shortname, "sshi") && strcmp(q->shortname, "ssif")) {
263                 EXEC SQL UPDATE tblstats
264                   SET updates = updates + 1, modtime = SYSDATE
265                   WHERE table_name = :table;
266             }
267         }
268
269         /* execute followup routine (if any) */
270         if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
271
272         break;
273
274     case APPEND:
275         /* see if row already exists */
276         if (v->field) {
277             status = validate_row(q, Argv, v);
278             if (status != MR_NO_MATCH) break;
279         }
280
281         /* build "where" clause if needed */
282         if (q->qual) {
283             build_qual(q->qual, q->argc, Argv, qual);
284             pqual = qual;
285         } else {
286             pqual = 0;
287         }
288
289         /* perform the append */
290         /* if q->rvar = NULL, perform post_rtn only */
291         if (q->rvar) {
292             incremental_clear_before();
293             status = do_append(q, &Argv[q->argc], pqual, action, actarg);
294             if (status != MR_SUCCESS) break;
295             if (v && v->object_id) {
296                 sprintf(qual, "%s.%s = %s",q->rvar, v->object_id, 
297                         Argv[q->argc+q->vcnt]);
298                 incremental_after(q->rtable, qual, argv_ro);
299             } else
300               incremental_after(q->rtable, pqual, argv_ro);
301
302             table = table_name[q->rtable];
303             EXEC SQL UPDATE tblstats
304               SET appends = appends + 1, modtime = SYSDATE
305               WHERE table_name = :table;
306         }
307         
308         /* execute followup routine */
309         if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
310         break;
311
312     case DELETE:
313         /* see if row already exists */
314         if (v->field) {
315             status = validate_row(q, Argv, v);
316             if (status != MR_EXISTS) break;
317         }
318
319         /* build "where" clause and perform delete */
320         /* if q->rvar = NULL, perform post_rtn only */
321         if (q->rvar) {
322             build_qual(q->qual, q->argc, Argv, qual);
323             table = table_name[q->rtable];
324             incremental_before(q->rtable, qual, argv_ro);
325             status = do_delete(q, qual, action, actarg);
326             incremental_clear_after();
327             if (status != MR_SUCCESS) break;
328             flush_name(argv_ro[0], q->rtable);
329             EXEC SQL UPDATE tblstats
330               SET deletes = deletes + 1, modtime = SYSDATE
331               WHERE table_name = :table;
332         }
333
334         /* execute followup routine */
335         if (v->post_rtn) status = (*v->post_rtn)(q, Argv, cl);
336         break;
337
338     }
339
340 out:
341     if (status == MR_SUCCESS && dbms_errno != 0) {
342         com_err(whoami, MR_INTERNAL, "Server didn't notice DBMS ERROR %d",
343                        dbms_errno);
344         status = mr_errcode;
345     }
346
347     if (q->type == RETRIEVE) {
348         EXEC SQL COMMIT WORK;
349     } else {
350         if (status == MR_SUCCESS) {
351         EXEC SQL COMMIT WORK;
352             if (journal) {
353                 char buf[1024];
354                 int i;
355                 extern time_t now;
356
357                 fprintf(journal, "%% %s %s %s",
358                         cl->clname, cl->entity, ctime(&now));
359                 fprintf(journal, "%s[%d] ", q->name, cl->args->mr_version_no);
360                 for (i = 0; i < argc; i++) {
361                     if (i != 0) {
362                         putc(' ', journal);
363                     }
364                     requote(buf, argv_ro[i], sizeof(buf));
365                     fputs(buf, journal);
366                 }
367                 putc('\n', journal);
368                 fflush(journal);
369             }
370             incremental_update();
371         } else {
372             cache_abort();
373             EXEC SQL ROLLBACK WORK;
374             incremental_flush();
375         }
376     }
377     cache_commit(); /* commit following abort is safe */
378
379     if (status != MR_SUCCESS && log_flags & LOG_RES)
380         com_err(whoami, status, " (Query failed)");
381     return(status);
382 }
383
384 int build_qual(fmt_buf, argc, argv, qual)
385      char *fmt_buf, *argv[], *qual;
386      int argc;
387 {
388     char *res, *fmt;
389
390     for(res=qual, fmt=fmt_buf; *fmt; fmt++) {
391         if(*fmt=='%') {
392             if(*++fmt) {
393                 switch(*fmt) {                       
394                   case '%':                              /* %% -> % */
395                     *res++ = *fmt;           
396                     break;
397                   case 's':
398                     if(*argv[0]) {
399                         char *p=*argv;
400                         while(*p) {
401                             if(*p=='\'') *res++='\'';   /* double the ' */
402                             *res++=*p++;
403                         }
404                     }
405                     argv++;
406                     break;
407                   case 'd':
408                     res+=sprintf(res,"%d",*(int *)*argv++);
409                     break;
410                   default:                               /* Swallow other %? pairs */
411                     break;
412                 }
413             } else break;
414         } else *res++ = *fmt;                            /* text -> result buffer */
415     }
416     *res='\0';
417 }
418
419 char *build_sort(v, sort)
420      struct validate *v;
421      char *sort;
422 {
423     register struct valobj *vo;
424     register int n;
425     char elem[16];
426
427     n = v->objcnt;
428     vo = v->valobj;
429     *sort = 0;
430
431     while (--n >= 0) {
432         if (vo->type == V_SORT) {
433             sprintf(elem, "%d", vo->index + 1);    /* Result column number */
434             if (*sort) strcat(sort, ", ");
435             strcat(sort, elem);
436         }
437         vo++;
438     }
439
440     return ((*sort) ? sort : 0);
441 }
442
443
444 /* Build arguement vector, verify query and arguments */
445
446 int privileged;
447
448 int mr_verify_query(cl, q, argc, argv_ro)
449      client *cl;
450      struct query *q;
451      int argc;
452      char *argv_ro[];
453 {
454     register int argreq;
455     register int status;
456     register struct validate *v = q->validate;
457     register int i;
458     register char *to,*fr,*stop;
459
460     privileged = 0;
461
462     /* copy the arguments into a local argv that we can modify */
463     if (argc >= QMAXARGS)
464       return(MR_ARGS);
465     for (i = 0; i < argc; i++) {
466         for (to=Argv[i], fr=argv_ro[i], stop=to+ARGLEN; (*fr) && (to<stop);)
467           *to++ = *fr++;
468
469         if (*fr) 
470           return(MR_ARG_TOO_LONG);
471         *to='\0';
472
473         if (*--to == '\\')
474           return(MR_BAD_CHAR);
475     }
476
477     /* check initial query access */
478     status = check_query_access(q, Argv, cl);
479     if (status != MR_SUCCESS && status != MR_PERM)
480         return(status);
481     if (status == MR_SUCCESS)
482         privileged++;
483
484     /* check argument count */
485     argreq = q->argc;
486     if (q->type == UPDATE || q->type == APPEND) argreq += q->vcnt;
487     if (argc != argreq) return(MR_ARGS);
488
489     /* validate arguments */
490     if (v && v->valobj) {
491         status = validate_fields(q, Argv, v->valobj, v->objcnt);
492         if (status != MR_SUCCESS) return(status);
493     }
494
495     /* perform special query access check */
496     if (!privileged && v && v->acs_rtn) {
497         status = (*v->acs_rtn)(q, Argv, cl);
498         if (status != MR_SUCCESS && status != MR_PERM)
499             return(status);
500         if (status == MR_SUCCESS)
501             return(MR_SUCCESS);
502     }
503
504     return(privileged ? MR_SUCCESS : MR_PERM);
505 }
506
507
508 /* This routine caches info from the database.  Each query acl is stored
509  * in the query structure, and whether that acl contains everybody.
510  */
511
512 int check_query_access(q, argv, cl)
513      struct query *q;
514      char *argv[];
515      client *cl;
516 {
517     EXEC SQL BEGIN DECLARE SECTION; 
518     char *name;
519     int acl_id;
520     static int def_uid;
521     EXEC SQL END DECLARE SECTION; 
522     int client_id;
523     char *client_type;
524
525     /* initialize default uid */
526     if (def_uid == 0) {
527         EXEC SQL SELECT users_id INTO :def_uid FROM users WHERE login='default';
528     }
529
530     /* get query access control list */
531     if (q->acl != 0)
532       acl_id = q->acl;
533     else {
534         name = q->shortname;
535         EXEC SQL SELECT list_id INTO :acl_id FROM capacls WHERE tag = :name;
536         if (sqlca.sqlcode < 0) return(MR_DBMS_ERR);
537         if (sqlca.sqlcode == SQL_NO_MATCH) return(MR_PERM);
538         q->acl = acl_id;
539
540         /* check for default access */
541         EXEC SQL SELECT member_id INTO :acl_id FROM imembers
542           WHERE list_id = :acl_id AND member_type = 'USER' 
543             AND member_id = :def_uid;
544         if (sqlca.sqlerrd[2] == 0)
545           q->everybody = 0;
546         else
547           q->everybody = 1;
548     }
549
550     if (q->everybody)
551       return(MR_SUCCESS);
552
553     if (get_client(cl, &client_type, &client_id) != MR_SUCCESS)
554       return(MR_PERM);
555     if (find_member("LIST", acl_id, client_type, client_id))
556       return(MR_SUCCESS);
557     else
558       return(MR_PERM);
559 }
560
561
562 int get_client(cl, client_type, client_id)
563      client *cl;
564      char **client_type;
565      int *client_id;
566 {
567     if (cl->users_id > 0) {
568         *client_id = cl->users_id;
569         *client_type = "USER";
570         return(MR_SUCCESS);
571     }
572
573     if (cl->client_id < 0) {
574         *client_id = -cl->users_id;
575         *client_type = "KERBEROS";
576         return(MR_SUCCESS);
577     }
578
579     return(MR_PERM);
580 }
581
582 int find_member(list_type, list_id, member_type, member_id)
583      char *list_type, *member_type;
584      int list_id, member_id;
585 {
586     EXEC SQL BEGIN DECLARE SECTION; 
587     int flag;
588     EXEC SQL END DECLARE SECTION; 
589
590     if (!strcmp(strtrim(list_type), strtrim(member_type)) &&
591         list_id == member_id)
592         return(1);
593
594     /* see if client is a direct member of list */
595     flag = 0;
596     EXEC SQL SELECT member_id INTO :flag FROM imembers
597       WHERE list_id = :list_id AND member_type = :member_type 
598         AND member_id = :member_id;
599     if(flag!=0) flag=1;             /** Not strictly necessary */
600     if (sqlca.sqlcode == 0)
601       return(flag);            
602     return(0);
603 }
604
605
606 int do_retrieve(q, pqual, psort, action, actarg)
607      struct query *q;
608      char *pqual, *psort, *actarg;
609      int (*action)();
610 {
611     build_sql_stmt(stmt_buf,"SELECT",q->tlist,NULL,pqual);
612     if(psort) {
613       strcat(stmt_buf," ORDER BY ");
614       strcat(stmt_buf,psort);
615     }
616
617     return do_for_all_rows(stmt_buf, q->vcnt, action, actarg);
618 }
619
620 char *sqlstrstr(str, pat)
621      char *str, *pat;
622 {
623     register char *p=pat;
624     
625     do {
626         if(*str=='\'') {    /* Skip over single-quote delimited substrings */ 
627             while(*++str && (*str!='\'')) 
628                 ; 
629             continue;
630         }
631         if(*str==*p) {
632             register char *s;
633             s=str; 
634             while(*++p && (*++s==*p))
635                 ; 
636             if(*p) p=pat;  /* failed */
637         }
638     } while(*p && *++str);
639
640     if(!*str) str=NULL;
641     return(str);
642 }
643
644 void optimize_sql_stmt(buf)
645      char *buf;
646 {
647     char *point=buf, *pat, *eopat, *esc1, *esc2, *csr;
648
649     for(point=buf; point=sqlstrstr(point,"LIKE"); point++)  {
650         /* Now pointing to string "LIKE" */
651
652         /* Look at next word */
653         for(pat=point+4; *pat==' '; pat++) ;
654
655         /* Is it a single-quote delimited string? */
656         if(*pat!='\'') continue;
657
658         /* look for "escape" clause - save escape character */
659         /* 1. Find end of pattern */
660         for(eopat=pat+1; 1; eopat++) {
661             if(*eopat=='\'') {
662                 if(eopat[1]=='\'')  /* single-quote is self-escaping */
663                     eopat++;
664                 else
665                     break;
666             }
667         }
668
669         /* 2. Look at next word */
670         for(esc1=eopat; *++esc1==' ';) ;
671
672         /* 3. esc1=0 if not "ESCAPE '?'", where the ? may be any character. */
673         if(strncmp(esc1,"ESCAPE",6)) esc1=NULL;
674
675         if(esc1) {
676             for(esc2=esc1+6; *esc2==' '; esc2++) ;
677             
678             if(*esc2++!='\'') continue; /* Bad SQL syntax. Skip. */
679             /* esc2 now points at the escape character itself */
680             if(esc2[1]!='\'') continue; /* Weird escape string. Skip. */
681         } else {
682             esc2="\\";
683         }
684
685         /* Is pattern free from special characters? */
686         for(csr=pat; csr<eopat; csr++) 
687             if((*csr=='%') || (*csr=='_') || (*csr==*esc2)) break;
688         if(csr!=eopat) continue; /* Uses pattern matching. Skip. */
689
690         /* Optimize the query statement */
691         /* 1. Change "LIKE" to " =  " */
692         memcpy(point," =  ",4);
693         
694         /* 2. Change "ESCAPE" to "      " */
695         if(esc1) {
696             memset(esc1,' ',6);
697             /* 3. Change  "'*'" to "   " */
698             /*    (Changes '''' to "    ") */
699             if(esc2) memset(esc2-1,' ',(*esc2=='\'')?4:3); 
700         }
701     }
702 }
703
704 void build_sql_stmt(result_buf, cmd, targetlist, argv, qual)
705      char *result_buf, *cmd, *targetlist, *argv[], *qual;
706 {
707     char fmt_buf[MR_STMTBUF_LEN];
708     register char *res, *fmt;
709
710     if(qual)
711       sprintf(fmt_buf,"%s %s WHERE %s",cmd,targetlist,qual);
712     else
713       sprintf(fmt_buf,"%s %s",cmd,targetlist);
714
715     for(res=result_buf, fmt=fmt_buf; *fmt; fmt++) {
716         if(*fmt=='%') {
717             if(*++fmt) {
718                 switch(*fmt) {                       
719                   case '%':                              /* %% -> % */
720                     *res++ = *fmt;           
721                     break;
722                   case 's':
723                     if(*argv[0]) {
724                         char *p=*argv;
725                         while(*p) {
726                             if(*p=='\'') *res++='\'';   /* double the ' */
727                             *res++=*p++;
728                         }
729                     }
730                     argv++;
731                     break;
732                   case 'd':
733                     res+=sprintf(res,"%d",*(int *)*argv++);
734                     break;
735                   default:                               /* Swallow other %? pairs */
736                     break;
737                 }
738             } else break;
739         } else *res++ = *fmt;                            /* text -> result buffer */
740     }
741     *res='\0';
742
743     optimize_sql_stmt(result_buf);
744 }
745
746 int do_update(q, argv, qual, action, actarg)
747      struct query *q;
748      char *argv[], *qual, *actarg;
749      int (*action)();
750 {
751     build_sql_stmt(stmt_buf,"UPDATE",q->tlist,argv,qual);
752     EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
753     if (mr_errcode) return(mr_errcode);
754     return(MR_SUCCESS);
755 }
756
757 int do_append(q, argv, pqual, action, actarg)
758      struct query *q;
759      char *argv[], *pqual, *actarg;
760      int (*action)();
761 {
762     build_sql_stmt(stmt_buf,"INSERT",q->tlist,argv,pqual);
763     EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
764     if (mr_errcode) return(mr_errcode);
765     return(MR_SUCCESS);
766 }
767
768 int do_delete(q, qual, action, actarg)
769      struct query *q;
770      char *qual, *actarg;
771      int (*action)();
772 {
773     sprintf(stmt_buf,"DELETE FROM %s WHERE %s",table_name[q->rtable],qual);
774     EXEC SQL EXECUTE IMMEDIATE :stmt_buf;
775     if (mr_errcode) return(mr_errcode);
776     return(MR_SUCCESS);
777 }
778
779
780 /**
781  ** set_next_object_id - set next object id in values table
782  **
783  ** Inputs: object - object name in values table and in objects
784  **         table - name of table objects are found in
785  **         limit - should the ID be range limited
786  **
787  ** - called before an APPEND operation to set the next object id to
788  **   be used for the new record to the next free value
789  **
790  **/
791
792 int set_next_object_id(object, table, limit)
793 EXEC SQL BEGIN DECLARE SECTION;
794      char *object;
795 EXEC SQL END DECLARE SECTION;
796      enum tables table;
797      int limit;
798 {
799     EXEC SQL BEGIN DECLARE SECTION; 
800     int value;
801     EXEC SQL END DECLARE SECTION;
802     int starting_value;
803     
804     EXEC SQL SELECT value INTO :value FROM numvalues WHERE name = :object;
805     if (sqlca.sqlerrd[2] != 1)
806         return(MR_NO_ID);
807
808     starting_value=value;
809     while (1) { 
810         if (limit && value > MAX_ID_VALUE) 
811             value = MIN_ID_VALUE;
812
813         sprintf(stmt_buf,"SELECT %s FROM %s WHERE %s=%d",
814                 object,table_name[table],object,value);
815         dosql(sqlbuffer);
816         if (sqlca.sqlcode < 0) return(mr_errcode);
817         if (sqlca.sqlcode == SQL_NO_MATCH) break;
818
819         value++;
820         if (limit && value == starting_value) {   
821             com_err(whoami,0,"All id values have been used");
822             return(MR_NO_ID);
823         }
824     }
825
826     if (LOG_RES)
827         com_err(whoami, 0, "setting ID %s to %d", object, value);
828     EXEC SQL UPDATE numvalues SET value = :value WHERE name = :object;
829     return(MR_SUCCESS);
830 }
831
832
833 /* Turn a kerberos name into the user's ID of the account that principal
834  * owns.  Sets the kerberos ID and user ID.
835  */
836
837 int set_krb_mapping(name, login, ok, kid, uid)
838      char *name, *login;
839      int ok, *kid, *uid;
840 {
841     EXEC SQL BEGIN DECLARE SECTION; 
842     int u_id, k_id;
843     char *krbname;
844     EXEC SQL END DECLARE SECTION; 
845
846     krbname = name;
847     *kid = 0;
848     *uid = 0;
849
850     EXEC SQL SELECT km.users_id, km.string_id INTO :u_id, :k_id
851       FROM krbmap km, strings str
852       WHERE km.string_id = str.string_id AND str.string = :krbname;
853     EXEC SQL COMMIT WORK;
854
855     if (dbms_errno) return(mr_errcode);
856     
857     if (sqlca.sqlerrd[2] == 1) {    /* rowcount */
858         *kid = -k_id;
859         *uid = u_id;
860         return(MR_SUCCESS);
861     }
862
863     if (name_to_id(name, STRINGS_TABLE, &k_id) == MR_SUCCESS)
864       *kid = -k_id;
865
866     if (!ok) {             
867         *uid = *kid;
868         return(MR_SUCCESS);
869     }
870
871     if (name_to_id(login, USERS_TABLE, uid) != MR_SUCCESS)
872       *uid = 0;
873
874     if (*kid == 0)
875       *kid = *uid;
876     if (dbms_errno) return(mr_errcode);
877     return(MR_SUCCESS);
878 }
879
880
881 /* For now this just checks the argc's.  It should also see that there
882  * are no duplicate names.
883  */
884
885 void sanity_check_queries(void)
886 {
887     register int i;
888     int maxv = 0, maxa = 0;
889     extern int QueryCount2;
890     extern struct query Queries2[];
891
892 #define MAX(x,y) ((x) > (y) ? (x) : (y))
893
894     for (i = 0; i < QueryCount2; i++) {
895         maxv = MAX(maxv, Queries2[i].vcnt);
896         maxa = MAX(maxa, Queries2[i].argc);
897     }
898     if (MAX(maxv, maxa) > QMAXARGS) {
899         com_err(whoami, 0, "A query has more args than QMAXARGS");
900         exit(1);
901     }
902 }
903
904
905 /* Generically do a SELECT, storing the results in the provided buffers */
906
907 void dosql(buffers)
908      char *buffers[];
909 {
910   int i, errcode=0, errlen;
911
912   EXEC SQL PREPARE inc_stmt FROM :stmt_buf;
913   if(sqlca.sqlcode) return;
914   EXEC SQL DECLARE inc_crs CURSOR FOR inc_stmt;
915   EXEC SQL OPEN inc_crs;
916   mr_sqlda->N = QMAXARGS;
917   EXEC SQL DESCRIBE SELECT LIST FOR inc_stmt INTO mr_sqlda;
918   mr_sqlda->N = mr_sqlda->F;
919   for(i=0; i<mr_sqlda->N; i++) {
920     mr_sqlda->V[i]=buffers[i];
921     mr_sqlda->T[i]=97;
922     mr_sqlda->L[i]=ARGLEN;
923   }
924   EXEC SQL FETCH inc_crs USING DESCRIPTOR mr_sqlda;
925
926   /* if we got an error from the FETCH, we have to preserve it or the
927      close will reset it and the caller will think nothing happened */
928   if(sqlca.sqlcode) {
929     errcode=sqlca.sqlcode;
930     errlen=sqlca.sqlerrm.sqlerrml;
931   }
932
933   EXEC SQL CLOSE inc_crs;
934   if(errcode) {
935     sqlca.sqlcode=errcode;
936     sqlca.sqlerrm.sqlerrml=errlen;
937   }
938 }
939
940 int do_for_all_rows(query, count, action, actarg)
941 EXEC SQL BEGIN DECLARE SECTION;
942      char *query;
943 EXEC SQL END DECLARE SECTION;
944      int count, (*action)(), actarg;
945 {
946   int i, rowcount=0;
947
948   EXEC SQL PREPARE stmt FROM :query;
949   if(sqlca.sqlcode) return;
950   EXEC SQL DECLARE curs CURSOR FOR stmt;
951   EXEC SQL OPEN curs;
952   mr_sqlda->N = count;
953   EXEC SQL DESCRIBE SELECT LIST FOR stmt INTO mr_sqlda;
954   mr_sqlda->N = mr_sqlda->F;
955   for(i=0; i<mr_sqlda->N; i++) {
956     mr_sqlda->V[i]=sqlbuffer[i];
957     mr_sqlda->T[i]=97;
958     mr_sqlda->L[i]=ARGLEN;
959   }
960
961   while(1) {
962     EXEC SQL FETCH curs USING DESCRIPTOR mr_sqlda;
963     if(sqlca.sqlcode != 0) break;
964     (*action)(count, sqlbuffer, actarg);
965     rowcount++;
966   }
967   EXEC SQL CLOSE curs;
968   
969   if (mr_errcode) return(mr_errcode);
970   return ((rowcount == 0) ? MR_NO_MATCH : MR_SUCCESS);
971 }
972
973
974 /* eof:qrtn.dc */
This page took 0.121913 seconds and 5 git commands to generate.