I want to fetch metadata information regarding a Database view.
I can find my view using the following code
DatabaseMetaData databaseMetaData = connection.getMetaData();
String tableName = "";
ResultSet rSet = databaseMetaData.getTables(null, databaseName, null, new String[] {TABLE, VIEW});
while (rSet.next()) {
tableName = rSet.getString(TABLE_NAME_COLUMN);
if (rSet.getString(TABLE_TYPE_COLUMN).equals(TABLE)) {
tableNames.add(tableName);
} else if (rSet.getString(TABLE_TYPE_COLUMN).equals(VIEW)) {
viewNames.add(tableName);
}
}
Now when i have the view name, i want to fetch the list of data columns in the VIEW.
I use the following code
ResultSet rSet = databaseMetaData.getColumns(null, databaseName, table, null);
while (rSet.next()) {
columnDefinitions.add(new ColumnDefinition(rSet.getString(COLUMN_NAME_COLUMN), getColumnClassName(rSet
.getInt(DATA_TYPE_COLUMN))));
}
the concern here being that this query only returns the list of base columns from which this VIEW was derived. Say if my base table had 3 columns and i created a view if that table with 2 extra columns deriving information from the 3 base columns.
I want to fetch all 5 columns name and information. Is this possible ?
Is there any other method available to do this ?
Related
I have two tables in one database, table one called: ci_admin, and table two called active_ingredient.
I want to get user data from the active_ingredient table where user_id equals admin_id from ci_admin table using the current user session.
this code, get data for all user, I need the data inserted by the user only:
$wh =array();
$SQL ='SELECT * FROM active_ingredient';
$wh[] = "SELECT 1
FROM ci_admin
WHERE ci_admin.admin_id = active_ingredient.user_id";
if(count($wh)>0)
{ $WHERE = implode(' and ',$wh);
return $this->datatable->LoadJson($SQL,$WHERE);
}
else
{
return $this->datatable->LoadJson($SQL);
}
Try this, it will help you.
$this->db->select('ai.*,ca.*');
$this->db->from('active_ingredient ai');
$this->db->join('ci_admin ca', 'ca.admin_id = ai.user_id', 'left');
$this->db->where($data); //pass the session data for exact filter
$query = $this->db->get();
return $query->result();
My scenario is i have a grid with search option where user can select the column and can do the search, the grid data is coming from various tables. I have attached a sample screen of grid.
User Screen
So i'm trying to create a dynamic query for search but the problem is i can able to search only in main table (schema.Robot) not in Preload tables. whenever i trying to search data data from Preload tables let say from RobotModel table that time getting below error
pq: missing FROM-clause entry for table "robot_models"
Here is my go code
func (r *RobotsRepository) GetRobotsSummary(listParams viewmodel.ListParams, companyID uint) ([]*schema.Robot, int, error) {
mrobots := []*schema.Robot{}
var count int
var order string
if listParams.SortColumn == "" {
listParams.SortColumn = "id"
listParams.SortOrder = 1
} else {
listParams.SortColumn = util.Underscore(listParams.SortColumn)
}
if listParams.SortOrder == 0 {
order = "ASC"
} else {
order = "DESC"
}
var searchQuery string
if listParams.SearchText != "" {
switch listParams.SearchColumn {
case "Robot":
listParams.SearchColumn = "name"
case "Model":
listParams.SearchColumn = "robot_models.name"
}
searchQuery = listParams.SearchColumn +" LIKE '%"+ listParams.SearchText +"%' and Company_ID = " + fmt.Sprint(companyID)
}else{
searchQuery = "Company_ID = " + fmt.Sprint(companyID)
}
orderBy := fmt.Sprintf("%s %s", listParams.SortColumn, order)
err := r.Conn.
Preload("RobotModel", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Name")
}).
Preload("Task", func(db *gorm.DB) *gorm.DB {
return db.Where("Task_Status in ('In-Progress','Pending')").Select("ID, Task_Status")
}).
Preload("CreatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Preload("UpdatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Where(searchQuery).
Order(orderBy).
Offset(listParams.PageSize * (listParams.PageNo - 1)).
Limit(listParams.PageSize).
Find(&mrobots).Error
r.Conn.Model(&schema.Robot{}).Where(searchQuery).Count(&count)
return mrobots, count, err
}
In searchQuery variable i'm storing my dynamic query.
My question is how can i search data for preload table columns
Here is the sql query which i'm trying to achieve using gorm
SELECT robots.id,robots.name,robot_models.name as
model_name,count(tasks.task_status) as task_on_hand,
robots.updated_at,users.user_name as updated_by
FROM rfm.robots as robots
left join rfm.tasks as tasks on tasks.robot_id = robots.id and
tasks.task_status in ('In-Progress','Pending')
left join rfm.robot_models as robot_models on robot_models.id =
robots.robot_model_id
left join rfm.users as users on users.id = robots.updated_by
WHERE robot_models.name::varchar like '%RNR%' and robots.deleted_at is null
GROUP BY robots.id,robot_models.name,users.user_name
ORDER BY task_on_hand DESC LIMIT 2 OFFSET 0
and sorry for bad English!
Even though you are preloading, you are still required to explicitly use joins when filtering and ordering on columns on other tables. Preloading is used to eagerly load the data to map into your models, not to join tables.
Chain on something like this:
.Joins("LEFT JOIN rfm.robot_models AS robot_models ON robot_models.id = robots.robot_model_id")
I'm not positive if you can use the AS keyword using this technique, but if not, it should be easy enough to adjust your query accordingly.
My application is in Asp.Net MVC3 coded in C#.Net. My issue is i want to get data from database using SQL query, for that i'm aware that i can use the below technique
Code to get data using ExecuteStoreQuery
var Complete_Data = db.ExecuteStoreQuery<Mytable>("select * from Mytable").ToList();
I have two issues
How to get the data in var Complete_Data when the data is coming from Multiple table (i.e the query has multiple joins).
I will be generating the selecting columns dynamically. The select query columns will generating dynamically.
Below is the sample example
string Field_Formation=string.Empty;
foreach (var item in My_Parameter_Collection_Logic_Variable)
{
Field_Formation+= item.Field_Name + ",";
}
Here My_Parameter_Collection_Logic_Variable is a variable declared in my code that will have a certain collection.
var Complete_Data = db.ExecuteStoreQuery<What_Class_To_Be_Taken_Here>("select" + Field_Formation + " from My_Tables_With_Multiple_Joins").ToList();
Need suggestion, whether it is possible to do such a stuff.
var Complete_Data = db.ExecuteStoreQuery<**What_Class_To_Be_Taken_Here**>
<What_Class_To_Be_Taken_Here> - this class must have properties like your Field_Formation.
For example if your select is:
"SELECT e.idExpense AS ExpenseID, e.idVehicle as VehicleID, d.Date AS Date1 .... join ... where ..."
create class like this:
public class ItemExample
{
private int VehicleID{ get; set; }
private int ExpenseID{ get; set; }
private DateTime? Date1 { get; set; }
}
You can write query using join and get your data from multiple tables.
for eg:-
var Complete_Data = db.ExecuteStoreQuery("select * from Table1 as T1 inner join Table2 as T2 on T1.id=T2.Id").ToList();
You will get all column of all table and then you can access using A.ColumnName or B.ColumnName.
i have alot of tables with alot of columns and want to generate xml using linq without having to specify
the column names. here's a quick example:
users
---------------
user_id
name
email
user_addresses
---------------
address_id
user_id
city
state
this is the xml i want to generate with linq would look like
<user>
<name>john</name>
<email>john#dlsjkf.com</email>
<address>
<city>charleston</city>
<state>sc</state>
</address>
<address>
<city>charlotte</city>
<state>nc</state>
</address>
</user>
so i'm guessing the code would look something like this:
var userxml = new XElement("user",
from row in dc.Users where user.id == 5
select (what do i put here??)
);
i can do this for one table but can't figure out how to generate the xml for a linked table (like user_addresses).
any ideas?
ok found a way to get the xml i want, but i have to specify the related table names in the query...which is good enough for now i guess. here's the code:
XElement root = new XElement("root",
from row in dc.users
where row.user_id == 5
select new XElement("user",
row.AsXElements(),
new XElement("addresses",
from row2 in dc.user_addresses
where row2.user_id == 5
select new XElement("address", row2.AsXElements())
)
)
);
// used to generate xml tags/elements named after the table column names
public static IEnumerable<XElement> AsXElements(this object source)
{
if (source == null) throw new ArgumentNullException("source");
foreach (System.Reflection.PropertyInfo prop in source.GetType().GetProperties())
{
object value = prop.GetValue(source, null);
if (value != null)
{
bool isColumn = false;
foreach (object obj in prop.GetCustomAttributes(true))
{
System.Data.Linq.Mapping.ColumnAttribute attribute = obj as System.Data.Linq.Mapping.ColumnAttribute;
if (attribute != null)
{
isColumn = true;
break;
}
}
if (isColumn)
{
yield return new XElement(prop.Name, value);
}
}
}
}
You need to use a join. Here's one way:
var query = from user in dc.Users
from addr in dc.UserAddress
where user.Id == addr.UserId
select new XElement("user",
new XElement("name", user.Name),
new XElement("email", user.Email),
new XElement("address",
new XElement("city", addr.City),
new XElement("state", addr.State)));
foreach (var item in query)
Console.WriteLine(item);
i have alot of tables with alot of
columns and want to generate xml using
linq without having to specify the
column names.
Not quite sure how you want to achieve that. You need to state the column names that go into the XML. Even if you were to reflect over the field names, how would you filter the undesired fields out and structure them properly without specifying the column names? For example how would you setup the address part? You could get the fields by using this on your User and UserAddress classes: User.GetType().GetFields() and go through the Name of each field, but then what?
I've got two form fields from which the user submits a 'category' and an 'item'.
The following code inserts the category fine (I modified it from the WebMatrix intro PDF) but I've no idea how to then insert the 'item' into the Items table. I'll also need to add the Id of the new category to the new item row.
This is the code that's working so far
#{ var db = Database.OpenFile("StarterSite.sdf");
var Category = Request["Category"]; //was name
var Item = Request["Item"]; //was description
if (IsPost) {
// Read product name.
Category = Request["Category"];
if (Category.IsEmpty()) {
Validation.AddFieldError("Category", "Category is required");
}
// Read product description.
Item = Request["Item"];
if (Item.IsEmpty()) {
Validation.AddFieldError("Item",
"Item type is required.");
}
// Define the insert query. The values to assign to the
// columns in the Products table are defined as parameters
// with the VALUES keyword.
if(Validation.Success) {
var insertQuery = "INSERT INTO Category (CategoryName) " +
"VALUES (#0)";
db.Execute(insertQuery, Category);
// Display the page that lists products.
Response.Redirect(#Href("~/success"));
}
}
}
I'm guessing/hoping this is a very easy question to answer so hopefully there isn't much more detail required - but please let me know if there is. Thanks.
There's a Database.GetLastInsertId method within WebMatrix which returns the id of the last inserted record (assuming it's an IDENTITY column you are using). Use that:
db.Execute(insertQuery, Category);
var id = (int)db.GetLastInsertId(); //id is the new CategoryId
db.Execute(secondInsertQuery, param1, id);