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)
13555정성태2/15/20242404닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20242097VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20242151닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20242056닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242378닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242566Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242971개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242730개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242470개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20242294Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20242191닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20242220오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20242266Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20242260오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242390VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242510Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242482개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242704닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242766닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242768닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242703닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242464닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242621닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242569닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242606닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242346닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...