How to query a database table that references itself via an intermediate table and extract all the data

J

Jose Vargas

Guest
Jose Vargas Asks: How to query a database table that references itself via an intermediate table and extract all the data
I have two tables, the main item table and the intermediate itemXitem table, which are used to generate a BOM list. Item

Code:
| Id | Name      |ItemType_id(FK)|
| -- | --------- |-------|
| 1  | Raw Item 1| 3     |
| 2  | Assy Item1| 2     |
| 3  | Raw Item 2| 3     |
| 4  | Top 1     | 1     |

ItemXItem

Code:
| Id | Parent_Id(FK) | Child_Id(FK) |
| -- | ------------- |------------- |
| 1  | 2             | 1            |
| 2  | 4             | 2            |
| 3  | 4             | 3            |

ItemType_id (1: Top, 2: Assembly, 3: Raw Material)

I extract the information from C# through a recursive method that converts it into a IQueryable.

This is the code

Code:
  public IQueryable<Item> GetChildsByParentId(long Id){
        List<ItemXItem> itemsXItems = new List<ItemXItem>();
        List<Item> items = new List<Item>();
        items.Add(db.Items
            .AsNoTracking()
            .Include("ItemType")
            .Include("ItemXItems")
            .Include("ItemXItems1")
            .Where(x => x.Id == Id).FirstOrDefault());

        GetAllChilds(Id, itemsXItems);
        foreach (ItemXItem element in itemsXItems)
        {
            items.Add(db.Items
            .AsNoTracking()
            .Include("ItemType")
            .Include("ItemXItems")
            .Include("ItemXItems1")
            .Where(x => x.Id == element.Child_Id).FirstOrDefault());
        }
        return items.AsQueryable();
    }

    private List<ItemXItem> GetAllChilds(long id, List<ItemXItem> itemsXItems)
    {
        List<ItemXItem> itemData = db.ItemXItems.Where(x => x.Parent_Id == id).ToList();
        foreach (ItemXItem element in itemData)
        {
            int items = db.ItemXItems.Where(x => x.Parent_Id == element.Child_Id).Count();
            if (items > 0)
            {
                itemsXItems.Add(element);
                GetAllChilds(element.ChildId, itemsXItems);
            }
            else
            {
                itemsXItems.Add(element);
            }
        }
        return itemsXItems;
    }

The problem is performance, the response time is affected by being a recursive function and by the number of levels it can go down to the final element (raw material).

I was looking for options to make the database server through a query allow me to extract the information, without having to use that recursion function. Any ideas. Thanks

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.
 
/forums/whats-new/news-feed

Unreplied Posts

Add context value into web.xml

KineticUncertainty Asks: Add context value into web.xml
I have an application where i defined the location to the external log4j2.properties. I have defined the Log4jServletContextListener in the web.xml and if i provide a path to the file it works. I am trying to figure out how to use a place holder and get the value of the context into it. Can any one help?

Here is my tomcat context entry

Code:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Environment name="demo/log4j2.location" type="java.lang.String" value="C:/conf/log4j2.xml"/>
</Context>

I have a bean setup that's grabbing the context entry. This is working fine.

Code:
@Bean("Logging")
    public String getConfig(
            @Value("${demo/log4j2.location}") String log4jConfigLocation
    ){
        validate(log4jConfigLocation, not(equalTo("${demo/log4j2.location}")));
        return log4jConfigLocation;
    }

I can also get the context value this way if its easier to use.

Code:
@Component
public class Log4jLoader {
  
    String location;
  
    public  Log4jLoader(@Value("${construct-demo/log4j2.location}") String location){
        this.location = location;
        loadLog4jConfig();
    }

