[data views] deprecate indexPattern exports, provide dataView exports (#109987)

* first pass at renaming exports

* type fixes

* fix jest test

* look for correct error type

* remove transitional error

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
Matthew Kime 2021-08-30 18:04:03 -05:00 committed by GitHub
parent 88f955621d
commit 75c6afe112
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 257 additions and 185 deletions

View file

@ -10,4 +10,11 @@ export { buildEsQuery, EsQueryConfig } from './build_es_query';
export { buildQueryFromFilters } from './from_filters';
export { luceneStringToDsl } from './lucene_string_to_dsl';
export { decorateQuery } from './decorate_query';
export { IndexPatternBase, IndexPatternFieldBase, IFieldSubType, BoolQuery } from './types';
export {
IndexPatternBase,
IndexPatternFieldBase,
IFieldSubType,
BoolQuery,
DataViewBase,
DataViewFieldBase,
} from './types';

View file

@ -21,7 +21,7 @@ export interface IFieldSubType {
* A base interface for an index pattern field
* @public
*/
export interface IndexPatternFieldBase {
export interface DataViewFieldBase {
name: string;
/**
* Kibana field type
@ -40,16 +40,26 @@ export interface IndexPatternFieldBase {
scripted?: boolean;
}
/**
* @deprecated Use DataViewField instead. All index pattern interfaces were renamed.
*/
export type IndexPatternFieldBase = DataViewFieldBase;
/**
* A base interface for an index pattern
* @public
*/
export interface IndexPatternBase {
fields: IndexPatternFieldBase[];
export interface DataViewBase {
fields: DataViewFieldBase[];
id?: string;
title?: string;
}
/**
* @deprecated Use DataViewBase instead. All index pattern interfaces were renamed.
*/
export type IndexPatternBase = DataViewBase;
export interface BoolQuery {
must: estypes.QueryDslQueryContainer[];
must_not: estypes.QueryDslQueryContainer[];

View file

@ -10,7 +10,13 @@ export const DEFAULT_QUERY_LANGUAGE = 'kuery';
export const KIBANA_USER_QUERY_LANGUAGE_KEY = 'kibana.userQueryLanguage';
/** @public **/
export const INDEX_PATTERN_SAVED_OBJECT_TYPE = 'index-pattern';
export const DATA_VIEW_SAVED_OBJECT_TYPE = 'index-pattern';
/**
* @deprecated Use DATA_VIEW_SAVED_OBJECT_TYPE. All index pattern interfaces were renamed.
*/
export const INDEX_PATTERN_SAVED_OBJECT_TYPE = DATA_VIEW_SAVED_OBJECT_TYPE;
export type ValueSuggestionsMethod = 'terms_enum' | 'terms_agg';

View file

@ -22,4 +22,4 @@ export * from './exports';
* @removeBy 8.1
*/
export { IndexPatternAttributes } from './types';
export { IndexPatternAttributes, DataViewAttributes } from './types';

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
export class DuplicateIndexPatternError extends Error {
export class DuplicateDataViewError extends Error {
constructor(message: string) {
super(message);
this.name = 'DuplicateIndexPatternError';

View file

@ -8,8 +8,8 @@
import { i18n } from '@kbn/i18n';
import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common';
import { IndexPatternsContract } from '../index_patterns';
import { IndexPatternSpec } from '..';
import { DataViewsContract } from '../index_patterns';
import { DataViewSpec } from '..';
import { SavedObjectReference } from '../../../../../core/types';
const name = 'indexPatternLoad';
@ -17,7 +17,7 @@ const type = 'index_pattern';
export interface IndexPatternExpressionType {
type: typeof type;
value: IndexPatternSpec;
value: DataViewSpec;
}
type Input = null;
@ -29,7 +29,7 @@ interface Arguments {
/** @internal */
export interface IndexPatternLoadStartDependencies {
indexPatterns: IndexPatternsContract;
indexPatterns: DataViewsContract;
}
export type IndexPatternLoadExpressionFunctionDefinition = ExpressionFunctionDefinition<

View file

@ -8,24 +8,22 @@
import { findIndex } from 'lodash';
import { IFieldType } from './types';
import { IndexPatternField } from './index_pattern_field';
import { FieldSpec, IndexPatternFieldMap } from '../types';
import { IndexPattern } from '../index_patterns';
import { DataViewField } from './index_pattern_field';
import { FieldSpec, DataViewFieldMap } from '../types';
import { DataView } from '../index_patterns';
type FieldMap = Map<IndexPatternField['name'], IndexPatternField>;
type FieldMap = Map<DataViewField['name'], DataViewField>;
export interface IIndexPatternFieldList extends Array<IndexPatternField> {
export interface IIndexPatternFieldList extends Array<DataViewField> {
add(field: FieldSpec): void;
getAll(): IndexPatternField[];
getByName(name: IndexPatternField['name']): IndexPatternField | undefined;
getByType(type: IndexPatternField['type']): IndexPatternField[];
getAll(): DataViewField[];
getByName(name: DataViewField['name']): DataViewField | undefined;
getByType(type: DataViewField['type']): DataViewField[];
remove(field: IFieldType): void;
removeAll(): void;
replaceAll(specs: FieldSpec[]): void;
update(field: FieldSpec): void;
toSpec(options?: {
getFormatterForField?: IndexPattern['getFormatterForField'];
}): IndexPatternFieldMap;
toSpec(options?: { getFormatterForField?: DataView['getFormatterForField'] }): DataViewFieldMap;
}
// extending the array class and using a constructor doesn't work well
@ -35,11 +33,11 @@ export const fieldList = (
specs: FieldSpec[] = [],
shortDotsEnable = false
): IIndexPatternFieldList => {
class FldList extends Array<IndexPatternField> implements IIndexPatternFieldList {
class FldList extends Array<DataViewField> implements IIndexPatternFieldList {
private byName: FieldMap = new Map();
private groups: Map<IndexPatternField['type'], FieldMap> = new Map();
private setByName = (field: IndexPatternField) => this.byName.set(field.name, field);
private setByGroup = (field: IndexPatternField) => {
private groups: Map<DataViewField['type'], FieldMap> = new Map();
private setByName = (field: DataViewField) => this.byName.set(field.name, field);
private setByGroup = (field: DataViewField) => {
if (typeof this.groups.get(field.type) === 'undefined') {
this.groups.set(field.type, new Map());
}
@ -53,12 +51,12 @@ export const fieldList = (
}
public readonly getAll = () => [...this.byName.values()];
public readonly getByName = (name: IndexPatternField['name']) => this.byName.get(name);
public readonly getByType = (type: IndexPatternField['type']) => [
public readonly getByName = (name: DataViewField['name']) => this.byName.get(name);
public readonly getByType = (type: DataViewField['type']) => [
...(this.groups.get(type) || new Map()).values(),
];
public readonly add = (field: FieldSpec) => {
const newField = new IndexPatternField({ ...field, shortDotsEnable });
const newField = new DataViewField({ ...field, shortDotsEnable });
this.push(newField);
this.setByName(newField);
this.setByGroup(newField);
@ -73,7 +71,7 @@ export const fieldList = (
};
public readonly update = (field: FieldSpec) => {
const newField = new IndexPatternField(field);
const newField = new DataViewField(field);
const index = this.findIndex((f) => f.name === newField.name);
this.splice(index, 1, newField);
this.setByName(newField);
@ -95,10 +93,10 @@ export const fieldList = (
public toSpec({
getFormatterForField,
}: {
getFormatterForField?: IndexPattern['getFormatterForField'];
getFormatterForField?: DataView['getFormatterForField'];
} = {}) {
return {
...this.reduce<IndexPatternFieldMap>((collector, field) => {
...this.reduce<DataViewFieldMap>((collector, field) => {
collector[field.name] = field.toSpec({ getFormatterForField });
return collector;
}, {}),

View file

@ -6,15 +6,17 @@
* Side Public License, v 1.
*/
/* eslint-disable max-classes-per-file */
import { KbnFieldType, getKbnFieldType, castEsToKbnFieldTypeName } from '@kbn/field-types';
import type { RuntimeField } from '../types';
import { KbnFieldType, getKbnFieldType, castEsToKbnFieldTypeName } from '../../kbn_field_types';
import { KBN_FIELD_TYPES } from '../../kbn_field_types/types';
import type { IFieldType } from './types';
import { FieldSpec, IndexPattern } from '../..';
import { FieldSpec, DataView } from '../..';
import { shortenDottedString } from '../../utils';
/** @public */
export class IndexPatternField implements IFieldType {
export class DataViewField implements IFieldType {
readonly spec: FieldSpec;
// not writable or serialized
private readonly kbnFieldType: KbnFieldType;
@ -182,7 +184,7 @@ export class IndexPatternField implements IFieldType {
public toSpec({
getFormatterForField,
}: {
getFormatterForField?: IndexPattern['getFormatterForField'];
getFormatterForField?: DataView['getFormatterForField'];
} = {}): FieldSpec {
return {
count: this.count,
@ -205,3 +207,8 @@ export class IndexPatternField implements IFieldType {
};
}
}
/**
* @deprecated Use DataViewField instead. All index pattern interfaces were renamed.
*/
export class IndexPatternField extends DataViewField {}

View file

@ -5,14 +5,14 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { IndexPatternFieldBase } from '@kbn/es-query';
import { FieldSpec, IndexPattern } from '../..';
import { DataViewFieldBase } from '@kbn/es-query';
import { FieldSpec, DataView } from '../..';
/**
* @deprecated Use {@link IndexPatternField}
* @removeBy 8.1
*/
export interface IFieldType extends IndexPatternFieldBase {
export interface IFieldType extends DataViewFieldBase {
count?: number;
// esTypes might be undefined on old index patterns that have not been refreshed since we added
// this prop. It is also undefined on scripted fields.
@ -26,5 +26,5 @@ export interface IFieldType extends IndexPatternFieldBase {
displayName?: string;
customLabel?: string;
format?: any;
toSpec?: (options?: { getFormatterForField?: IndexPattern['getFormatterForField'] }) => FieldSpec;
toSpec?: (options?: { getFormatterForField?: DataView['getFormatterForField'] }) => FieldSpec;
}

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { getFilterableKbnTypeNames } from '../../kbn_field_types';
import { getFilterableKbnTypeNames } from '@kbn/field-types';
import { IFieldType } from './types';
const filterableTypes = getFilterableKbnTypeNames();

View file

@ -9,7 +9,17 @@
export * from './constants';
export * from './fields';
export * from './types';
export { IndexPatternsService, IndexPatternsContract } from './index_patterns';
export type { IndexPattern, IndexPatternListItem } from './index_patterns';
export {
IndexPatternsService,
IndexPatternsContract,
DataViewsService,
DataViewsContract,
} from './index_patterns';
export type {
IndexPattern,
IndexPatternListItem,
DataView,
DataViewListItem,
} from './index_patterns';
export * from './errors';
export * from './expressions';

View file

@ -6,18 +6,18 @@
* Side Public License, v 1.
*/
import { IndexPattern } from './index_pattern';
import { DataView } from './index_pattern';
export interface PatternCache {
get: (id: string) => Promise<IndexPattern> | undefined;
set: (id: string, value: Promise<IndexPattern>) => Promise<IndexPattern>;
export interface DataViewCache {
get: (id: string) => Promise<DataView> | undefined;
set: (id: string, value: Promise<DataView>) => Promise<DataView>;
clear: (id: string) => void;
clearAll: () => void;
}
export function createIndexPatternCache(): PatternCache {
export function createDataViewCache(): DataViewCache {
const vals: Record<string, any> = {};
const cache: PatternCache = {
const cache: DataViewCache = {
get: (id: string) => {
return vals[id];
},

View file

@ -7,12 +7,12 @@
*/
import { includes } from 'lodash';
import { IndexPatternsContract } from './index_patterns';
import { DataViewsContract } from './index_patterns';
import { UiSettingsCommon } from '../types';
export type EnsureDefaultIndexPattern = () => Promise<unknown> | undefined;
export type EnsureDefaultDataView = () => Promise<unknown> | undefined;
export const createEnsureDefaultIndexPattern = (
export const createEnsureDefaultDataView = (
uiSettings: UiSettingsCommon,
onRedirectNoIndexPattern: () => Promise<unknown> | void
) => {
@ -20,7 +20,7 @@ export const createEnsureDefaultIndexPattern = (
* Checks whether a default index pattern is set and exists and defines
* one otherwise.
*/
return async function ensureDefaultIndexPattern(this: IndexPatternsContract) {
return async function ensureDefaultDataView(this: DataViewsContract) {
const patterns = await this.getIds();
let defaultId = await uiSettings.get('defaultIndex');
let defined = !!defaultId;

View file

@ -7,12 +7,12 @@
*/
import _ from 'lodash';
import { IndexPattern } from './index_pattern';
import { DataView } from './index_pattern';
// Takes a hit, merges it with any stored/scripted fields, and with the metaFields
// returns a flattened version
function flattenHit(indexPattern: IndexPattern, hit: Record<string, any>, deep: boolean) {
function flattenHit(indexPattern: DataView, hit: Record<string, any>, deep: boolean) {
const flat = {} as Record<string, any>;
// recursively merge _source
@ -104,11 +104,7 @@ function decorateFlattenedWrapper(hit: Record<string, any>, metaFields: Record<s
*
* @internal
*/
export function flattenHitWrapper(
indexPattern: IndexPattern,
metaFields = {},
cache = new WeakMap()
) {
export function flattenHitWrapper(indexPattern: DataView, metaFields = {}, cache = new WeakMap()) {
return function cachedFlatten(hit: Record<string, any>, deep = false) {
const decorateFlattened = decorateFlattenedWrapper(hit, metaFields);
const cached = cache.get(hit);

View file

@ -7,7 +7,7 @@
*/
import _ from 'lodash';
import { IndexPattern } from './index_pattern';
import { DataView } from './index_pattern';
import { FieldFormatsContentType } from '../../../../field_formats/common';
const formattedCache = new WeakMap();
@ -15,7 +15,7 @@ const partialFormattedCache = new WeakMap();
// Takes a hit, merges it with any stored/scripted fields, and with the metaFields
// returns a formatted version
export function formatHitProvider(indexPattern: IndexPattern, defaultFormat: any) {
export function formatHitProvider(indexPattern: DataView, defaultFormat: any) {
function convert(
hit: Record<string, any>,
val: any,

View file

@ -6,22 +6,24 @@
* Side Public License, v 1.
*/
/* eslint-disable max-classes-per-file */
import _, { each, reject } from 'lodash';
import { FieldAttrs, FieldAttrSet, IndexPatternAttributes } from '../..';
import { castEsToKbnFieldTypeName } from '@kbn/field-types';
import { FieldAttrs, FieldAttrSet, DataViewAttributes } from '../..';
import type { RuntimeField } from '../types';
import { DuplicateField } from '../../../../kibana_utils/common';
import { ES_FIELD_TYPES, KBN_FIELD_TYPES, IIndexPattern, IFieldType } from '../../../common';
import { IndexPatternField, IIndexPatternFieldList, fieldList } from '../fields';
import { DataViewField, IIndexPatternFieldList, fieldList } from '../fields';
import { formatHitProvider } from './format_hit';
import { flattenHitWrapper } from './flatten_hit';
import { FieldFormatsStartCommon, FieldFormat } from '../../../../field_formats/common';
import { IndexPatternSpec, TypeMeta, SourceFilter, IndexPatternFieldMap } from '../types';
import { DataViewSpec, TypeMeta, SourceFilter, DataViewFieldMap } from '../types';
import { SerializedFieldFormat } from '../../../../expressions/common';
import { castEsToKbnFieldTypeName } from '../../kbn_field_types';
interface IndexPatternDeps {
spec?: IndexPatternSpec;
interface DataViewDeps {
spec?: DataViewSpec;
fieldFormats: FieldFormatsStartCommon;
shortDotsEnable?: boolean;
metaFields?: string[];
@ -41,7 +43,7 @@ interface SavedObjectBody {
type FormatFieldFn = (hit: Record<string, any>, fieldName: string) => any;
export class IndexPattern implements IIndexPattern {
export class DataView implements IIndexPattern {
public id?: string;
public title: string = '';
public fieldFormatMap: Record<string, any>;
@ -49,7 +51,7 @@ export class IndexPattern implements IIndexPattern {
* Only used by rollup indices, used by rollup specific endpoint to load field list
*/
public typeMeta?: TypeMeta;
public fields: IIndexPatternFieldList & { toSpec: () => IndexPatternFieldMap };
public fields: IIndexPatternFieldList & { toSpec: () => DataViewFieldMap };
public timeFieldName: string | undefined;
/**
* @deprecated Used by time range index patterns
@ -84,12 +86,7 @@ export class IndexPattern implements IIndexPattern {
*/
public readonly allowNoIndex: boolean = false;
constructor({
spec = {},
fieldFormats,
shortDotsEnable = false,
metaFields = [],
}: IndexPatternDeps) {
constructor({ spec = {}, fieldFormats, shortDotsEnable = false, metaFields = [] }: DataViewDeps) {
// set dependencies
this.fieldFormats = fieldFormats;
// set config
@ -206,7 +203,7 @@ export class IndexPattern implements IIndexPattern {
/**
* Create static representation of index pattern
*/
public toSpec(): IndexPatternSpec {
public toSpec(): DataViewSpec {
return {
id: this.id,
version: this.version,
@ -311,7 +308,7 @@ export class IndexPattern implements IIndexPattern {
return this.fields.getByName(this.timeFieldName);
}
getFieldByName(name: string): IndexPatternField | undefined {
getFieldByName(name: string): DataViewField | undefined {
if (!this.fields || !this.fields.getByName) return undefined;
return this.fields.getByName(name);
}
@ -323,7 +320,7 @@ export class IndexPattern implements IIndexPattern {
/**
* Returns index pattern as saved object body for saving
*/
getAsSavedObjectBody(): IndexPatternAttributes {
getAsSavedObjectBody(): DataViewAttributes {
const fieldFormatMap = _.isEmpty(this.fieldFormatMap)
? undefined
: JSON.stringify(this.fieldFormatMap);
@ -349,9 +346,7 @@ export class IndexPattern implements IIndexPattern {
* Provide a field, get its formatter
* @param field
*/
getFormatterForField(
field: IndexPatternField | IndexPatternField['spec'] | IFieldType
): FieldFormat {
getFormatterForField(field: DataViewField | DataViewField['spec'] | IFieldType): FieldFormat {
const fieldFormat = this.getFormatterForFieldNoDefault(field.name);
if (fieldFormat) {
return fieldFormat;
@ -490,3 +485,8 @@ export class IndexPattern implements IIndexPattern {
delete this.fieldFormatMap[fieldName];
};
}
/**
* @deprecated Use DataView instead. All index pattern interfaces were renamed.
*/
export class IndexPattern extends DataView {}

View file

@ -7,7 +7,7 @@
*/
import { defaults } from 'lodash';
import { IndexPatternsService, IndexPattern } from '.';
import { DataViewsService, DataView } from '.';
import { fieldFormatsMock } from '../../../../field_formats/common/mocks';
import { UiSettingsCommon, SavedObjectsClientCommon, SavedObject } from '../types';
@ -47,7 +47,7 @@ const savedObject = {
};
describe('IndexPatterns', () => {
let indexPatterns: IndexPatternsService;
let indexPatterns: DataViewsService;
let savedObjectsClient: SavedObjectsClientCommon;
let SOClientGetDelay = 0;
@ -85,7 +85,7 @@ describe('IndexPatterns', () => {
};
});
indexPatterns = new IndexPatternsService({
indexPatterns = new DataViewsService({
uiSettings: ({
get: () => Promise.resolve(false),
getAll: () => {},
@ -207,7 +207,7 @@ describe('IndexPatterns', () => {
indexPatterns.refreshFields = jest.fn();
const indexPattern = await indexPatterns.create({ title }, true);
expect(indexPattern).toBeInstanceOf(IndexPattern);
expect(indexPattern).toBeInstanceOf(DataView);
expect(indexPattern.title).toBe(title);
expect(indexPatterns.refreshFields).not.toBeCalled();
@ -235,7 +235,7 @@ describe('IndexPatterns', () => {
indexPatterns.createSavedObject = jest.fn(() =>
Promise.resolve(({
id: 'id',
} as unknown) as IndexPattern)
} as unknown) as DataView)
);
indexPatterns.setDefault = jest.fn();
await indexPatterns.createAndSave({ title });

View file

@ -6,78 +6,80 @@
* Side Public License, v 1.
*/
/* eslint-disable max-classes-per-file */
import { i18n } from '@kbn/i18n';
import { PublicMethodsOf } from '@kbn/utility-types';
import { INDEX_PATTERN_SAVED_OBJECT_TYPE, SavedObjectsClientCommon } from '../..';
import { castEsToKbnFieldTypeName } from '@kbn/field-types';
import { DATA_VIEW_SAVED_OBJECT_TYPE, SavedObjectsClientCommon } from '../..';
import { createIndexPatternCache } from '.';
import { createDataViewCache } from '.';
import type { RuntimeField } from '../types';
import { IndexPattern } from './index_pattern';
import {
createEnsureDefaultIndexPattern,
EnsureDefaultIndexPattern,
} from './ensure_default_index_pattern';
import { DataView } from './index_pattern';
import { createEnsureDefaultDataView, EnsureDefaultDataView } from './ensure_default_index_pattern';
import {
OnNotification,
OnError,
UiSettingsCommon,
IIndexPatternsApiClient,
IDataViewsApiClient,
GetFieldsOptions,
IndexPatternSpec,
IndexPatternAttributes,
DataViewSpec,
DataViewAttributes,
FieldAttrs,
FieldSpec,
IndexPatternFieldMap,
DataViewFieldMap,
TypeMeta,
} from '../types';
import { FieldFormatsStartCommon, FORMATS_UI_SETTINGS } from '../../../../field_formats/common/';
import { UI_SETTINGS, SavedObject } from '../../../common';
import { SavedObjectNotFound } from '../../../../kibana_utils/common';
import { IndexPatternMissingIndices } from '../lib';
import { DataViewMissingIndices } from '../lib';
import { findByTitle } from '../utils';
import { DuplicateIndexPatternError } from '../errors';
import { castEsToKbnFieldTypeName } from '../../kbn_field_types';
import { DuplicateDataViewError } from '../errors';
const MAX_ATTEMPTS_TO_RESOLVE_CONFLICTS = 3;
export type IndexPatternSavedObjectAttrs = Pick<
IndexPatternAttributes,
'title' | 'type' | 'typeMeta'
>;
export type IndexPatternSavedObjectAttrs = Pick<DataViewAttributes, 'title' | 'type' | 'typeMeta'>;
export type IndexPatternListSavedObjectAttrs = Pick<
IndexPatternAttributes,
DataViewAttributes,
'title' | 'type' | 'typeMeta'
>;
export interface IndexPatternListItem {
export interface DataViewListItem {
id: string;
title: string;
type?: string;
typeMeta?: TypeMeta;
}
/**
* @deprecated Use DataViewListItem. All index pattern interfaces were renamed.
*/
export type IndexPatternListItem = DataViewListItem;
interface IndexPatternsServiceDeps {
uiSettings: UiSettingsCommon;
savedObjectsClient: SavedObjectsClientCommon;
apiClient: IIndexPatternsApiClient;
apiClient: IDataViewsApiClient;
fieldFormats: FieldFormatsStartCommon;
onNotification: OnNotification;
onError: OnError;
onRedirectNoIndexPattern?: () => void;
}
export class IndexPatternsService {
export class DataViewsService {
private config: UiSettingsCommon;
private savedObjectsClient: SavedObjectsClientCommon;
private savedObjectsCache?: Array<SavedObject<IndexPatternSavedObjectAttrs>> | null;
private apiClient: IIndexPatternsApiClient;
private apiClient: IDataViewsApiClient;
private fieldFormats: FieldFormatsStartCommon;
private onNotification: OnNotification;
private onError: OnError;
private indexPatternCache: ReturnType<typeof createIndexPatternCache>;
private indexPatternCache: ReturnType<typeof createDataViewCache>;
ensureDefaultIndexPattern: EnsureDefaultIndexPattern;
ensureDefaultIndexPattern: EnsureDefaultDataView;
constructor({
uiSettings,
@ -94,12 +96,12 @@ export class IndexPatternsService {
this.fieldFormats = fieldFormats;
this.onNotification = onNotification;
this.onError = onError;
this.ensureDefaultIndexPattern = createEnsureDefaultIndexPattern(
this.ensureDefaultIndexPattern = createEnsureDefaultDataView(
uiSettings,
onRedirectNoIndexPattern
);
this.indexPatternCache = createIndexPatternCache();
this.indexPatternCache = createDataViewCache();
}
/**
@ -107,7 +109,7 @@ export class IndexPatternsService {
*/
private async refreshSavedObjectsCache() {
const so = await this.savedObjectsClient.find<IndexPatternSavedObjectAttrs>({
type: INDEX_PATTERN_SAVED_OBJECT_TYPE,
type: DATA_VIEW_SAVED_OBJECT_TYPE,
fields: ['title', 'type', 'typeMeta'],
perPage: 10000,
});
@ -148,9 +150,9 @@ export class IndexPatternsService {
* @param size
* @returns IndexPattern[]
*/
find = async (search: string, size: number = 10): Promise<IndexPattern[]> => {
find = async (search: string, size: number = 10): Promise<DataView[]> => {
const savedObjects = await this.savedObjectsClient.find<IndexPatternSavedObjectAttrs>({
type: INDEX_PATTERN_SAVED_OBJECT_TYPE,
type: DATA_VIEW_SAVED_OBJECT_TYPE,
fields: ['title'],
search,
searchFields: ['title'],
@ -261,7 +263,7 @@ export class IndexPatternsService {
* @returns FieldSpec[]
*/
getFieldsForIndexPattern = async (
indexPattern: IndexPattern | IndexPatternSpec,
indexPattern: DataView | DataViewSpec,
options?: GetFieldsOptions
) =>
this.getFieldsForWildcard({
@ -275,7 +277,7 @@ export class IndexPatternsService {
* Refresh field list for a given index pattern
* @param indexPattern
*/
refreshFields = async (indexPattern: IndexPattern) => {
refreshFields = async (indexPattern: DataView) => {
try {
const fields = (await this.getFieldsForIndexPattern(indexPattern)) as FieldSpec[];
fields.forEach((field) => (field.isMapped = true));
@ -286,7 +288,7 @@ export class IndexPatternsService {
);
indexPattern.fields.replaceAll(fieldsWithSavedAttrs);
} catch (err) {
if (err instanceof IndexPatternMissingIndices) {
if (err instanceof DataViewMissingIndices) {
this.onNotification({ title: (err as any).message, color: 'danger', iconType: 'alert' });
}
@ -308,7 +310,7 @@ export class IndexPatternsService {
* @returns Record<string, FieldSpec>
*/
private refreshFieldSpecMap = async (
fields: IndexPatternFieldMap,
fields: DataViewFieldMap,
id: string,
title: string,
options: GetFieldsOptions,
@ -331,7 +333,7 @@ export class IndexPatternsService {
return this.fieldArrayToMap(updatedFieldList, fieldAttrs);
} catch (err) {
if (err instanceof IndexPatternMissingIndices) {
if (err instanceof DataViewMissingIndices) {
this.onNotification({ title: (err as any).message, color: 'danger', iconType: 'alert' });
return {};
}
@ -353,7 +355,7 @@ export class IndexPatternsService {
* @returns Record<string, FieldSpec>
*/
fieldArrayToMap = (fields: FieldSpec[], fieldAttrs?: FieldAttrs) =>
fields.reduce<IndexPatternFieldMap>((collector, field) => {
fields.reduce<DataViewFieldMap>((collector, field) => {
collector[field.name] = {
...field,
customLabel: fieldAttrs?.[field.name]?.customLabel,
@ -368,7 +370,7 @@ export class IndexPatternsService {
* @returns IndexPatternSpec
*/
savedObjectToSpec = (savedObject: SavedObject<IndexPatternAttributes>): IndexPatternSpec => {
savedObjectToSpec = (savedObject: SavedObject<DataViewAttributes>): DataViewSpec => {
const {
id,
version,
@ -413,15 +415,15 @@ export class IndexPatternsService {
};
};
private getSavedObjectAndInit = async (id: string): Promise<IndexPattern> => {
const savedObject = await this.savedObjectsClient.get<IndexPatternAttributes>(
INDEX_PATTERN_SAVED_OBJECT_TYPE,
private getSavedObjectAndInit = async (id: string): Promise<DataView> => {
const savedObject = await this.savedObjectsClient.get<DataViewAttributes>(
DATA_VIEW_SAVED_OBJECT_TYPE,
id
);
if (!savedObject.version) {
throw new SavedObjectNotFound(
INDEX_PATTERN_SAVED_OBJECT_TYPE,
DATA_VIEW_SAVED_OBJECT_TYPE,
id,
'management/kibana/indexPatterns'
);
@ -431,8 +433,8 @@ export class IndexPatternsService {
};
private initFromSavedObject = async (
savedObject: SavedObject<IndexPatternAttributes>
): Promise<IndexPattern> => {
savedObject: SavedObject<DataViewAttributes>
): Promise<DataView> => {
const spec = this.savedObjectToSpec(savedObject);
const { title, type, typeMeta, runtimeFieldMap } = spec;
spec.fieldAttrs = savedObject.attributes.fieldAttrs
@ -471,7 +473,7 @@ export class IndexPatternsService {
}
}
} catch (err) {
if (err instanceof IndexPatternMissingIndices) {
if (err instanceof DataViewMissingIndices) {
this.onNotification({
title: (err as any).message,
color: 'danger',
@ -501,7 +503,7 @@ export class IndexPatternsService {
* @param id
*/
get = async (id: string): Promise<IndexPattern> => {
get = async (id: string): Promise<DataView> => {
const indexPatternPromise =
this.indexPatternCache.get(id) ||
this.indexPatternCache.set(id, this.getSavedObjectAndInit(id));
@ -520,11 +522,11 @@ export class IndexPatternsService {
* @param skipFetchFields
* @returns IndexPattern
*/
async create(spec: IndexPatternSpec, skipFetchFields = false): Promise<IndexPattern> {
async create(spec: DataViewSpec, skipFetchFields = false): Promise<DataView> {
const shortDotsEnable = await this.config.get(FORMATS_UI_SETTINGS.SHORT_DOTS_ENABLE);
const metaFields = await this.config.get(UI_SETTINGS.META_FIELDS);
const indexPattern = new IndexPattern({
const indexPattern = new DataView({
spec,
fieldFormats: this.fieldFormats,
shortDotsEnable,
@ -545,7 +547,7 @@ export class IndexPatternsService {
* @param skipFetchFields Whether to skip field refresh step.
*/
async createAndSave(spec: IndexPatternSpec, override = false, skipFetchFields = false) {
async createAndSave(spec: DataViewSpec, override = false, skipFetchFields = false) {
const indexPattern = await this.create(spec, skipFetchFields);
const createdIndexPattern = await this.createSavedObject(indexPattern, override);
await this.setDefault(createdIndexPattern.id!);
@ -558,24 +560,24 @@ export class IndexPatternsService {
* @param override Overwrite if existing index pattern exists
*/
async createSavedObject(indexPattern: IndexPattern, override = false) {
async createSavedObject(indexPattern: DataView, override = false) {
const dupe = await findByTitle(this.savedObjectsClient, indexPattern.title);
if (dupe) {
if (override) {
await this.delete(dupe.id);
} else {
throw new DuplicateIndexPatternError(`Duplicate index pattern: ${indexPattern.title}`);
throw new DuplicateDataViewError(`Duplicate index pattern: ${indexPattern.title}`);
}
}
const body = indexPattern.getAsSavedObjectBody();
const response: SavedObject<IndexPatternAttributes> = (await this.savedObjectsClient.create(
INDEX_PATTERN_SAVED_OBJECT_TYPE,
const response: SavedObject<DataViewAttributes> = (await this.savedObjectsClient.create(
DATA_VIEW_SAVED_OBJECT_TYPE,
body,
{
id: indexPattern.id,
}
)) as SavedObject<IndexPatternAttributes>;
)) as SavedObject<DataViewAttributes>;
const createdIndexPattern = await this.initFromSavedObject(response);
this.indexPatternCache.set(createdIndexPattern.id!, Promise.resolve(createdIndexPattern));
@ -592,7 +594,7 @@ export class IndexPatternsService {
*/
async updateSavedObject(
indexPattern: IndexPattern,
indexPattern: DataView,
saveAttempts: number = 0,
ignoreErrors: boolean = false
): Promise<void | Error> {
@ -611,7 +613,7 @@ export class IndexPatternsService {
});
return this.savedObjectsClient
.update(INDEX_PATTERN_SAVED_OBJECT_TYPE, indexPattern.id, body, {
.update(DATA_VIEW_SAVED_OBJECT_TYPE, indexPattern.id, body, {
version: indexPattern.version,
})
.then((resp) => {
@ -681,8 +683,18 @@ export class IndexPatternsService {
*/
async delete(indexPatternId: string) {
this.indexPatternCache.clear(indexPatternId);
return this.savedObjectsClient.delete(INDEX_PATTERN_SAVED_OBJECT_TYPE, indexPatternId);
return this.savedObjectsClient.delete(DATA_VIEW_SAVED_OBJECT_TYPE, indexPatternId);
}
}
export type IndexPatternsContract = PublicMethodsOf<IndexPatternsService>;
/**
* @deprecated Use DataViewsService. All index pattern interfaces were renamed.
*/
export class IndexPatternsService extends DataViewsService {}
export type DataViewsContract = PublicMethodsOf<DataViewsService>;
/**
* @deprecated Use DataViewsContract. All index pattern interfaces were renamed.
*/
export type IndexPatternsContract = DataViewsContract;

View file

@ -13,7 +13,7 @@ import { KbnError } from '../../../../kibana_utils/common/';
/**
* Tried to call a method that relies on SearchSource having an indexPattern assigned
*/
export class IndexPatternMissingIndices extends KbnError {
export class DataViewMissingIndices extends KbnError {
constructor(message: string) {
const defaultMessage = "IndexPattern's configured pattern does not match any indices";

View file

@ -7,14 +7,14 @@
*/
import { SavedObjectsClientContract, SimpleSavedObject } from '../../../../../core/public';
import { INDEX_PATTERN_SAVED_OBJECT_TYPE } from '../../constants';
import { DATA_VIEW_SAVED_OBJECT_TYPE } from '../../constants';
export async function getTitle(
client: SavedObjectsClientContract,
indexPatternId: string
): Promise<SimpleSavedObject<any>> {
const savedObject = (await client.get(
INDEX_PATTERN_SAVED_OBJECT_TYPE,
DATA_VIEW_SAVED_OBJECT_TYPE,
indexPatternId
)) as SimpleSavedObject<any>;

View file

@ -6,9 +6,9 @@
* Side Public License, v 1.
*/
export { IndexPatternMissingIndices } from './errors';
export { DataViewMissingIndices } from './errors';
export { getTitle } from './get_title';
export { isDefault } from './is_default';
export * from './types';
export { validateIndexPattern } from './validate_index_pattern';
export { validateDataView } from './validate_index_pattern';

View file

@ -8,24 +8,24 @@
import { CONTAINS_SPACES_KEY, ILLEGAL_CHARACTERS_KEY, ILLEGAL_CHARACTERS_VISIBLE } from './types';
import { validateIndexPattern } from './validate_index_pattern';
import { validateDataView } from './validate_index_pattern';
describe('Index Pattern Utils', () => {
describe('Validation', () => {
it('should not allow space in the pattern', () => {
const errors = validateIndexPattern('my pattern');
const errors = validateDataView('my pattern');
expect(errors[CONTAINS_SPACES_KEY]).toBe(true);
});
it('should not allow illegal characters', () => {
ILLEGAL_CHARACTERS_VISIBLE.forEach((char) => {
const errors = validateIndexPattern(`pattern${char}`);
const errors = validateDataView(`pattern${char}`);
expect(errors[ILLEGAL_CHARACTERS_KEY]).toEqual([char]);
});
});
it('should return empty object when there are no errors', () => {
expect(validateIndexPattern('my-pattern-*')).toEqual({});
expect(validateDataView('my-pattern-*')).toEqual({});
});
});
});

View file

@ -8,7 +8,7 @@
import { ILLEGAL_CHARACTERS_VISIBLE, CONTAINS_SPACES_KEY, ILLEGAL_CHARACTERS_KEY } from './types';
function indexPatternContainsSpaces(indexPattern: string): boolean {
function dataViewContainsSpaces(indexPattern: string): boolean {
return indexPattern.includes(' ');
}
@ -23,7 +23,7 @@ function findIllegalCharacters(indexPattern: string): string[] {
return illegalCharacters;
}
export function validateIndexPattern(indexPattern: string) {
export function validateDataView(indexPattern: string) {
const errors: Record<string, any> = {};
const illegalCharacters = findIllegalCharacters(indexPattern);
@ -32,7 +32,7 @@ export function validateIndexPattern(indexPattern: string) {
errors[ILLEGAL_CHARACTERS_KEY] = illegalCharacters;
}
if (indexPatternContainsSpaces(indexPattern)) {
if (dataViewContainsSpaces(indexPattern)) {
errors[CONTAINS_SPACES_KEY] = true;
}

View file

@ -6,14 +6,14 @@
* Side Public License, v 1.
*/
import type { estypes } from '@elastic/elasticsearch';
import type { IndexPatternFieldBase, IFieldSubType, IndexPatternBase } from '@kbn/es-query';
import type { DataViewFieldBase, IFieldSubType, DataViewBase } from '@kbn/es-query';
import { ToastInputFields, ErrorToastOptions } from 'src/core/public/notifications';
// eslint-disable-next-line
import type { SavedObject } from 'src/core/server';
import { IFieldType } from './fields';
import { RUNTIME_FIELD_TYPES } from './constants';
import { SerializedFieldFormat } from '../../../expressions/common';
import { KBN_FIELD_TYPES, IndexPatternField } from '..';
import { KBN_FIELD_TYPES, DataViewField } from '..';
import { FieldFormat } from '../../../field_formats/common';
export type FieldFormatMap = Record<string, SerializedFieldFormat>;
@ -31,7 +31,7 @@ export interface RuntimeField {
* IIndexPattern allows for an IndexPattern OR an index pattern saved object
* Use IndexPattern or IndexPatternSpec instead
*/
export interface IIndexPattern extends IndexPatternBase {
export interface IIndexPattern extends DataViewBase {
title: string;
fields: IFieldType[];
/**
@ -44,15 +44,13 @@ export interface IIndexPattern extends IndexPatternBase {
/**
* Look up a formatter for a given field
*/
getFormatterForField?: (
field: IndexPatternField | IndexPatternField['spec'] | IFieldType
) => FieldFormat;
getFormatterForField?: (field: DataViewField | DataViewField['spec'] | IFieldType) => FieldFormat;
}
/**
* Interface for an index pattern saved object
*/
export interface IndexPatternAttributes {
export interface DataViewAttributes {
fields: string;
title: string;
type?: string;
@ -69,6 +67,11 @@ export interface IndexPatternAttributes {
allowNoIndex?: boolean;
}
/**
* @deprecated Use DataViewAttributes. All index pattern interfaces were renamed.
*/
export type IndexPatternAttributes = DataViewAttributes;
/**
* @intenal
* Storage of field attributes. Necessary since the field list isn't saved.
@ -133,12 +136,17 @@ export interface GetFieldsOptionsTimePattern {
interval: string;
}
export interface IIndexPatternsApiClient {
export interface IDataViewsApiClient {
getFieldsForTimePattern: (options: GetFieldsOptionsTimePattern) => Promise<any>;
getFieldsForWildcard: (options: GetFieldsOptions) => Promise<any>;
hasUserIndexPattern: () => Promise<boolean>;
}
/**
* @deprecated Use IDataViewsApiClient. All index pattern interfaces were renamed.
*/
export type IIndexPatternsApiClient = IDataViewsApiClient;
export type { SavedObject };
export type AggregationRestrictions = Record<
@ -160,11 +168,19 @@ export interface TypeMeta {
};
}
export enum IndexPatternType {
export enum DataViewType {
DEFAULT = 'default',
ROLLUP = 'rollup',
}
/**
* @deprecated Use DataViewType. All index pattern interfaces were renamed.
*/
export enum IndexPatternType {
DEFAULT = DataViewType.DEFAULT,
ROLLUP = DataViewType.ROLLUP,
}
export type FieldSpecConflictDescriptions = Record<string, string[]>;
// This should become FieldSpec once types are cleaned up
@ -189,7 +205,7 @@ export interface FieldSpecExportFmt {
* @public
* Serialized version of IndexPatternField
*/
export interface FieldSpec extends IndexPatternFieldBase {
export interface FieldSpec extends DataViewFieldBase {
/**
* Popularity count is used by discover
*/
@ -208,13 +224,18 @@ export interface FieldSpec extends IndexPatternFieldBase {
isMapped?: boolean;
}
export type IndexPatternFieldMap = Record<string, FieldSpec>;
export type DataViewFieldMap = Record<string, FieldSpec>;
/**
* @deprecated Use DataViewFieldMap. All index pattern interfaces were renamed.
*/
export type IndexPatternFieldMap = DataViewFieldMap;
/**
* Static index pattern format
* Serialized data object, representing index pattern attributes and state
*/
export interface IndexPatternSpec {
export interface DataViewSpec {
/**
* saved object id
*/
@ -231,7 +252,7 @@ export interface IndexPatternSpec {
intervalName?: string;
timeFieldName?: string;
sourceFilters?: SourceFilter[];
fields?: IndexPatternFieldMap;
fields?: DataViewFieldMap;
typeMeta?: TypeMeta;
type?: string;
fieldFormats?: Record<string, SerializedFieldFormat>;
@ -240,6 +261,11 @@ export interface IndexPatternSpec {
allowNoIndex?: boolean;
}
/**
* @deprecated Use DataViewSpec. All index pattern interfaces were renamed.
*/
export type IndexPatternSpec = DataViewSpec;
export interface SourceFilter {
value: string;
}

View file

@ -9,7 +9,7 @@
import type { IndexPatternSavedObjectAttrs } from './index_patterns';
import type { SavedObjectsClientCommon } from '../types';
import { INDEX_PATTERN_SAVED_OBJECT_TYPE } from '../constants';
import { DATA_VIEW_SAVED_OBJECT_TYPE } from '../constants';
/**
* Returns an object matching a given title
@ -21,7 +21,7 @@ import { INDEX_PATTERN_SAVED_OBJECT_TYPE } from '../constants';
export async function findByTitle(client: SavedObjectsClientCommon, title: string) {
if (title) {
const savedObjects = await client.find<IndexPatternSavedObjectAttrs>({
type: INDEX_PATTERN_SAVED_OBJECT_TYPE,
type: DATA_VIEW_SAVED_OBJECT_TYPE,
perPage: 10,
search: `"${title}"`,
searchFields: ['title'],

View file

@ -43,7 +43,7 @@ import {
ILLEGAL_CHARACTERS_VISIBLE,
ILLEGAL_CHARACTERS,
isDefault,
validateIndexPattern,
validateDataView,
flattenHitWrapper,
} from './index_patterns';
@ -58,7 +58,7 @@ export const indexPatterns = {
isDefault,
isFilterable,
isNestedField,
validate: validateIndexPattern,
validate: validateDataView,
flattenHitWrapper,
};
@ -82,7 +82,7 @@ export {
IndexPatternListItem,
} from '../common';
export { DuplicateIndexPatternError } from '../common/index_patterns/errors';
export { DuplicateDataViewError } from '../common/index_patterns/errors';
/*
* Autocomplete query suggestions:

View file

@ -11,7 +11,7 @@ export {
CONTAINS_SPACES_KEY,
ILLEGAL_CHARACTERS_VISIBLE,
ILLEGAL_CHARACTERS,
validateIndexPattern,
validateDataView,
isDefault,
} from '../../common/index_patterns/lib';
export { flattenHitWrapper, formatHitProvider, onRedirectNoIndexPattern } from './index_patterns';

View file

@ -7,7 +7,7 @@
*/
import { HttpSetup } from 'src/core/public';
import { IndexPatternMissingIndices } from '../../../common/index_patterns/lib';
import { DataViewMissingIndices } from '../../../common/index_patterns/lib';
import {
GetFieldsOptions,
IIndexPatternsApiClient,
@ -30,7 +30,7 @@ export class IndexPatternsApiClient implements IIndexPatternsApiClient {
})
.catch((resp: any) => {
if (resp.body.statusCode === 404 && resp.body.attributes?.code === 'no_matching_indices') {
throw new IndexPatternMissingIndices(resp.body.message);
throw new DataViewMissingIndices(resp.body.message);
}
throw new Error(resp.body.message || resp.body.error || `${resp.body.statusCode} Response`);

View file

@ -12,7 +12,7 @@ import {
IIndexPatternsApiClient,
GetFieldsOptionsTimePattern,
} from '../../common/index_patterns/types';
import { IndexPatternMissingIndices } from '../../common/index_patterns/lib';
import { DataViewMissingIndices } from '../../common/index_patterns/lib';
import { IndexPatternsFetcher } from './fetcher';
import { hasUserIndexPattern } from './has_user_index_pattern';
@ -44,7 +44,7 @@ export class IndexPatternsApiServer implements IIndexPatternsApiClient {
err.output.payload.statusCode === 404 &&
err.output.payload.code === 'no_matching_indices'
) {
throw new IndexPatternMissingIndices(pattern);
throw new DataViewMissingIndices(pattern);
} else {
throw err;
}

View file

@ -17,7 +17,7 @@ import {
IndexPatternSpec,
} from '../../../data/public';
import { FailedImport } from './process_import_response';
import { DuplicateIndexPatternError, IndexPattern } from '../../../data/public';
import { DuplicateDataViewError, IndexPattern } from '../../../data/public';
type SavedObjectsRawDoc = Record<string, any>;
@ -89,7 +89,7 @@ async function importIndexPattern(
try {
emptyPattern = await indexPatterns.createAndSave(indexPatternSpec, overwriteAll, true);
} catch (err) {
if (err instanceof DuplicateIndexPatternError) {
if (err instanceof DuplicateDataViewError) {
// We can override and we want to prompt for confirmation
const isConfirmed = await openConfirm(
i18n.translate('savedObjectsManagement.indexPattern.confirmOverwriteLabel', {

View file

@ -13,7 +13,7 @@ import { extractErrorMessage } from '../../../../../../../common/util/errors';
import { DeepReadonly } from '../../../../../../../common/types/common';
import { ml } from '../../../../../services/ml_api_service';
import { useMlContext } from '../../../../../contexts/ml';
import { DuplicateIndexPatternError } from '../../../../../../../../../../src/plugins/data/public';
import { DuplicateDataViewError } from '../../../../../../../../../../src/plugins/data/public';
import { useRefreshAnalyticsList, DataFrameAnalyticsConfig } from '../../../../common';
import { extractCloningConfig, isAdvancedConfig } from '../../components/action_clone';
@ -145,7 +145,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => {
),
});
} catch (e) {
if (e instanceof DuplicateIndexPatternError) {
if (e instanceof DuplicateDataViewError) {
addRequestMessage({
error: i18n.translate(
'xpack.ml.dataframe.analytics.create.duplicateIndexPatternErrorMessageError',

View file

@ -45,7 +45,7 @@ import { useApi } from '../../../../hooks/use_api';
import { useAppDependencies, useToastNotifications } from '../../../../app_dependencies';
import { RedirectToTransformManagement } from '../../../../common/navigation';
import { ToastNotificationText } from '../../../../components';
import { DuplicateIndexPatternError } from '../../../../../../../../../src/plugins/data/public';
import { DuplicateDataViewError } from '../../../../../../../../../src/plugins/data/public';
import {
PutTransformsLatestRequestSchema,
PutTransformsPivotRequestSchema,
@ -257,7 +257,7 @@ export const StepCreateForm: FC<StepCreateFormProps> = React.memo(
setLoading(false);
return true;
} catch (e) {
if (e instanceof DuplicateIndexPatternError) {
if (e instanceof DuplicateDataViewError) {
toastNotifications.addDanger(
i18n.translate('xpack.transform.stepCreateForm.duplicateIndexPatternErrorMessage', {
defaultMessage: