I need to insert records to an Oracle DB table that already has records in it by using the table's sequence.
I tried using RQL which creates an auto-generated id for the primary key but sometimes those generated ids already exist in the database and as a result, a constraint violation error is thrown.
ATG documentation provides an alternative named Overriding RQL-Generated SQL but I didn't manage to make it work for insert statements.
GSARepository repo =
(GSARepository)request.resolveName("/examples/TestRepository");
RepositoryView view = repo.getView("canard");
Object params[] = new Object[4];
params[0] = new Integer (25);
params[1] = new Integer (75);
params[2] = "french";
params[3] = "greek";
Builder builder = (Builder)view.getQueryBuilder();
String str = "SELECT * FROM usr_tbl WHERE (age_col > 0 AND age_col < 1
AND EXISTS (SELECT * from subjects_tbl where id = usr_tbl.id AND subject
IN (2, 3)))";
RepositoryItem[] items =
view.executeQuery (builder.createSqlPassthroughQuery(str, params));
Is there any way to use table's sequence for insert statements via ATG Repository API?
Eventually, I did not manage to make it work but I found the following solution.
I retrieved the sequence number as below and then used it in the RQL insert statement.
RepositoryView view = getRestServiceDetailsRepository().getView("wsLog");
String sql = "select log_seq.nextval from dual";
Object[] params = {};
Builder builder = (Builder) view.getQueryBuilder();
Query query = builder.createSqlPassthroughQuery(sql, params);
RepositoryItem[] items = view.executeQuery(query);
if (items != null && items.length > 0) {
items[0].getRepositoryId();
}
Related
I have face problem about entity framework in mcv c#,
i decide to change the way to exec query to normally query scripting,
this bellow script I have for exemple
//for only one row result
string activeUser = await db.Users.Where(x => x.Token.Equals(token)).Select(x => x.Username).FirstOrDefaultAsync();
ReceivingSFG receiving = await db.ReceivingSFGs.Where(s => s.ID.Equals(receivingVM.ID)).FirstOrDefaultAsync();
//for multiple row result (List)
IQueryable<ReceivingSFGDetail> query = db.ReceivingSFGDetails.Where(s => s.ReceivingID.Equals(req.ID)).AsQueryable();
IEnumerable<ReceivingSFGDetail> list = Enumerable.Empty<ReceivingSFGDetail>();
list = query.ToList();
IEnumerable<ReceivingSFGDetailDTO> listDto = Enumerable.Empty<ReceivingSFGDetailDTO>();
string message = "";
bool status = false;
listDto = from x in list
select new ReceivingSFGDetailDTO
{
ID = x.ID,
ReceivingID = x.ReceivingID,
Barcode = x.Barcode,
QtyActual = x.QtyActual,
QtyBag = x.QtyBag,
CreatedBy = x.CreatedBy,
CreatedDate = x.CreatedDate,
QtyPerBag = x.QtyPerBag
};
or some case that I never use before,
like how to exec store procedure... please some one can help me to solve this case.
If you want to execute Stored Procedure vie Entity framework you will of course have to start by mapping it into the data context.
Once the stored procedure is mapped in your model layer you can simply call it pseudo like this:
List<SomeStuff_Result> list = _db.NameOfStoredProcedure(string somevariable).ToList();
It should behave the same way any object you receive from data layer.
You can also check this answer.
when i query a single table , i do not want all columns , i just want some column that i interest in.
For example, when i use where method to query a table, it will query all columns in a table like
public class SubjectSpecimenType extends Model {
}
SubjectSpecimenType.where("SUBJECT_ID = ? AND SITE_ID = ?", subjectId, siteId);
i don't know if there has a method named select that i can use to query some column like
SubjectSpecimenType.select("SUBJECT_NAME", "SITE_NAME").where("SUBJECT_ID = ? AND SITE_ID = ?", subjectId, siteId);
there are the source code in LazyList.java
/**
* Use to see what SQL will be sent to the database.
*
* #param showParameters true to see parameter values, false not to.
* #return SQL in a dialect for current connection which will be used if you start querying this
* list.
*/
public String toSql(boolean showParameters) {
String sql;
if(forPaginator){
sql = metaModel.getDialect().formSelect(null, null, fullQuery, orderBys, limit, offset);
}else{
sql = fullQuery != null ? fullQuery
: metaModel.getDialect().formSelect(metaModel.getTableName(), null, subQuery, orderBys, limit, offset);
}
if (showParameters) {
StringBuilder sb = new StringBuilder(sql).append(", with parameters: ");
join(sb, params, ", ");
sql = sb.toString();
}
return sql;
}
when call formSelect method, the second param columns always be null
is there a unfinish TODO ?
When operating on Models, ActiveJDBC always selects all columns, because if you load a model and it has partial attributes loaded, then you have a deficient model. The columns are specified in some edge cases, as in the RawPaginator: https://github.com/javalite/javalite/blob/e91ebdd1e4958bc0965d7ee99e6b7debc59a7b85/activejdbc/src/main/java/org/javalite/activejdbc/RawPaginator.java#L141
There is nothing to finish here, the behavior is intentional.
I am using ServiceStack 4.5.14. I want to pass a list of Guid to such as below query.
Table Name: Image
Columns: (Id -> Type=Guid) (ImageId -> Type=Guid) (Guid -> Type=Guid)
var result = Db.ExecuteSql("select value from image unpivot (value for col in (Id, ImageId)) un where Guid=(#param) order by Guid",
new { param = "5de7f247-f590-479a-9c29-2e68a57e711c" });
It returns a result which their Id and ImageId are 000.... while they are null.
Another question is: how can I send a list of Guid as parameter to above query?
To query a parameterized field you should include the Guid instead of the string, e.g:
var result = Db.ExecuteSql(
#"select value from image unpivot (value for col in (Id, ImageId)) un
where Guid=(#param) order by Guid",
new { param = new Guid("5de7f247-f590-479a-9c29-2e68a57e711c") });
If values are null, it's likely masquerading an error, you can bubble errors with:
OrmLiteConfig.ThrowOnError = true;
Or enable debug logging with:
LogManager.LogFactory = new ConsoleLogFactory();
In v5+ you can also inspect SQL commands before they're executed with:
OrmLiteConfig.BeforeExecFilter = dbCmd => Console.WriteLine(dbCmd.GetDebugString());
In my Windows Forms application, I'm using a SQL Server Compact database. I have a function in which I want to update the columns 'id' and 'name' in table 'owner', unless the specified id does not exist, in which case I want new values inserted.
For example, my current table has 'id' 1 and 2. It MIGHT have 'id' 3. User enters data to insert/update id 3.
I want my query to do something like this:
UPDATE owner
SET name = #InputN
WHERE id = 3
IF ##ROWCOUNT = 0
INSERT INTO owner (id, name) VALUES 3, #InputN
How should I define my query in order to make this work in SQL Server Compact Edition?
You should do it in your form codes. This way you don't even need to check if there is an di with the value=3. It will check it by itself and update the row if it exists. If not you won't get any errors.
RSSql.UpdateNonQueryParametric("update owner set name=? where id=3", newname);
public static void UpdateNonQueryParametric(string query, params Object[] parameters)
{
SqlCeParameter[] param = new SqlCeParameter[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
param[i] = new SqlCeParameter();
param[i].Value = parameters[i];
}
_cnt = new SqlCeConnection();
_cnt.ConnectionString = ConnectionString;
_cmd = new SqlCeCommand();
_cmd.Connection = _cnt;
_cmd.CommandType = System.Data.CommandType.Text;
_cmd.CommandText = query;
_cmd.Parameters.AddRange(param);
if (_cnt.State != System.Data.ConnectionState.Open)
_cnt.Open();
_cmd.ExecuteNonQuery();
_cmd.Dispose();
if (_cnt.State != System.Data.ConnectionState.Closed)
_cnt.Close();
_cnt.Dispose();
}
I have this table:
Please, don't mind because it's on my native language and it doesn't matter..
Those are all attributes in table but when I go to Visual StudioS and try to use some of this I get this one:
I see all "normal" attributes in VS but where is those FK attributes?
I need them to compare few ones and get values?
I can't use it from name of other tables [dot] attribute etc...
like for example:
I need this: table1.ID == table2.ID
and not this: table1.ID == table1.table2.ID
Where or what is FK attribute in VS that is shown in SQL table ??
public void setParametri(int desID)
{
foreach (desavanje d in DM_Class.dc.desavanje)
if (d.desavanjeID == desID)
{
//THIS FIRST 4 LINES WORKS PERFECTLY
this.naziv_des = d.naziv_des;
this.datum_po = d.datum_pocetka.ToString();
this.datum_zav = d.datum_kraja.ToString();
this.cijena = d.cijena_des;
//foreach (klijenti k in DM_Class.dc.klijenti)
//{
// if(k.klijentID == //WHAT TO PUT HERE TO COMPARE VALUE klijentID from tables klijenti with FK value in table desavanje)
// this.klijent = k.Ime + ' ' + k.Prezime;
//}
//ON THIS LINE I'M GETTING ERROR - Object reference not set to an instance of an object. but why?
//I have data on that field in DB ?
//this.grad = d.mjesto_desavanja.gradovi.naziv_grada.ToString();
//this.mjesto = d.mjesto_desavanja.naziv_objekta;
//this.organizator = d.organizator.Ime + ' ' + d.organizator.Prezime;
//this.tip = d.tip_desavanja.vrsta_des;
this.klijent = d.klijenti.Ime + ' ' + d.klijenti.Prezime;
//this.status = d.status_desavanja.naziv_statusa;
//this.br_gost = d.specifikacija_desavanja.br_osoba;
}
}
If is there other solution to get values for attributes I'm willing to try it without using another foreach loop?
Ok, I managed this.. I've used a linq query to generate data that I need and in that queries I've compared needed ID's and finally get some working stuff.