    private void loadLog4jConfig() {

in my web.xml

Code:
<context-param>
    <param-name>isLog4jAutoInitializationDisabled</param-name>
    <param-value>true</param-value>
</context-param>
<listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<context-param>
    <param-name>log4jContextName</param-name>
    <param-value>demo</param-value>
</context-param>

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>file:$(location)</param-value>
</context-param>

THIS WORKS
<!--<context-param>-->
<!--<param-name>log4jConfiguration</param-name>-->
<!--<param-value>file:///C:/conf/log4j2.xml</param-value>-->
<!--</context-param>-->

is there a way to get that value into the file:$(location) ?

I have been stuck trying to figure this out for days and exhausting my googling

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Trying to simplify exception message but it's not being caught

SomeoneSpecial Asks: Trying to simplify exception message but it's not being caught
I'm attempting to shorten an exception that is being output to a log file. The exception is occurring but the contains is working how I intended it.

This is the message:

!Dropbox Success Message: System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Dropbox.Api.DropboxRequestHandler.d__18.MoveNext() --- End of stack trace from previous location where exception was thrown ---

This is what I'm trying to do:

Code:
  catch (Exception e)
  {
    if (e.ToString().Contains("Could not create SSL/TLS secure channel"))
    {
      _report.Add($"!Exception occurred in SendToDropbox.");
      _report.Add($"!Could not create SSL/TLS secure channel.");
    }
    else
    {
      _report.Add($"!Exception occurred in SendToDropbox.");
      _report.Add($"!{e}");
    }

The .contains isn't catching the message in the exception. The odd thing is, the exception is being output with that phrase in it so I don't understand why the contains wouldn't catch it.

Why isn't the contains catching it? What am I doing wrong?

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Chrome Extension: How to get object from DB when searching by value?

Nick Asks: Chrome Extension: How to get object from DB when searching by value?
Im trying to create a chrome extension, and have encountered an annoying problem. I have this function, where I add an object to my indexedDB if the urlKeyValue of that object, does not already exist in the database.

If the urlKeyValue does exist in the DB, i want to get the object in the DB that contains that value. This is where my problem begins. On line 184 - 188, i try to get the object by searching by the `urlKeyValue, but when I try to print the object, i get undefined.

Question: How to get an object from IndexedDB by a value?

This is how my objects are structured:

Code:
    {
    message: "insert",

    payload: [
      {
        urlKeyValue: "",
        url: {
          [userId]: {
            [time]: {
              msg: form_data.get("message"),
            },
          },
        },
      },
    ],
  }

My Function where it all happens:

Code:
function insert_records(records, when) {
  if (db) {
    const insert_transaction = db.transaction(["roster2"], "readwrite");
    const objectStore = insert_transaction.objectStore("roster2");

    return new Promise((resolve, reject) => {
      insert_transaction.oncomplete = function () {
        console.log("ALL INSERT TRANSACTIONS COMPLETE.");
        resolve(true);
      };

      insert_transaction.onerror = function () {
        console.log("PROBLEM INSERTING RECORDS.");
        resolve(false);
      };

      records.forEach((person) => {
        // the "when" varieable isnt important, just disregard it
        if (when != "init") {
          const index = objectStore.index("urlKeyValue");
          let search = index.get(person.urlKeyValue);

          search.onsuccess = function (event) {
            if (search.result === undefined) {
              // no record with that key
              let request = objectStore.add(person);

              request.onsuccess = function () {
                console.log("Added: ", person);
              };
            } 
            else {
              const request2 = objectStore.get(person.urlKeyValue);

              request2.onsuccess = function (event) {
                console.log("--------" +  event.target.result);
              };

            }
          };
        } else {
          // this else statement isnt really important for this question 
          let request = objectStore.add(person);

          request.onsuccess = function () {
            console.log("Added: ", person);
            //self.location.href;
          };
        }
      });
    });
  }
}

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Why are non-zero non-absolute seeks not supported in python?

MarcellPerger Asks: Why are non-zero non-absolute seeks not supported in python?
According to the python documentation,

  • SEEK_SET or 0: seek from the start of the stream (the default); offset must either be a number returned by TextIOBase.tell(), or zero. Any other offset value produces undefined behaviour.
  • SEEK_CUR or 1: “seek” to the current position; offset must be zero, which is a nooperation (all other values are unsupported).
  • SEEK_END or 2: seek to the end of the stream; offset must be zero (all other values are unsupported).

For SEEK_END and SEEK_CUR, why is only 0 offset supported?
Has it simply not been implemented yet/does it need a PEP?
Is this by design? If so, why?

Is there a workaround with acceptable performance (for files with UTF-8, without using undefined behavior)?
All the answers on this question either use undefined behavior or don't handle files with UTF-8.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Remove errors from code of sparse matrix using linked list

Garvit Asks: Remove errors from code of sparse matrix using linked list
Not getting any error on running the code. On debugging Segmentation fault on if(j == temp->col) when j = 4

Create function "seems" to have created the function well but I'm unsure why the segmentation fault.

The matrix(5x6) I input was 0 0 0 0 0 1\n 1 0 0 0 0 1\n 1 1 0 0 0 1\n 1 1 1 1 0 0\n 0 0 0 0 1 1\n

The output I received was 0 0 0 0 0 1\n 1 0 0 0 0 1\n 1 1 0 0 0 1\n 1 1 1 1

Code:
#include <stdio.h>
#include <stdlib.h>

struct node{
  int col;
  int data;
  struct node *next;
}*first;

void create(struct node *A[], int m, int n){
  struct node *temp, *last;
  int noe, flag = 0;
  for(int i = 0; i < m; i++){
    flag = 0;
    A[i] = (struct node *) malloc(sizeof(struct node));
    last = A[i];
    
    printf("Enter no. of items in Row %d :", i);
    scanf("%d", &noe);

    for(int j = 0; j < noe; j++){
      temp = (struct node *) malloc(sizeof(struct node));
      
      printf("Enter column and elmeent :");
      scanf("%d%d", &temp->col, &temp->data);
      
      temp->next = NULL;
      if(last == A[i] && flag == 0){
        A[i] = temp;
        flag = 1;
      }
      else
        last->next = temp;

      last = temp;

    }
    last = NULL;
  }
}

void display(struct node *A[], int m, int n){
  struct node *temp;
  for(int i = 0; i < m; i++){
    temp = A[i];
    for(int j = 0; j < n; j++){
      if(j == temp->col){
        printf("%d ", temp->data);
        temp = temp->next;
      }
      else
        printf("0 ");
    }
    printf("\n");
  }
}

int main(){
  
  int m = 5, n = 6;
  struct node *A[m];

  create(A, m, n);
  display(A, m, n);

  return 0;
}

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Latest posts

Top