Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Firebird ALinq Provider - 날짜 필드에 대한 낙관적 동시성 쿼리 오류

문제 재현을 위해 아래와 같은 정도의 Linq Table 개체를 하나 정의하고,

[Table(Name = "Agents")]
public class Agent
{
    public Agent()
    {
    }

    [Column(IsPrimaryKey = true, DbType = "Char(38)")]
    public string Guid { get; set; }

    [Column(DbType = "TIMESTAMP")] // 날짜 필드가 Firebird에서는 TIMESTAMP 형식으로 정의되어 있습니다.
    public DateTime? Created { get; set; }

    [Column(DbType = "VarChar(50)")]
    public string Name { get; set; }

    ...[생략]...
}

다음과 같이 Linq 쿼리를 작성하였는데 오류가 발생한 것입니다.

var items = from record in db.Agents
            where record.Guid == agent.Guid
            select record;

if (items.Count() == 1)
{
    items.First().Name = "...[변경]...";
    db.SubmitChanges();
}

오류 메시지는 아래와 같습니다.

System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> was caught
  Message=conversion error from string "2011-05-25 오전 8:53:43"
  Source=mscorlib
  StackTrace:
    Server stack trace: 
       at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
       at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]: 
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at AgentServiceTest.ServiceReference1.IAgentWebService.Register(Agent agent)
       at AgentServiceTest.ServiceReference1.AgentWebServiceClient.Register(Agent agent) in D:\...[생략]...\Reference.cs:line 271
       at AgentServiceTest.Program.RegisterService(String addr, String agentId, String agentName, String version) in D:\...[생략]...\Program.cs:line 77
       at AgentServiceTest.Program.Main(String[] args) in D:\...[생략]...\Program.cs:line 29
  InnerException: 

Linq to SQL의 DataContext.Log를 이용하여 생성된 쿼리를 확인해 보니,

UPDATE Agents
SET Name = @p1
WHERE (Guid = @p0) AND ...[낙관적 동시성에 따른 기존 값 나열]... AND (Created = '2011-05-25 오전 8:53:43')

SET에 "Name = @p1"만 있는 것은 변경된 필드 값이 그것 하나이기 때문에 당연한 것이고, WHERE 구문 다음에 개별 값들에 대해서 기존 값을 지정함으로써 낙관적 동시성을 이용한 충돌을 방지하는 것도... 이해할 만한 수준입니다.

그런데, 하필 기존 값들이 'Parameterized Query'로 넘어가는 것이 아니고 직접 문자열 연결 쿼리로 구성하는 것이 문제가 되어버렸고, 게다가 한글 윈도우라서 DateTime 필드 값이 Localization 된 것이 결정적인 오류 원인이 되었습니다.

Firebird에서 허용되는 TIMESTAMP 값 형식은 아래의 글에 자세하게 소개되고 있습니다.

DATE, TIME AND TIMESTAMP LITERALS
; http://www.janus-software.com/fbmanual/manual.php?book=psql&topic=41

"For the TIMESTAMP form: 'mm/dd/yyyy hh:mm:ss'"라고 알려주듯이, ALinq provider의 SQL로 변환된 Linq 쿼리에 있는 TIMESTAMP 값의 문자열 형식하고는 완전히 다릅니다. 오류가 나는 것이 지극히 정상인 상황입니다. ^^




이를 가지고 ALinq 측에 문의를 했고, 다음은 제가 받은 응답니다. (역시 빠른 답변을 받을 수 있었습니다.)

Yes, We can use the parameter instead the text value, but that will cause another problem white you use complex query. (We will try to fix this problem in later)

Now I can provide you a solution: 
I do not think the the Created filed is necessary in the filter, so it can be ignore. you can set the UpdateCheck property of the Column Attribute as UpdateCheck.Never, now the Created property becomes:
[Column(DbType = "TIMESTAMP", UpdateCheck=UpdateCheck.Never)]
public DateTime? Created { get; set; }

And I suggest you only use the primary key value in the filter. it's say append  UpdateCheck=UpdateCheck.Never  to all the properties except primary key property.
That the SQL will become just like below
Update XXX
Set XXX
Where  Guid = @p0

PS: ALinq support update query, that means you can update the data directly, without select the data first.
For example:
db.Orders.Update(o => new Order { OrderID = 10, OrderDate = DateTime.Now },
                          o => o.OrderID == 1 & o.EmployeeID == 1)
for more details, you can see the sample which is in the ALinq install directory.

고민이군요. UpdateCheck를 해제할까 하다가 제 경우에는 Name 필드 값 변경이 그다지 특별한 동시성 체크를 요구하는 것은 아니었기 때문에 후자의 방법을 도입했습니다.

db.Agents.Update(
    o => new Agent { Name = agent.Name }
    o => o.Guid == agent.Guid);

==> 변환된 SQL 쿼리
UPDATE Agents SET Name = @p1 WHERE Guid = @p0

참고로, 원래의 System.Data.Linq에서 제공되는 Table<> 타입에는 Update 메서드가 제공되지 않습니다. 아마도 ALinq 측에서는 이런 문제를 대비해서 별도의 메서드를 제공한 것 같습니다.




SQL Server에 대한 System.Data.Linq의 기본 동작은 어떻게 되어 있을까요? 예상할 수 있는 것처럼 낙관적 동시성을 위한 조건문의 필드 값들이 전부 'parameterized query'로 처리되어 있습니다.

사실, 바로 이런 난관들이 3rd-party 라이브러리를 도입했을 때의 문제입니다. 해당 제품의 '홈페이지 설명문' 정도만 봐서는 실제 구현에 들어갔을 때 발생할 수 있는 문제를 예측할 수 없는데, 이런 때 중요한 것이 바로 '기술지원'입니다. 제 생각에는 ALinq는 '기술지원' 수준에서 충분히 합격점이라고 봅니다. ^^ (물론 System.Data.Linq와 완전히 동일하게 구현해 주면 더 좋겠지만... 저 스스로가 개발자이기 때문에 이런 부분은 이해해 줄 수 있습니다.)



[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/7/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13402정성태8/20/20233753닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233973닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233821오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233644닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234545스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20234071닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233830스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233632개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233590오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233893닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233755오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233823닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233640스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233684개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233924오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233980오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20234107Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20234293Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20234010.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233756개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233806.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20234238오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233619스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233652스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233523오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237443오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...