/*
Performance indexes for Product Stock By Attributes queries.
Target: SQL Server
*/

/* trStock (inventory aggregation) */
IF NOT EXISTS (
  SELECT 1
  FROM sys.indexes
  WHERE name = 'IX_trStock_Item_Warehouse_Dims'
    AND object_id = OBJECT_ID('dbo.trStock')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_trStock_Item_Warehouse_Dims
  ON dbo.trStock (ItemTypeCode, ItemCode, WarehouseCode, ColorCode, ItemDim1Code, ItemDim2Code, ItemDim3Code)
  INCLUDE (In_Qty1, Out_Qty1, CompanyCode, OfficeCode, StoreTypeCode, StoreCode);
END;
GO

/* PickingStates */
IF NOT EXISTS (
  SELECT 1
  FROM sys.indexes
  WHERE name = 'IX_PickingStates_Item_Warehouse_Dims'
    AND object_id = OBJECT_ID('dbo.PickingStates')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_PickingStates_Item_Warehouse_Dims
  ON dbo.PickingStates (ItemTypeCode, ItemCode, WarehouseCode, ColorCode, ItemDim1Code, ItemDim2Code, ItemDim3Code)
  INCLUDE (Qty1, CompanyCode, OfficeCode, StoreTypeCode, StoreCode);
END;
GO

/* ReserveStates */
IF NOT EXISTS (
  SELECT 1
  FROM sys.indexes
  WHERE name = 'IX_ReserveStates_Item_Warehouse_Dims'
    AND object_id = OBJECT_ID('dbo.ReserveStates')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_ReserveStates_Item_Warehouse_Dims
  ON dbo.ReserveStates (ItemTypeCode, ItemCode, WarehouseCode, ColorCode, ItemDim1Code, ItemDim2Code, ItemDim3Code)
  INCLUDE (Qty1, CompanyCode, OfficeCode, StoreTypeCode, StoreCode);
END;
GO

/* DispOrderStates */
IF NOT EXISTS (
  SELECT 1
  FROM sys.indexes
  WHERE name = 'IX_DispOrderStates_Item_Warehouse_Dims'
    AND object_id = OBJECT_ID('dbo.DispOrderStates')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_DispOrderStates_Item_Warehouse_Dims
  ON dbo.DispOrderStates (ItemTypeCode, ItemCode, WarehouseCode, ColorCode, ItemDim1Code, ItemDim2Code, ItemDim3Code)
  INCLUDE (Qty1, CompanyCode, OfficeCode, StoreTypeCode, StoreCode);
END;
GO

/* Latest price lookup */
IF NOT EXISTS (
  SELECT 1
  FROM sys.indexes
  WHERE name = 'IX_prItemBasePrice_ItemType_ItemCode_PriceDate'
    AND object_id = OBJECT_ID('dbo.prItemBasePrice')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_prItemBasePrice_ItemType_ItemCode_PriceDate
  ON dbo.prItemBasePrice (ItemTypeCode, ItemCode, PriceDate DESC)
  INCLUDE (Price);
END;
GO
