12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262 |
- /*##############################################################################
- HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ############################################################################## */
- #include "platform.h"
- #include "jliball.hpp"
- #include "eclrtl.hpp"
- #include "rtlds_imp.hpp"
- #include "fvresultset.ipp"
- #include "fileview.hpp"
- #include "fvsource.ipp"
- #include "fverror.hpp"
- #include "hqlerror.hpp"
- #include "eclhelper.hpp"
- #include "hqlattr.hpp"
- #include "hqlutil.hpp"
- #include "fvdatasource.hpp"
- #define MAX_RECORD_SIZE 4096
- inline void appendNextXpathName(StringBuffer &s, const char *&xpath)
- {
- while (*xpath && !strchr("*[/", *xpath))
- s.append(*xpath++);
- xpath = strchr(xpath, '/');
- }
- void splitXmlTagNamesFromXPath(const char *xpath, StringAttr &inner, StringAttr *outer=NULL)
- {
- if (!xpath)
- return;
- StringBuffer s1;
- StringBuffer s2;
- appendNextXpathName(s1, xpath);
- if (outer && xpath)
- appendNextXpathName(s2, ++xpath);
- if (xpath) //xpath too deep
- return;
- if (!s2.length())
- inner.set(s1.str());
- else
- {
- inner.set(s2.str());
- outer->set(s1.str());
- }
- if (!inner.get())
- inner.set("");
- if (outer && !outer->get())
- outer->set("");
- }
- DataSourceMetaItem::DataSourceMetaItem(unsigned _flags, const char * _name, const char * _xpath, ITypeInfo * _type)
- {
- flags = _flags;
- name.set(_name);
- type.set(_type);
- xpath.set(_xpath);
- splitXmlTagNamesFromXPath(_xpath, tagname);
- hasMixedContent = false;
- }
- DataSourceMetaItem::DataSourceMetaItem(unsigned _flags, MemoryBuffer & in)
- {
- flags = _flags;
- in.read(hasMixedContent);
- in.read(name);
- in.read(xpath);
- type.setown(deserializeType(in));
- splitXmlTagNamesFromXPath(xpath.get(), tagname);
- }
- void DataSourceMetaItem::serialize(MemoryBuffer & out) const
- {
- out.append(flags);
- out.append(hasMixedContent);
- out.append(name);
- out.append(xpath);
- type->serialize(out);
- }
- //---------------------------------------------------------------------------
- DataSourceDatasetItem::DataSourceDatasetItem(const char * _name, const char * _xpath, IHqlExpression * expr) : DataSourceMetaItem(FVFFdataset, NULL, NULL, NULL), record(expr->queryRecord(), 0, true, false, false)
- {
- type.setown(makeTableType(NULL));
- name.set(_name);
- xpath.set(_xpath);
- splitXmlTagNamesFromXPath(_xpath, record.tagname, &tagname);
- if (!record.tagname.length())
- record.tagname.set("Row");
- }
- DataSourceDatasetItem::DataSourceDatasetItem(unsigned flags, MemoryBuffer & in) : DataSourceMetaItem(FVFFdataset, NULL, NULL, NULL), record(in)
- {
- type.setown(makeTableType(NULL));
- in.read(name);
- }
- void DataSourceDatasetItem::serialize(MemoryBuffer & out) const
- {
- out.append(flags);
- record.serialize(out);
- out.append(name);
- }
- //---------------------------------------------------------------------------
- DataSourceSetItem::DataSourceSetItem(const char * _name, const char * _xpath, ITypeInfo * _type) : DataSourceMetaItem(FVFFset, _name, NULL, _type)
- {
- createChild();
- xpath.set(_xpath);
- StringBuffer attr;
- splitXmlTagNamesFromXPath(_xpath, record.tagname, &tagname);
- if (!_xpath)
- record.tagname.set("Item");
- }
- DataSourceSetItem::DataSourceSetItem(unsigned flags, MemoryBuffer & in) : DataSourceMetaItem(flags, in)
- {
- createChild();
- splitXmlTagNamesFromXPath(xpath.get(), record.tagname, &tagname);
- if (!record.tagname.get())
- record.tagname.set("Item");
- }
- void DataSourceSetItem::createChild()
- {
- ITypeInfo * childType = type->queryChildType()->queryPromotedType();
- record.addSimpleField("Item", NULL, childType);
- }
- void DataSourceSetItem::serialize(MemoryBuffer & out) const
- {
- out.append(flags);
- record.serialize(out);
- out.append(name);
- }
- //---------------------------------------------------------------------------
- DataSourceMetaData::DataSourceMetaData(IHqlExpression * _record, byte _numFieldsToIgnore, bool _randomIsOk, bool _isGrouped, unsigned _keyedSize)
- {
- init();
- numFieldsToIgnore = _numFieldsToIgnore;
- randomIsOk = _randomIsOk;
- isStoredFixedWidth = true;
- //MORE: Blobs aren't handled correctly in indexes....
- maxRecordSize = ::getMaxRecordSize(_record, MAX_RECORD_SIZE);
- keyedSize = _keyedSize;
- gatherFields(_record, false, &hasMixedContent);
- if (_isGrouped)
- {
- Owned<ITypeInfo> type = makeBoolType();
- addSimpleField("__groupfollows__", NULL, type);
- maxRecordSize++;
- }
- gatherAttributes();
- if (isStoredFixedWidth)
- assertex(minRecordSize == maxRecordSize);
- }
- DataSourceMetaData::DataSourceMetaData()
- {
- init();
- randomIsOk = true;
- isStoredFixedWidth = true;
- }
- DataSourceMetaData::DataSourceMetaData(type_t typeCode)
- {
- init();
- OwnedITypeInfo type;
- if (typeCode == type_unicode)
- type.setown(makeUnicodeType(UNKNOWN_LENGTH, 0));
- else
- type.setown(makeStringType(UNKNOWN_LENGTH, NULL, NULL));
- fields.append(*new DataSourceMetaItem(FVFFnone, "line", NULL, type));
- }
- void DataSourceMetaData::init()
- {
- keyedSize = 0;
- minRecordSize = 0;
- maxRecordSize = 0;
- bitsRemaining = 0;
- numVirtualFields = 0;
- isStoredFixedWidth = false;
- randomIsOk = false;
- numFieldsToIgnore = 0;
- hasMixedContent = false;
- }
- DataSourceMetaData::DataSourceMetaData(MemoryBuffer & buffer)
- {
- numVirtualFields = 0;
- buffer.read(numFieldsToIgnore);
- buffer.read(randomIsOk);
- buffer.read(hasMixedContent);
- buffer.read(isStoredFixedWidth);
- buffer.read(minRecordSize);
- buffer.read(keyedSize);
- buffer.read(maxRecordSize);
- unsigned numFields;
- buffer.read(numFields);
- for (unsigned idx=0; idx < numFields; idx++)
- {
- byte flags;
- buffer.read(flags);
- if (flags == FVFFdataset)
- fields.append(*new DataSourceDatasetItem(flags, buffer));
- else if (flags == FVFFset)
- fields.append(*new DataSourceSetItem(flags, buffer));
- else
- fields.append(*new DataSourceMetaItem(flags, buffer));
- if (flags == FVFFvirtual)
- ++numVirtualFields;
- }
- gatherAttributes();
- }
- void DataSourceMetaData::addFileposition()
- {
- addVirtualField("__fileposition__", NULL, makeIntType(8, false));
- }
- void DataSourceMetaData::addSimpleField(const char * name, const char * xpath, ITypeInfo * type, unsigned flag)
- {
- ITypeInfo * promoted = type->queryPromotedType();
- unsigned size = promoted->getSize();
- unsigned thisBits = 0;
- if (size == UNKNOWN_LENGTH)
- {
- isStoredFixedWidth = false;
- switch (type->getTypeCode())
- {
- case type_set:
- minRecordSize += sizeof(bool) + sizeof(size32_t);
- break;
- case type_varstring:
- minRecordSize += 1;
- break;
- case type_packedint:
- minRecordSize += 1;
- break;
- case type_varunicode:
- minRecordSize += sizeof(UChar);
- break;
- default:
- minRecordSize += sizeof(size32_t);
- break;
- }
- }
- else if (type->getTypeCode() == type_bitfield)
- {
- thisBits = type->getBitSize();
- if (thisBits > bitsRemaining)
- {
- size = type->queryChildType()->getSize();
- minRecordSize += size;
- bitsRemaining = size * 8;
- }
- bitsRemaining -= thisBits;
- }
- else
- minRecordSize += size;
- if (thisBits == 0)
- bitsRemaining = 0;
- fields.append(*new DataSourceMetaItem(flag, name, xpath, type));
- }
- void DataSourceMetaData::addVirtualField(const char * name, const char * xpath, ITypeInfo * type)
- {
- fields.append(*new DataSourceMetaItem(FVFFvirtual, name, xpath, type));
- ++numVirtualFields;
- }
- void DataSourceMetaData::extractKeyedInfo(UnsignedArray & offsets, TypeInfoArray & types)
- {
- unsigned curOffset = 0;
- ForEachItemIn(i, fields)
- {
- if (curOffset >= keyedSize)
- break;
- DataSourceMetaItem & cur = fields.item(i);
- switch (cur.flags)
- {
- case FVFFnone:
- {
- offsets.append(curOffset);
- types.append(*LINK(cur.type));
- unsigned size = cur.type->getSize();
- assertex(size != UNKNOWN_LENGTH);
- curOffset += size;
- break;
- }
- case FVFFbeginrecord:
- case FVFFendrecord:
- break;
- default:
- throwUnexpected();
- }
- }
- offsets.append(curOffset);
- assertex(curOffset == keyedSize);
- }
- //MORE: Really this should create no_selects for the sub records, but pass on that for the moment.
- void DataSourceMetaData::gatherFields(IHqlExpression * expr, bool isConditional, bool *pMixedContent)
- {
- switch (expr->getOperator())
- {
- case no_record:
- gatherChildFields(expr, isConditional, pMixedContent);
- break;
- case no_ifblock:
- {
- OwnedITypeInfo boolType = makeBoolType();
- OwnedITypeInfo voidType = makeVoidType();
- isStoredFixedWidth = false;
- fields.append(*new DataSourceMetaItem(FVFFbeginif, NULL, NULL, boolType));
- gatherChildFields(expr->queryChild(1), true, pMixedContent);
- fields.append(*new DataSourceMetaItem(FVFFendif, NULL, NULL, voidType));
- break;
- }
- case no_field:
- {
- if (expr->hasAttribute(__ifblockAtom))
- break;
- Linked<ITypeInfo> type = expr->queryType();
- IAtom * name = expr->queryName();
- IHqlExpression * nameAttr = expr->queryAttribute(namedAtom);
- StringBuffer outname;
- if (nameAttr && nameAttr->queryChild(0)->queryValue())
- nameAttr->queryChild(0)->queryValue()->getStringValue(outname);
- else
- outname.append(name).toLowerCase();
- StringBuffer xpathtext;
- const char * xpath = NULL;
- IHqlExpression * xpathAttr = expr->queryAttribute(xpathAtom);
- if (xpathAttr && xpathAttr->queryChild(0)->queryValue())
- xpath = xpathAttr->queryChild(0)->queryValue()->getStringValue(xpathtext);
- unsigned flag = FVFFnone;
- if (isKey() && expr->hasAttribute(blobAtom))
- {
- type.setown(makeIntType(8, false));
- flag = FVFFblob;
- }
- type_t tc = type->getTypeCode();
- if (tc == type_row)
- {
- OwnedITypeInfo voidType = makeVoidType();
- Owned<DataSourceMetaItem> begin = new DataSourceMetaItem(FVFFbeginrecord, outname, xpath, voidType);
- //inherit mixed content from child row with xpath('')
- bool *pItemMixedContent = (pMixedContent && xpath && !*xpath) ? pMixedContent : &(begin->hasMixedContent);
- fields.append(*begin.getClear());
- gatherChildFields(expr->queryRecord(), isConditional, pItemMixedContent);
- fields.append(*new DataSourceMetaItem(FVFFendrecord, outname, xpath, voidType));
- }
- else if ((tc == type_dictionary) || (tc == type_table) || (tc == type_groupedtable))
- {
- isStoredFixedWidth = false;
- Owned<DataSourceDatasetItem> ds = new DataSourceDatasetItem(outname, xpath, expr);
- if (pMixedContent && xpath && !*xpath)
- *pMixedContent = ds->queryChildMeta()->hasMixedContent;
- fields.append(*ds.getClear());
- }
- else if (tc == type_set)
- {
- isStoredFixedWidth = false;
- if (pMixedContent && xpath && !*xpath)
- *pMixedContent = true;
- fields.append(*new DataSourceSetItem(outname, xpath, type));
- }
- else
- {
- if (type->getTypeCode() == type_alien)
- {
- IHqlAlienTypeInfo * alien = queryAlienType(type);
- type.set(alien->queryPhysicalType());
- }
- if (pMixedContent && xpath && !*xpath)
- *pMixedContent = true;
- addSimpleField(outname, xpath, type, flag);
- }
- break;
- }
- }
- }
- void DataSourceMetaData::gatherChildFields(IHqlExpression * expr, bool isConditional, bool *pMixedContent)
- {
- bitsRemaining = 0;
- ForEachChild(idx, expr)
- gatherFields(expr->queryChild(idx), isConditional, pMixedContent);
- }
- unsigned DataSourceMetaData::numKeyedColumns() const
- {
- unsigned count = 0;
- unsigned curOffset = 0;
- ForEachItemIn(i, fields)
- {
- if (curOffset >= keyedSize)
- break;
- DataSourceMetaItem & cur = fields.item(i);
- switch (cur.flags)
- {
- case FVFFnone:
- {
- unsigned size = cur.type->getSize();
- assertex(size != UNKNOWN_LENGTH);
- curOffset += size;
- count++;
- break;
- }
- default:
- throwUnexpected();
- }
- }
- return count;
- assertex(curOffset == keyedSize);
- }
- unsigned DataSourceMetaData::numColumns() const
- {
- return fields.ordinality() - numFieldsToIgnore;
- }
- ITypeInfo * DataSourceMetaData::queryType(unsigned column) const
- {
- return fields.item(column).type;
- }
- unsigned DataSourceMetaData::queryFieldFlags(unsigned column) const
- {
- return fields.item(column).flags;
- }
- bool DataSourceMetaData::mixedContent(unsigned column) const
- {
- return fields.item(column).hasMixedContent;
- }
- bool DataSourceMetaData::mixedContent() const
- {
- return hasMixedContent;
- }
- const char * DataSourceMetaData::queryName(unsigned column) const
- {
- return fields.item(column).name;
- }
- const char * DataSourceMetaData::queryXPath(unsigned column) const
- {
- return fields.item(column).xpath;
- }
- const char * DataSourceMetaData::queryXmlTag(unsigned column) const
- {
- DataSourceMetaItem &item = fields.item(column);
- return (item.tagname.get()) ? item.tagname.get() : item.name.get();
- }
- const char *DataSourceMetaData::queryXmlTag() const
- {
- return (tagname.get()) ? tagname.get() : "Row";
- }
- void DataSourceMetaData::gatherNestedAttributes(DataSourceMetaItem &rec, aindex_t &idx)
- {
- aindex_t numItems = fields.ordinality();
- while (++idx < numItems)
- {
- DataSourceMetaItem &item = fields.item(idx);
- if (item.flags==FVFFendrecord)
- return;
- else if (item.flags==FVFFbeginrecord)
- gatherNestedAttributes((!item.tagname.get() || *item.tagname.get()) ? item : rec, idx);
- else if (item.isXmlAttribute())
- rec.nestedAttributes.append(idx);
- }
- }
- void DataSourceMetaData::gatherAttributes()
- {
- aindex_t numItems = fields.ordinality();
- for (aindex_t idx = 0; idx < numItems; ++idx)
- {
- DataSourceMetaItem &item = fields.item(idx);
- if (item.flags==FVFFbeginrecord)
- {
- if (!item.tagname.get() || *item.tagname.get())
- gatherNestedAttributes(item, idx);
- }
- else if (item.isXmlAttribute())
- attributes.append(idx);
- }
- }
- const IntArray &DataSourceMetaData::queryAttrList(unsigned column) const
- {
- return fields.item(column).nestedAttributes;
- }
- const IntArray &DataSourceMetaData::queryAttrList() const
- {
- return attributes;
- }
- IFvDataSourceMetaData * DataSourceMetaData::queryChildMeta(unsigned column) const
- {
- return fields.item(column).queryChildMeta();
- }
- IFvDataSource * DataSourceMetaData::createChildDataSource(unsigned column, unsigned len, const void * data)
- {
- DataSourceMetaData * childMeta = fields.item(column).queryChildMeta();
- if (childMeta)
- return new NestedDataSource(*childMeta, len, data);
- return NULL;
- }
- bool DataSourceMetaData::supportsRandomSeek() const
- {
- return randomIsOk;
- }
- void DataSourceMetaData::serialize(MemoryBuffer & buffer) const
- {
- //NB: Update NullDataSourceMeta if this changes....
- buffer.append(numFieldsToIgnore);
- buffer.append(randomIsOk);
- buffer.append(hasMixedContent);
- buffer.append(isStoredFixedWidth);
- buffer.append(minRecordSize);
- buffer.append(keyedSize);
- buffer.append(maxRecordSize);
- unsigned numFields = fields.ordinality();
- buffer.append(numFields);
- for (unsigned idx=0; idx < numFields; idx++)
- {
- fields.item(idx).serialize(buffer);
- }
- }
- size32_t DataSourceMetaData::getRecordSize(const void *rec)
- {
- if (isStoredFixedWidth)
- return minRecordSize;
- if (!rec)
- return maxRecordSize;
- const byte * data = (const byte *)rec;
- unsigned curOffset = 0;
- unsigned bitsRemaining = 0;
- unsigned max = fields.ordinality() - numVirtualFields;
- for (unsigned idx=0; idx < max; idx++)
- {
- ITypeInfo & type = *fields.item(idx).type;
- unsigned size = type.getSize();
- if (size == UNKNOWN_LENGTH)
- {
- const byte * cur = data + curOffset;
- switch (type.getTypeCode())
- {
- case type_data:
- case type_string:
- case type_table:
- case type_groupedtable:
- size = *((unsigned *)cur) + sizeof(unsigned);
- break;
- case type_set:
- size = *((unsigned *)(cur + sizeof(bool))) + sizeof(unsigned) + sizeof(bool);
- break;
- case type_qstring:
- size = rtlQStrSize(*((unsigned *)cur)) + sizeof(unsigned);
- break;
- case type_unicode:
- size = *((unsigned *)cur)*2 + sizeof(unsigned);
- break;
- case type_utf8:
- size = sizeof(unsigned) + rtlUtf8Size(*(unsigned *)cur, cur+sizeof(unsigned));
- break;
- case type_varstring:
- size = strlen((char *)cur)+1;
- break;
- case type_varunicode:
- size = (rtlUnicodeStrlen((UChar *)cur)+1)*2;
- break;
- case type_packedint:
- size = rtlGetPackedSize(cur);
- break;
- default:
- UNIMPLEMENTED;
- }
- }
- if (type.getTypeCode() == type_bitfield)
- {
- unsigned thisBits = type.getBitSize();
- if (thisBits > bitsRemaining)
- {
- size = type.queryChildType()->getSize();
- bitsRemaining = size * 8;
- }
- else
- size = 0;
- bitsRemaining -= thisBits;
- }
- else
- bitsRemaining = 0;
- curOffset += size;
- }
- return curOffset;
- }
- size32_t DataSourceMetaData::getFixedSize() const
- {
- if (isStoredFixedWidth)
- return minRecordSize;
- return 0;
- }
- size32_t DataSourceMetaData::getMinRecordSize() const
- {
- return minRecordSize;
- }
- IFvDataSourceMetaData * deserializeDataSourceMeta(MemoryBuffer & in)
- {
- return new DataSourceMetaData(in);
- }
- //---------------------------------------------------------------------------
- RowBlock::RowBlock(MemoryBuffer & _buffer, __int64 _start, __int64 _startOffset)
- {
- buffer.swapWith(_buffer);
- start = _start;
- startOffset = _startOffset;
- numRows = 0;
- }
- RowBlock::RowBlock(__int64 _start, __int64 _startOffset)
- {
- start = _start;
- startOffset = _startOffset;
- numRows = 0;
- }
- void RowBlock::getNextStoredOffset(__int64 & row, offset_t & offset)
- {
- row = getNextRow();
- offset = startOffset + buffer.length();
- }
- FixedRowBlock::FixedRowBlock(MemoryBuffer & _buffer, __int64 _start, __int64 _startOffset, size32_t _fixedRecordSize) : RowBlock(_buffer, _start, _startOffset)
- {
- if (_fixedRecordSize == 0) _fixedRecordSize = 1;
- fixedRecordSize = _fixedRecordSize;
- numRows = buffer.length() / fixedRecordSize;
- }
- const void * FixedRowBlock::fetchRow(__int64 offset, size32_t & len)
- {
- __int64 maxOffset = startOffset + buffer.length();
- if (offset < startOffset || offset >= maxOffset)
- return NULL;
- len = fixedRecordSize;
- return buffer.toByteArray() + (offset - startOffset);
- }
- const void * FixedRowBlock::getRow(__int64 row, size32_t & len, unsigned __int64 & rowOffset)
- {
- if (row < start || row >= start + numRows)
- return NULL;
- unsigned index = (unsigned)(row - start);
- unsigned blockOffset = index * fixedRecordSize;
- len = fixedRecordSize;
- rowOffset = startOffset + blockOffset;
- return buffer.toByteArray() + blockOffset;
- }
- VariableRowBlock::VariableRowBlock(MemoryBuffer & _buffer, __int64 _start, __int64 _startOffset, IRecordSizeEx * recordSize, bool isLast) : RowBlock(_buffer, _start, _startOffset)
- {
- const char * buff = buffer.toByteArray();
- unsigned cur = 0;
- unsigned max = buffer.length();
- unsigned maxCur = max;
- if (!isLast)
- maxCur -= recordSize->getRecordSize(NULL);
- while (cur < maxCur)
- {
- rowIndex.append(cur);
- cur += recordSize->getRecordSize(max-cur, buff + cur);
- if (cur > max)
- throwError(FVERR_RowTooLarge);
- }
- buffer.setLength(cur);
- rowIndex.append(cur);
- numRows = rowIndex.ordinality()-1;
- }
- VariableRowBlock::VariableRowBlock(MemoryBuffer & inBuffer, __int64 _start) : RowBlock(_start, 0)
- {
- inBuffer.read(numRows);
- for (unsigned row = 0; row < numRows; row++)
- {
- unsigned thisLength;
- rowIndex.append(buffer.length());
- inBuffer.read(thisLength);
- buffer.append(thisLength, inBuffer.readDirect(thisLength));
- }
- rowIndex.append(buffer.length());
- }
- const void * VariableRowBlock::fetchRow(__int64 offset, size32_t & len)
- {
- __int64 maxOffset = startOffset + buffer.length();
- if (offset < startOffset || offset >= maxOffset)
- return NULL;
- size32_t rowOffset = (size32_t)(offset - startOffset);
- unsigned pos = rowIndex.find(rowOffset);
- if (pos == NotFound)
- return NULL;
- len = rowIndex.item(pos+1)-rowOffset;
- return buffer.toByteArray() + rowOffset;
- }
- const void * VariableRowBlock::getRow(__int64 row, size32_t & len, unsigned __int64 & rowOffset)
- {
- if (row < start || row >= start + numRows)
- return NULL;
- unsigned index = (unsigned)(row - start);
- unsigned blockOffset = rowIndex.item(index);
- len = rowIndex.item(index+1) - blockOffset;
- rowOffset = startOffset + blockOffset;
- return buffer.toByteArray() + blockOffset;
- }
- //---------------------------------------------------------------------------
- offset_t calculateNextOffset(const char * data, unsigned len)
- {
- offset_t offset = *(offset_t *)(data + len - sizeof(offset_t) - sizeof(unsigned short));
- return offset + *(unsigned short*)(data + len - sizeof(unsigned short));
- }
- void FilePosFixedRowBlock::getNextStoredOffset(__int64 & row, offset_t & offset)
- {
- row = start + numRows;
- offset = calculateNextOffset(buffer.toByteArray(), buffer.length());
- }
- void FilePosVariableRowBlock::getNextStoredOffset(__int64 & row, offset_t & offset)
- {
- row = start + numRows;
- offset = calculateNextOffset(buffer.toByteArray(), buffer.length());
- }
- //---------------------------------------------------------------------------
- static int rowCacheId;
- void RowCache::addRowsOwn(RowBlock * rows)
- {
- if (allRows.ordinality() == MaxBlocksCached)
- makeRoom();
- unsigned newPos = getInsertPosition(rows->getStartRow());
- allRows.add(*rows, newPos);
- ages.add(++rowCacheId, newPos);
- }
- bool RowCache::getCacheRow(__int64 row, RowLocation & location)
- {
- unsigned numRows = allRows.ordinality();
- if (numRows == 0)
- return false;
- const RowBlock & first = allRows.item(0);
- if (row < first.getStartRow())
- {
- location.bestRow = 0;
- location.bestOffset = 0;
- return false;
- }
- unsigned best = getBestRow(row);
- ages.replace(++rowCacheId, best);
- RowBlock & cur = allRows.item(best);
- location.matchRow = cur.getRow(row, location.matchLength, location.bestOffset);
- if (location.matchRow)
- return true;
- if (location.bestRow < cur.getNextRow())
- {
- cur.getNextStoredOffset(location.bestRow, location.bestOffset);
- }
- return false;
- }
- //Find the rowBlock that contains the expected row.
- //Return the *previous* RowBlock if no match is found.
- unsigned RowCache::getBestRow(__int64 row)
- {
- unsigned max = allRows.ordinality();
- int start = 0;
- int end = max;
- while (end - start > 1)
- {
- int mid = (start + end) >> 1;
- RowBlock & cur = allRows.item(mid);
- if (row >= cur.getStartRow())
- start = mid;
- else
- end = mid;
- }
- assertex(row >= allRows.item(start).getStartRow());
- assertex(start != max);
- return start;
- }
- unsigned RowCache::getInsertPosition(__int64 row)
- {
- unsigned max = allRows.ordinality();
- int start = 0;
- int end = max;
- while (end - start > 1)
- {
- int mid = (start + end) >> 1;
- RowBlock & cur = allRows.item(mid);
- if (row >= cur.getStartRow())
- start = mid;
- else
- end = mid;
- }
- if (start != max)
- {
- if (row >= allRows.item(start).getStartRow())
- start++;
- }
- assertex(start == max || (row < allRows.item(start).getStartRow()));
- return start;
- }
- void RowCache::makeRoom()
- {
- #if 0
- //For testing the caching by throwing away random blocks
- while (allRows.ordinality() > MinBlocksCached)
- {
- unsigned index = getRandom() % allRows.ordinality();
- allRows.remove(index);
- ages.remove(index);
- }
- return;
- #endif
- unsigned numToFree = allRows.ordinality() - MinBlocksCached;
- RowBlock * * oldestRow = new RowBlock * [numToFree];
- __int64 * oldestAge = new __int64[numToFree];
- unsigned numGot = 0;
- ForEachItemIn(idx, ages)
- {
- __int64 curAge = ages.item(idx);
- unsigned compare = numGot;
- while (compare != 0)
- {
- if (curAge >= oldestAge[compare-1])
- break;
- compare--;
- }
- if (compare < numToFree)
- {
- unsigned copySize = numGot - compare;
- if (numGot == numToFree)
- copySize--; //NB: Cannot go negative because compare < numToFree, numToFree == numGot => compare < numGot
- if (copySize)
- {
- memmove(oldestAge + compare + 1, oldestAge + compare, copySize * sizeof(*oldestAge));
- memmove(oldestRow + compare + 1, oldestRow + compare, copySize * sizeof(*oldestRow));
- }
- oldestAge[compare] = curAge;
- oldestRow[compare] = &allRows.item(idx);
- if (numGot != numToFree)
- numGot++;
- }
- }
- unsigned max = allRows.ordinality();
- unsigned i;
- for (i = 0; i < max; )
- {
- for (unsigned j = 0; j < numGot; j++)
- {
- if (oldestRow[j] == &allRows.item(i))
- {
- allRows.remove(i);
- ages.remove(i);
- max--;
- goto testNext;
- }
- }
- i++;
- testNext: ;
- }
- delete [] oldestRow;
- delete [] oldestAge;
- }
- //---------------------------------------------------------------------------
- FVDataSource::FVDataSource()
- {
- transformer = NULL;
- extraFieldsSize = 0;
- openCount = 0;
- appendFileposition = false;
- }
- FVDataSource::~FVDataSource()
- {
- //ensure all refs into the dll are cleared before it is unloaded
- returnedRecordSize.clear();
- }
- void FVDataSource::addFileposition()
- {
- appendFileposition = true;
- transformedMeta->addFileposition(); // This may modify the other metas as well!
- }
- void FVDataSource::copyRow(MemoryBuffer & out, const void * src, size32_t length)
- {
- if (transformer)
- {
- unsigned curLen = out.length();
- size32_t maxSize = transformedMeta->getMaxRecordSize();
- void * target = out.reserve(maxSize);
- //MORE: won't cope with dynamic maxlengths
- RtlStaticRowBuilder rowBuilder(target, maxSize);
- unsigned copied = transformer(rowBuilder, (const byte *)src);
- out.rewrite(curLen + copied);
- }
- else
- out.append(length, src);
- }
- bool FVDataSource::fetchRow(MemoryBuffer & out, __int64 offset)
- {
- if (!transformer)
- return fetchRawRow(out, offset);
- MemoryBuffer temp;
- if (fetchRowData(temp, offset))
- {
- copyRow(out, temp.toByteArray(), temp.length());
- if (appendFileposition)
- out.append(offset);
- return true;
- }
- return false;
- }
- bool FVDataSource::fetchRawRow(MemoryBuffer & out, __int64 offset)
- {
- if (fetchRowData(out, offset))
- {
- if (appendFileposition)
- out.append(offset);
- return true;
- }
- return false;
- }
- bool FVDataSource::getRow(MemoryBuffer & out, __int64 row)
- {
- size32_t length;
- const void * data;
- unsigned __int64 offset = 0;
- if (getRowData(row, length, data, offset))
- {
- copyRow(out, data, length);
- if (appendFileposition)
- out.append(offset);
- return true;
- }
- return false;
- }
- bool FVDataSource::getRawRow(MemoryBuffer & out, __int64 row)
- {
- size32_t length;
- const void * data;
- unsigned __int64 offset = 0;
- if (getRowData(row, length, data, offset))
- {
- out.append(length-extraFieldsSize, data);
- if (appendFileposition)
- out.append(offset);
- return true;
- }
- return false;
- }
- void FVDataSource::loadDll(const char * wuid)
- {
- //MORE: This code should be commoned up and available in the work unit code or something...
- Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
- Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid);
- //Plugins should already be loaded when they were registered with the ViewTransformerRegistry
- //Something like the following code could be used to check the plugin version...
- #if 0
- Owned<IConstWUPluginIterator> plugins = &wu->getPlugins();
- SafePluginMap * map = NULL;
- ForEach(*plugins)
- {
- IConstWUPlugin &thisplugin = plugins->query();
- SCMStringBuffer name, version;
- thisplugin.getPluginName(name);
- thisplugin.getPluginVersion(version);
- Owned<ILoadedDllEntry> loadedPlugin = map->getPluginDll(name.str(), version.str(), true);
- if (!loadedPlugin)
- break;
- }
- #endif
- Owned<IConstWUQuery> q = wu->getQuery();
- SCMStringBuffer dllname;
- q->getQueryDllName(dllname);
- // MORE - leaks....
- loadedDll.setown(queryDllServer().loadDll(dllname.str(), DllLocationAnywhere));
- }
- IFvDataSourceMetaData * FVDataSource::queryMetaData()
- {
- return transformedMeta;
- }
- bool FVDataSource::setReturnedInfoFromResult()
- {
- SCMStringBuffer s;
- wuResult->getResultEclSchema(s);
- returnedRecord.setown(parseQuery(s.str()));
- if (!returnedRecord)
- throw MakeStringException(FVERR_CouldNotProcessSchema, "Could not process result schema [%s]", s.str());
- bool isKey = false;
- bool isGrouped = false; // this isn't strictly true...it could be true for an internal result, but no current flag to test
- returnedMeta.setown(new DataSourceMetaData(returnedRecord, 0, true, isGrouped, 0));
- transformedRecord.setown(getFileViewerRecord(returnedRecord, isKey));
- if (!transformedRecord)
- {
- //No transformations needed, so don't need to loaded the dll containing the transform functions etc.
- transformedRecord.set(returnedRecord);
- returnedRecordSize.set(returnedMeta);
- }
- else
- {
- loadDll(wuid);
- s.clear();
- wuResult->getResultRecordSizeEntry(s);
- if (s.length())
- {
- typedef IRecordSize * (* recSizeFunc)();
- recSizeFunc func = (recSizeFunc)loadedDll->getEntry(s.str());
- Owned<IRecordSize> createdRecordSize = func();
- returnedRecordSize.setown(new RecordSizeToEx(createdRecordSize));
- }
- s.clear();
- wuResult->getResultTransformerEntry(s);
- if (s.length())
- transformer = (rowTransformFunction)loadedDll->getEntry(s.str());
- }
- transformedMeta.setown(new DataSourceMetaData(transformedRecord, 0, true, isGrouped, 0));
- return (returnedRecordSize != NULL);
- }
- //---------------------------------------------------------------------------
- __int64 PagedDataSource::numRows(bool force)
- {
- if (force && (totalRows == UNKNOWN_NUM_ROWS))
- {
- //MORE: Need to go and work it out - however painful...
- }
- return totalRows;
- }
- bool PagedDataSource::getRowData(__int64 row, size32_t & length, const void * & data, unsigned __int64 & offset)
- {
- if ((row < 0) || ((unsigned __int64)row > totalRows))
- return false;
- RowLocation location;
- loop
- {
- if (cache.getCacheRow(row, location))
- {
- length = location.matchLength;
- data = location.matchRow;
- offset = location.bestOffset;
- return true;
- }
- improveLocation(row, location);
- if (!loadBlock(location.bestRow, location.bestOffset))
- return false;
- }
- }
- void PagedDataSource::improveLocation(__int64 row, RowLocation & location)
- {
- }
- //---------------------------------------------------------------------------
- NestedDataSource::NestedDataSource(DataSourceMetaData & meta, unsigned len, const void * data)
- {
- returnedMeta.set(&meta);
- returnedRecordSize.set(returnedMeta);
- transformedMeta.set(returnedMeta);
- totalSize = len;
- MemoryBuffer temp;
- temp.append(len, data);
- if (returnedMeta->isFixedSize())
- rows.setown(new FixedRowBlock(temp, 0, 0, returnedMeta->fixedSize()));
- else
- rows.setown(new VariableRowBlock(temp, 0, 0, returnedRecordSize, true));
- }
- bool NestedDataSource::init()
- {
- return true;
- }
- __int64 NestedDataSource::numRows(bool force)
- {
- return rows->getNextRow() - rows->getStartRow();
- }
- bool NestedDataSource::getRowData(__int64 row, size32_t & length, const void * & data, unsigned __int64 & offset)
- {
- data = rows->getRow(row, length, offset);
- return (data != NULL);
- }
- //---------------------------------------------------------------------------
- NullDataSource::NullDataSource(IHqlExpression * _record, bool _isGrouped, unsigned _keyedSize)
- : meta(_record, 0, true, _isGrouped, _keyedSize)
- {
- }
- FailureDataSource::FailureDataSource(IHqlExpression * _record, IException * _error, bool _isGrouped, unsigned _keyedSize)
- : NullDataSource(_record, _isGrouped, _keyedSize), error(_error)
- {
- }
- //---------------------------------------------------------------------------
- IHqlExpression * parseQuery(const char * text)
- {
- MultiErrorReceiver errs;
- OwnedHqlExpr ret = ::parseQuery(text, &errs);
- if (errs.errCount() == 0)
- return ret.getClear();
- for (unsigned i=0; i < errs.errCount(); i++)
- {
- StringBuffer msg;
- PrintLog("%d %s", errs.item(i)->getLine(), errs.item(i)->errorMessage(msg).str());
- }
- return NULL;
- }
- IFvDataSourceMetaData * createMetaData(IConstWUResult * wuResult)
- {
- SCMStringBuffer s;
- wuResult->getResultEclSchema(s);
- OwnedHqlExpr record = parseQuery(s.str());
- if (!record)
- throw MakeStringException(FVERR_CouldNotProcessSchema, "Could not process result schema [%s]", s.str());
- OwnedHqlExpr simplifiedRecord = getFileViewerRecord(record, false);
- bool isGrouped = false; // more not sure this is strictly true...
- if (!simplifiedRecord)
- return new DataSourceMetaData(record, 0, true, isGrouped, 0);
- return new DataSourceMetaData(simplifiedRecord, 0, true, isGrouped, 0);
- }
|