I'm trying to implement a repository with Dapper as ORM, I want inserted or updated entities to be returned back. This is what I came up with, it works just fine but I'm wondering if this is abusing the default Query and QueryAsync methods?
public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
{
IEnumerable<Models.TestTable> output;
output = await _connection.QueryAsync<Models.TestTable>(
sql: string.Format("INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (#FirstName, #LastName)"),
param: inputObject);
return output.SingleOrDefault();
}
The only actual problem I can see there is the unnecessary string.Format.
Personally I might have been tempted to just update the Id (or whatever) in the existing object, but your OUTPUT INSERTED.* works fine too. I might be very tempted to move the local declaration inline via var output = ..., and of course once I've done that it makes it tempting to make the entire thing inline:
public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
=> (await _connection.QueryAsync<Models.TestTable>(
"INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (#FirstName, #LastName)",
inputObject)).SingleOrDefault();
but most of that is trivia and subjective. Heck, even the string.Format is just unnecessary rather than problematic.
One other thing to check: did we (and I can't remember!) add a QuerySingleOrDefaultAsync method? I know we added QuerySingleOrDefault - I just can't remember about the *Async twin.
Related
If it's relevant I'm using Django with Django Rest Framework, django-mssql-backend and pyodbc
I am building some read only models of a legacy database using fairly complex queries and Django's MyModel.objects.raw() functionality. Initially I was executing the query as a Select query which was working well, however I received a request to try and do the same thing but with a table-valued function from within the database.
Executing this:
MyModel.objects.raw(select * from dbo.f_mytablefunction)
Gives the error: Invalid object name 'myapp_mymodel'.
Looking deeper into the local variables at time of error it looks like this SQL is generated:
'SELECT [myapp_mymodel].[Field1], '
'[myapp_mymodel].[Field2] FROM '
'[myapp_mymodel] WHERE '
'[myapp_mymodel].[Field1] = %s'
The model itself is mapped properly to the query as executing the equivalent:
MyModel.objects.raw(select * from dbo.mytable)
Returns data as expected, and dbo.f_mytablefunction is defined as:
CREATE FUNCTION dbo.f_mytablefunction
(
#param1 = NULL etc etc
)
RETURNS TABLE
AS
RETURN
(
SELECT
field1, field2 etc etc
FROM
dbo.mytable
)
If anyone has any explanation as to why these two modes of operation are treated substantially differently then I would be very pleased to find out.
Guess you've figured this out by now (see docs):
MyModel.objects.raw('select * from dbo.f_mytablefunction(%s)', [1])
If you'd like to map your table valued function to a model, this gist has a quite thorough approach, though no license is mentioned.
Once you've pointed your model 'objects' to the new TableFunctionManager and added the 'function_args' OrderedDict (see tests in gist), you can query it as follows:
MyModel.objects.all().table_function(param1=1)
For anyone wondering about use cases for table valued functions, try searching for 'your_db_vendor tvf'.
I am new to Scala and have been learning about slick(3.1.1). While writing a particular code to insert data into a table, I have to insert a row if it does not exist else update a particular column in that table. For a single row update I have written the following code, which works fine :
def updateDate(id: Int, country : Country, lastDate: DateTime)(implicit ec: ExecutionContext) =
byPKC.applied((id, country, )).map(_.lastMessageDate).update(lastDate) flatMap {
case 0 ⇒
create(User.withLastDate(id, country, lastDate))
case x ⇒ DBIO.successful(x)
}
Now I am unsure of how to do a bulk operation in scala for this. I tried the following, which even though inefficient, should work but there is no row being inserted into the table.
def updateDates(ids: Set[Int], country: Country, lastDate: DateTime)(implicit ec: ExecutionContext) = {
ids.foreach(e ⇒ updateDate(e, country, lastDate))
DBIO.successful(1)
}
How do I do a bulk write in scala? Also, why does this bulk operation not work? Any help would be much appreciated.
Two-part answer to the two-part question.
How do I do a bulk write in scala?
You can't do bulk updates in SQL; it's simply not supported. You can bulk insert, though. Slick supports bulk inserts with the ++= operator on TableQuery.
Why does this bulk operation not work?
You're generating the DBIO values, but you aren't executing them via db.run(). DBIO is a mapping of Scala operations to SQL, but you have to execute it before it will be sent to the database.
once again thanks for your help in advance im looking to pre fill a mysqli insert statement with data filled from an array and cannot seem to get it to work it just doesnt insert and im kinda stuck and looking for ideas
this is what im chasing as a end result as for code but cannot seem to get it to work
$table_colums= array("db_colum1","db_colum2");
$forms_data = array("form_data1","form_data2");
$sql = INSERT into some_table ($table_colums) VALUES ($forms_data)
obviously if i do it the old fashion way it will work but i need to have it get its values from the arrays because there dynamic and filled from a database
$sql = INSERT into some_table (db_colum1,db_colum2) VALUES ('form_data1','form_data2')
I can suggest you a library I wrote, SafeMysql, which is doing exactly what you want - adding arrays to mysql (among many other wonderful things).
Though you need another kind of array, but I suppose it would be even simpler:
include 'safemysql.class.php';
$db = new safemysql();
$data = array(
"db_colum1" => "form_data1",
"db_colum2" => "form_data2",
);
$db->query("INSERT INTO some_table SET ?u", $data);
Nothing could be easier.
We're having a strange problem in Oracle. I'll sketch some (simplified) context first:
Consider this mapping to an Entity:
public EntityMap()
{
Table("EntityTable");
Id(x => x.Id)
.Column("entityID")
.GeneratedBy.Native("ENTITYID").UnsavedValue(0);
Map(x => x.SomeBoolean).Column("SomeBoolean");
}
and this code:
var entity = new Entity();
using (var transaction = new TransactionScope(TransactionScopeOption.Required))
{
Session.Save(entity);
transaction.Complete();
}
//A lot of code
if(someCondition)
{
using (var transaction = new TransactionScope(TransactionScopeOption.Required))
{
enitity.SomeBoolean = true;
Session.Update(entity);
transaction.Complete();
}
}
This code is called a few times. The first time it generates the following queries:
select ENTITYID.nextval from dual
INSERT INTO Entity
(SomeBoolean, EntityID)
VALUES (0, 1216)
UPDATE Entity
SET SomeBoolean = 1
WHERE EntityID = 1216
The second time it is called these queries are generated (someCondition is false)
select ENTITYID.nextval from dual
INSERT INTO Entity
(SomeBoolean, EntityID)
VALUES (0, 1217)
And now the trouble begins. From now on, each insert will use the correct autoincremented value, but the update will always use 1217
select ENTITYID.nextval from dual
INSERT INTO Entity
(SomeBoolean, EntityID)
VALUES (0, 1218)
UPDATE Entity
SET SomeBoolean = 1
WHERE EntityID = 1217
And of course, this is not what we want to happen. If I inspect the value of the Id while debugging, it contains the correct autoincremented value. Somehow, deep in the bowels of NHibernate, the incorrect is is assigned to the WHERE clause...
The strange part is that this only happens on Oracle. If I switch NHibernate to MsSql, everything works like a charm.
So I found out what happened. NHibernate changed it's default connection release mode between versions 1.x and 2.x. Instead of closing the connection when the session is Disposed, the connections is now closed after each transaction. However, we were manually coordinating our transactions which apparently caused troubles in Oracle.
This question has some extra information and this entry in the NHibernate documentation also clarifies how the connections are handeled:
As of NHibernate, if your application manages transactions through .NET APIs such as System.Transactions library, ConnectionReleaseMode.AfterTransaction may cause NHibernate to open and close several connections during one transaction, leading to unnecessary overhead and transaction promotion from local to distributed. Specifying ConnectionReleaseMode.OnClose will revert to the legacy behavior and prevent this problem from occuring.
This blog post is what got me looking in the right direction.
I have a CLR UDT that would benefit greatly from table-valued methods, ala xml.nodes():
-- nodes() example, for reference:
declare #xml xml = '<id>1</id><id>2</id><id>5</id><id>10</id>'
select c.value('.','int') as id from #xml.nodes('/id') t (c)
I want something similar for my UDT:
-- would return tuples (1, 4), (1, 5), (1, 6)....(1, 20)
declare #udt dbo.FancyType = '1.4:20'
select * from #udt.AsTable() t (c)
Does anyone have any experience w/ this? Any help would be greatly appreciated. I've tried a few things and they've all failed. I've looked for documentation and examples and found none.
Yes, I know I could create table-valued UDFs that take my UDT as a parameter, but I was rather hoping to bundle everything inside a single type, OO-style.
EDIT
Russell Hart found the documentation states that table-valued methods are not supported, and fixed my syntax to produce the expected runtime error (see below).
In VS2010, after creating a new UDT, I added this at the end of the struct definition:
[SqlMethod(FillRowMethodName = "GetTable_FillRow", TableDefinition = "Id INT")]
public IEnumerable GetTable()
{
ArrayList resultCollection = new ArrayList();
resultCollection.Add(1);
resultCollection.Add(2);
resultCollection.Add(3);
return resultCollection;
}
public static void GetTable_FillRow(object tableResultObj, out SqlInt32 Id)
{
Id = (int)tableResultObj;
}
This builds and deploys successfully. But then in SSMS, we get a runtime error as expected (if not word-for-word):
-- needed to alias the column in the SELECT clause, rather than after the table alias.
declare #this dbo.tvm_example = ''
select t.[Id] as [ID] from #this.GetTable() as [t]
Msg 2715, Level 16, State 3, Line 2
Column, parameter, or variable #1: Cannot find data type dbo.tvm_example.
Parameter or variable '#this' has an invalid data type.
So, it seems it is not possible after all. And even if were possible, it probably wouldn't be wise, given the restrictions on altering CLR objects in SQL Server.
That said, if anyone knows a hack to get around this particular limitation, I'll raise a new bounty accordingly.
You have aliased the table but not the columns. Try,
declare #this dbo.tvm_example = ''
select t.[Id] as [ID] from #this.GetTable() as [t]
According to the documentation, http://msdn.microsoft.com/en-us/library/ms131069(v=SQL.100).aspx#Y4739, this should fail on another runtime error regarding incorrect type.
The SqlMethodAttribute class inherits from the SqlFunctionAttribute class, so SqlMethodAttribute inherits the FillRowMethodName and TableDefinition fields from SqlFunctionAttribute. This implies that it is possible to write a table-valued method, which is not the case. The method compiles and the assembly deploys, but an error about the IEnumerable return type is raised at runtime with the following message: "Method, property, or field '' in class '' in assembly '' has invalid return type."
They may be avoiding supporting such a method. If you alter the assembly with method updates this can cause problems to the data in UDT columns.
An appropriate solution is to have a minimal UDT, then a seperate class of methods to accompany it. This will ensure flexibility and fully featured methods.
xml nodes method will not change so it is not subject to the same implemetation limitations.
Hope this helps Peter and good luck.