Ftrack 쿼리는 Ftrack API의 객체 지향 래퍼입니다. 기본 쿼리 구문은 강력하지만 전적으로 텍스트 기반이므로 동적 쿼리를 구성하기가 어려울 수 있습니다. 이 모듈은 중첩 된 비교를 통해 운영자 를 지원합니다 .
Ftrack API의 작동 방식에 대한 기본 이해를 위해서는 먼저 https://ftrack-python-api.readthedocs.io/en/stable/tutorial.html을 읽는 것이 좋습니다.
pip install ftrack_query
전체 쿼리 문자열을 한 번에 작성하는 대신 "명령문"이 구성되고 ( 예 : stmt = select('Task') ), 쿼리는 문서에서 .where() 및 .populate() 와 같은 호출 메소드를 통해 구축 할 수 있습니다.
CRUD 메소드는 모두 지원됩니다 ( create , select , update , delete ). 기본 기능은 select 와 함께 사용하도록 설계되었습니다. 이 진술은 메인 API와 유사한 구문으로 구축되므로 둘 사이의 전환이 간단해야합니다.
이것은 완전히 뒤로 호환되므로 기존 쿼리를 다시 작성할 필요가 없습니다.
아래 예제는 매우 기본적인 쿼리입니다.
from ftrack_query import FTrackQuery , attr , create , select , and_ , or_
with FTrackQuery () as session :
# Select
project = session . select ( 'Project' ). where ( name = 'Test Project' ). one ()
# Create
task = session . execute (
create ( 'Task' ). values (
name = 'My Task' ,
project = project ,
)
)
session . commit ()
# Update
rows_updated = session . execute (
update ( 'Task' )
. where ( name = 'Old Task Name' )
. values ( name = 'New Task Name' )
)
session . commit ()
# Delete
rows_deleted = session . execute (
delete ( 'Task' ). where (
name = 'Old Task Name' ,
)
)
session . commit ()훨씬 더 복잡한 예를 위해 :
ATTR_TYPE = attr ( 'type.name' )
TASK_STMT = (
select ( 'Task' )
# Filter the tasks
. where (
# Get any task without these statuses
~ attr ( 'status.name' ). in_ ([ 'Lighting' , 'Rendering' ]),
# Check for notes matching any of the following conditions:
attr ( 'notes' ). any (
# Ensure note was posted by someone outside the company
~ attr ( 'user.email' ). endswith ( '@company.com' )
# Ensure note either not completable or not completed
or_ (
and_ (
completed_by = None ,
is_todo = True ,
),
is_todo = False ,
),
),
# Ensure it has an animation task
or_ (
ATTR_TYPE . contains ( 'Animation' ),
ATTR_TYPE == 'Anim_Fixes' ,
),
),
# Order the results
. order_by (
ATTR_TYPE . desc (), # Equivalent to "type.name desc"
'name' ,
)
# Use projections to populate attributes as part of the query
. populate (
'name' ,
'notes' ,
'status.name' ,
ATTR_TYPE ,
)
. limit ( 5 )
)
with FTrackQuery () as session :
# Filter the above query to the result of another query
task_stmt = TASK_STMT . where (
project_id = session . select ( 'Project' ). where ( name = 'Test Project' ). one ()[ 'id' ]
)
# Use the current session to execute the statement
tasks = session . execute ( task_stmt ). all ()이벤트 시스템은 약간 다른 쿼리 언어를 사용합니다.
from ftrack_query import FTrackQuery , event
from ftrack_query . event import attr , and_ , or_
with FTrackQuery () as session :
session . event_hub . subscribe ( str (
and_ (
attr ( 'topic' ) == 'ftrack.update' ,
attr ( 'data.user.name' ) != getuser (),
)
))
session . event_hub . wait () attr() , and_() 및 or_() ftrack_query 및 ftrack_query.event 에 모두 존재합니다. 이들은 교환 할 수 없으므로 둘 다 필요한 경우 event 가져 와서 네임 스페이스로 사용하십시오.
ftrack_api.Session 에서 상속 된 메인 세션.
다중 비교에 가입하십시오.
단축키는 & and | 와 함께 제공됩니다 ( 예 : attr(a).contains(b) & attr(x).contains(y) .
입력 비교를 뒤집습니다.
바로 가기에는 ~ ( 예 : ~attr(x).contains(y) )가 제공됩니다.
쿼리 문자열 빌드에 사용됩니다.
from ftrack_query import select
stmt = select ( entity ). where (...). populate (...) Calling session.execute(stmt) .one() 쿼리를 실행하고 ftrack의 자체 QueryResult 객체 .first() 반환 .all() .. 또는 바로 가기 session.select(entity) 선택하면 건너 뛸 수 있습니다.
결과를 필터링하십시오.
키워드를 사용하는 것은 .where(first_name='Peter', last_name='Hunt') 와 같은 가장 빠른 방법입니다. 평등 점검보다 더 복잡한 경우 .where(attr('project.metadata').any(attr('key') != 'disabled')) 와 같이 attr() 사용하는 것이 권장됩니다.
사전 가져 오기 엔티티 속성.
예를 들어, 모든 사용자의 이름을 반복하려면 쿼리의 일부로 .populate('first_name', 'last_name') 호출하는 것이 좋습니다. 그 없이는 N+1 쿼리 문제로 알려진 사용자 당 2 개의 별도 쿼리가 필요합니다.
속성으로 결과를 정렬하십시오.
속성과 순서는 형식 attr('name').desc() 또는 name descending 과 같은 원시 문자열로 제공 될 수 있습니다. 제공되지 않으면 주문이 ascending 으로 기본값을받습니다.
분류 방향을 바꿉니다.
결과량을 특정 값으로 제한하십시오.
참고 : 이것은 .first() 또는 .one() 호출 할 수 없습니다.
제한을 사용하는 경우 반환 된 결과에 오프셋을 적용하십시오.
고급 사용자 만.
page_size : ftrack에서 한 번에 가져올 결과 수를 설정하십시오.session : 쿼리에 세션 객체를 첨부하십시오. .in_() 내에서 사용하기위한 문헌을 명령문으로 만듭니다.
이것은 진술의 일부로 항상 "선택"이 있음을 보장합니다. 속성 매개 변수를 수동으로 설정하면 기존 예측이 무시됩니다.
새로운 엔티티를 만드는 데 사용됩니다.
from ftrack_query import create
stmt = create ( entity ). values (...) Calling session.execute(stmt) 생성 된 엔티티를 반환합니다.
엔티티를 만들기위한 값.
여러 엔티티의 업데이트 값을 배치하는 데 사용됩니다. 이것은 select 메소드에서 구축되므로 동일한 방법이 많이 포함되어 있습니다.
from ftrack_query import update
stmt = update ( entity ). where (...). values (...) Calling session.execute(stmt) 발견 된 엔티티 수를 반환하고 업데이트했습니다.
업데이트 할 내용을 필터링하십시오.
엔티티에서 업데이트 할 값.
엔티티를 삭제하는 데 사용됩니다. 이것은 select 메소드에서 구축되므로 동일한 방법이 많이 포함되어 있습니다.
from ftrack_query import delete
stmt = delete ( entity ). where (...). options ( remove_components = True ) 전화 session.execute(stmt) 삭제 된 엔티티 수를 반환합니다.
업데이트 할 내용을 필터링하십시오.
remove_components : 삭제되기 전에 포함 된 모든 Location 에서 Component 엔티티를 제거하십시오. 롤백 할 수 없으므로 기본적으로 활성화되지 않습니다. Comparison 객체는 데이터를 문자열로 변환하도록 설계되었습니다. 여기에는 다른 Comparison 개체를 포함하여 모든 데이터 유형에 사용할 수있는 광범위한 연산자가 포함되어 있습니다. 함수 attr 이것에 대한 지름길입니다.
모든 비교는 ~ prefix 또는 not_ 함수와 반전 될 수 있습니다.
attr(key) == 'value'attr(key) > 5attr(key).like('value%')attr(key).after(arrow.now().floor('day'))attr(key).has(subkey='value')attr(key).any(subkey='value')attr(key).in_(subquery)간단한 비교.
속성이 결과와 일치하는지 확인하기 위해 점검을 수행하십시오.
이렇게하면 .in_('select id from table where x is y') 또는 .in_(['x', 'y']) 와 같은 하위 쿼리를 허용 할 수 있습니다.
문자열이 쿼리에 포함되어 있는지 확인하십시오. like 또는 not_like 사용하는 경우 백분율 기호를 와일드 카드로 사용하십시오. 나머지는 바로 가기이며 자동으로 수행합니다.
스칼라 및 수집 관계에 대한 테스트.
날짜에 대한 테스트. arrow 개체 사용이 권장됩니다.
# Project
select ( 'Project' )
# Project where status is active
select ( 'Project' ). where ( status = 'active' )
# Project where status is active and name like "%thrones"
select ( 'Project' ). where ( attr ( 'name' ). like ( '%thrones' ), status = 'active' )
# session.query('Project where status is active and (name like "%thrones" or full_name like "%thrones")')
select ( 'Project' ). where ( or_ ( attr ( 'name' ). like ( '%thrones' ), attr ( 'full_name' ). like ( '%thrones' )), status = 'active' )
# session.query('Task where project.id is "{0}"'.format(project['id']))
select ( 'Task' ). where ( project = project )
# session.query('Task where project.id is "{0}" and status.type.name is "Done"'.format(project['id']))
select ( 'Task' ). where ( attr ( 'status.type.name' ) == 'Done' , project = project )
# session.query('Task where timelogs.start >= "{0}"'.format(arrow.now().floor('day')))
select ( 'Task' ). where ( attr ( 'timelogs.start' ) >= arrow . now (). floor ( 'day' ))
# session.query('Note where author has (first_name is "Jane" and last_name is "Doe")')
select ( 'Note' ). where ( attr ( 'author' ). has ( first_name = 'Jane' , last_name = 'Doe' ))
# session.query('User where not timelogs any ()')
select ( 'User' ). where ( ~ attr ( 'timelogs' ). any ())
# projects = session.query('select full_name, status.name from Project')
select ( 'Project' ). populate ( 'full_name' , 'status.name' )
# select name from Project where allocations.resource[Group].memberships any (user.username is "john_doe")
select ( 'Project' ). select ( 'name' ). where ( attr ( 'allocations.resource[Group].memberships' ). any ( attr ( 'user.username' ) == 'john_doe' ))
# Note where parent_id is "{version_id}" or parent_id in (select id from ReviewSessionObject where version_id is "{version_id}")
select ( 'Note' ). where ( or_ ( attr ( 'parent_id' ). in_ ( select ( 'ReviewSessionObject' ). where ( version_id = version_id ). subquery ()), parent_id = version_id ))