Plan 9 from Bell Labs’s /usr/web/sources/contrib/steve/root/sys/src/cmd/mysqlfs/results.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
#include <bio.h>
#include "mysql.h"

void
widths(Results *res)
{
	Row *r;
	Col *c;
	Field *f;
	int n, none;

	if(res == nil)
		return;

	none = strlen("<nil>");

	for(f = res->fields; f; f = f->next){
		if(f->name)
			n = strlen(f->name);
		else
			n = none;
		if(f->width < n)
			f->width = n;
	}

	for(r = res->rows; r; r = r->next){
		f = res->fields;
		for(c = r->cols; c; c = c->next){
			if(c->str)
				n = strlen(c->str);
			else
				n = none;
			if(f->width < n)
				f->width = n;
			f = f->next;
		}
	}

	n = 1;
	for(f = res->fields; f; f = f->next){
		f->start = n;
		n += f->width+1;
	}
}

static void
header(Fmt *fmt, Field *fields, Layout *l)
{
	Field *f;
	char colsep, rowsep;

	colsep = (l->colsep)? l->colsep: '|';
	rowsep = (l->rowsep)? l->rowsep: '\n';

	for(f = fields; f; f = f->next){
		if(! f->next)
			fmtprint(fmt, "%s", f->name);
		else
		if(! l->delimited)
			fmtprint(fmt, "%*s ", -f->width, f->name);
		else
			fmtprint(fmt, "%s%c", f->name, colsep);
	}
	fmtprint(fmt, "%c", rowsep);
}

static void
data(Fmt *fmt, Row *row, Field *fields, Layout *l)
{
	Col *c;
	Field *f;
	char colsep, rowsep;

	colsep = (l->colsep)? l->colsep: '|';
	rowsep = (l->rowsep)? l->rowsep: '\n';

	f = fields;
	for(c = row->cols; c; c = c->next){
		if(! c->next)
			fmtprint(fmt, "%s", c->str);
		else
		if(! l->delimited)
			fmtprint(fmt, "%*s ", -f->width, c->str);
		else
			fmtprint(fmt, "%s%c", c->str, colsep);
		f = f->next;
	}
	fmtprint(fmt, "%c", rowsep);
}

char *
fmtfields(Results *res, int idx)
{
	Field *f;

	for(f = res->fields; idx > 0 && f; f = f->next, idx--)
		continue;
	if(f == nil)
		return nil;
	return smprint("%d %d %s\n", f->start, f->start+f->width, f->name);
}


char *
fmtdata(Results *res, Layout *l, int idx)
{
	Row *r;
	Fmt fmt;

	if(res == nil)
		return nil;
	fmtstrinit(&fmt);

	if(l->headings){
		if(idx == 0){
			header(&fmt, res->fields, l);
			return fmtstrflush(&fmt);
		}
		idx--;
	}
	for(r = res->rows; idx > 0 && r; r = r->next, idx--)
		continue;
	if(r == nil)
		return nil;

	data(&fmt, r, res->fields, l);
	return fmtstrflush(&fmt);
}


Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.