:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add saved SQL expressions on tables (#78167)
Marius Andra97712d2a6d7c
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 76c0ab3bf2aa..06518f92b291 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -120,6 +120,7 @@ rules:|DatasetItemVersion|DatasetRevision|DataWarehouseCredential+ |DataWarehouseExpression|DataWarehouseJoin|DataWarehouseManagedViewSet|DataWarehouseModelPath@@ -468,6 +469,7 @@ rules:|DatasetItemVersion|DatasetRevision|DataWarehouseCredential+ |DataWarehouseExpression|DataWarehouseJoin|DataWarehouseManagedViewSet|DataWarehouseModelPathdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6fb97aa58528..36a3a64ffdc0 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5847,9 +5847,9 @@ snapshots:scenes-app-data-warehouse-settings-schemas--multi-schema--light:hash: v1.k794b7964.5ffdf524ce0fccb08b6337e373019c4f8601698dbd2ed67c236128731535cce0.dCP7dQzs_qdpEswIIblxlI6tpTWrpUNYGke67f_ZzHcscenes-app-data-warehouse-sql-editor--managed-warehouse-connection--dark:- hash: v1.k794b7964.d09b47ad01a9e133badd485b8d379f39d7fbff7f3e90fce5d8bda31dde99e854.Fz0b6MkRwO8N8vD_VmhzF3QTRE9CXUVbwZEd6QZ1h2g+ hash: v1.k794b7964.4d87a8398ed4a62e9e18ef60f2e907fc8f1585d178833c8eacc34eb5b49cd7cf.jIj6nVJk8Wp1LwkjVO3t4AsK_U0iWUqtUVC6HzXz12gscenes-app-data-warehouse-sql-editor--managed-warehouse-connection--light:- hash: v1.k794b7964.09e95ddff4424ba4d6435ea7b07a7347fddb55cd097f32738eb0cc3d5cfbfd3f.iICaMLjwq6Blk2kyDv4FA-tghl9Bi6fkPIVctuZQHDo+ hash: v1.k794b7964.94f8446b422849213e559816286f4692a33dae22bd5e0d2a7e046b39ee9bd995.Fi8bnmt0Ykul6Mhj3kLT5Jr7Pom70Xg2z9QQlNRFXPIscenes-app-data-warehouse-sql-editor--top-tools-per-server--dark:hash: v1.k794b7964.c5aa3840807ca349309a893b884ebc767c8fab70a82127532c1dae27d13f9f3d.51y_th6-WoFAlLgiWfsu6KUr3rxWjZzAbV84FIikvXQscenes-app-data-warehouse-sql-editor--top-tools-per-server--light:diff --git a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsxindex 33dbdd737afc..5755aad85608 100644--- a/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx+++ b/frontend/src/layout/panel-layout/DatabaseTree/DatabaseTree.tsx@@ -13,6 +13,7 @@ import { DATABASE_TREE_COLLAPSE_THRESHOLD, editorSizingLogic } from 'scenes/dataimport { DatabaseSearchField } from 'scenes/data-warehouse/editor/sidebar/DatabaseSearchField'import { QueryDatabase } from 'scenes/data-warehouse/editor/sidebar/QueryDatabase'import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { ExpressionModal } from 'scenes/data-warehouse/ExpressionModal'import { ViewLinkModal } from 'scenes/data-warehouse/ViewLinkModal'import { SyncMoreNotice } from './SyncMoreNotice'@@ -105,6 +106,7 @@ export const DatabaseTree = memo(function DatabaseTree({</div><SyncMoreNotice /><ViewLinkModal />+ <ExpressionModal /></ScrollableShadows><Resizer{...databaseTreeResizerProps}diff --git a/frontend/src/scenes/data-warehouse/ExpressionModal.tsx b/frontend/src/scenes/data-warehouse/ExpressionModal.tsxnew file mode 100644index 000000000000..da41e93ea7f9--- /dev/null+++ b/frontend/src/scenes/data-warehouse/ExpressionModal.tsx@@ -0,0 +1,74 @@+import { useActions, useValues } from 'kea'+import { Field, Form } from 'kea-forms'++import { LemonBanner, LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'++import { CodeEditorInline } from 'lib/monaco/CodeEditorInline'+import { expressionModalLogic } from 'scenes/data-warehouse/expressionModalLogic'++export function ExpressionModal(): JSX.Element {+ const {+ isExpressionModalOpen,+ expressionToEdit,+ expressionSourceQuery,+ selectedTableName,+ error,+ isExpressionFormSubmitting,+ isPostHogTable,+ } = useValues(expressionModalLogic)+ const { closeExpressionModal } = useActions(expressionModalLogic)++ return (+ <LemonModal+ title={expressionToEdit ? 'Edit expression' : 'Add expression'}+ description={+ <span>+ Add a SQL expression as a field on <code>{selectedTableName}</code>. It becomes available in every+ query against this table.+ </span>+ }+ isOpen={isExpressionModalOpen}+ onClose={closeExpressionModal}+ width={600}+ >+ <Form+ logic={expressionModalLogic}+ formKey="expressionForm"+ enableFormOnSubmit+ className="flex flex-col gap-4"+ >+ <Field name="field_name" label="Field name">+ <LemonInput placeholder="for example browser_name" autoFocus={!expressionToEdit} />+ </Field>+ {isPostHogTable ? (+ <LemonBanner type="info">+ PostHog sometimes adds new fields to its built-in tables. If a new field takes this name, the+ built-in field takes precedence and this expression stops applying. Use a unique prefix for your+ field name, for example <code>acme_browser</code> instead of <code>browser</code>.+ </LemonBanner>+ ) : null}+ <Field name="expression" label="Expression">+ {({ value, onChange }) => (+ <CodeEditorInline+ data-attr="expression-modal-editor"+ value={value ?? ''}+ onChange={(newValue) => onChange(newValue ?? '')}+ language="hogQLExpr"+ minHeight="78px"+ sourceQuery={expressionSourceQuery}+ />+ )}+ </Field>+ {error ? <LemonBanner type="error">{error}</LemonBanner> : null}+ <div className="flex flex-row justify-end gap-2">+ <LemonButton type="secondary" onClick={closeExpressionModal}>+ Cancel+ </LemonButton>+ <LemonButton type="primary" htmlType="submit" loading={isExpressionFormSubmitting}>+ {expressionToEdit ? 'Update expression' : 'Add expression'}+ </LemonButton>+ </div>+ </Form>+ </LemonModal>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex aaf6fb1d80b4..d5037bd62166 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -34,6 +34,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { ExpressionModal } from '../ExpressionModal'import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'import { ViewLinkModal } from '../ViewLinkModal'import { connectionSelectorLogic } from './connectionSelectorLogic'@@ -293,6 +294,7 @@ export function SQLEditor({<MaterializationModal tabId={tabId || ''} /><AccessControlModal /><ViewLinkModal />+ <ExpressionModal /></>) : null}</BindLogic>diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsxindex 644bac03795f..93ce60111b83 100644--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx@@ -17,7 +17,7 @@ import {IconExternal,IconPlusSmall,} from '@posthog/icons'-import { LemonDialog } from '@posthog/lemon-ui'+import { LemonDialog, Tooltip } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'import { IconTextSize } from 'lib/lemon-ui/icons'@@ -51,6 +51,7 @@ import {import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { expressionModalLogic } from 'scenes/data-warehouse/expressionModalLogic'import { urls } from 'scenes/urls'import { SearchHighlightMultiple } from '~/layout/navigation-3000/components/SearchHighlight'@@ -166,6 +167,8 @@ export const QueryDatabase = ({deleteDataWarehouseSavedQuery,} = useActions(dataWarehouseViewsLogic)const { deleteJoin } = useActions(sourceManagementLogic)+ const { expressionsByFieldName } = useValues(expressionModalLogic)+ const { openNewExpressionModal, openEditExpressionModal, deleteExpression } = useActions(expressionModalLogic)const { deleteDraft } = useActions(draftsLogic)const {openMaterializationModal,@@ -469,6 +472,10 @@ export const QueryDatabase = ({: nullconst canDragBIField = isBIEditor && !!biField && isBIFieldCompatible(biConfig.source, biField)const columnType = isColumn ? item.record?.field?.type : null+ const savedExpression =+ isColumn && item.record?.table && item.record?.field+ ? expressionsByFieldName[`${item.record.table}.${item.record.field.name}`]+ : nullconst tableKindLabel = !isColumn && item.children?.length ? getTableKindLabel(item) : nullconst certification =item.record?.type === 'table'@@ -537,7 +544,13 @@ export const QueryDatabase = ({</span>)}<TableCertificationIcon certification={certification} />- {isColumn && columnType ? (+ {isColumn && columnType && savedExpression ? (+ <Tooltip title={<code className="text-xs">{savedExpression.expression}</code>}>+ <span className="shrink rounded px-1.5 py-0.5 text-xs text-muted-alt">+ {columnType === 'expression' ? 'expression' : `${columnType} expression`}+ </span>+ </Tooltip>+ ) : isColumn && columnType ? (<span className="shrink rounded px-1.5 py-0.5 text-xs text-muted-alt">{columnType === 'field_traverser' && item?.record?.field.chain? formatTraversalChain(item.record.field.chain)@@ -602,6 +615,35 @@ export const QueryDatabase = ({return joinMenu}+ // Menu for fields backed by a saved expression+ if (item.record?.field && item.record?.table) {+ const expression = expressionsByFieldName[`${item.record.table}.${item.record.field.name}`]+ if (expression) {+ return (+ <DropdownMenuGroup>+ <DropdownMenuItem+ asChild+ onClick={(e) => {+ e.stopPropagation()+ openEditExpressionModal(expression)+ }}+ >+ <ButtonPrimitive menuItem>Edit expression</ButtonPrimitive>+ </DropdownMenuItem>+ <DropdownMenuItem+ asChild+ onClick={(e) => {+ e.stopPropagation()+ deleteExpression(expression)+ }}+ >+ <ButtonPrimitive menuItem>Delete expression</ButtonPrimitive>+ </DropdownMenuItem>+ </DropdownMenuGroup>+ )+ }+ }+// Show menu for draftsif (item.record?.type === 'draft') {const draft = item.record.draft@@ -676,6 +718,25 @@ export const QueryDatabase = ({Add join</ButtonPrimitive></DropdownMenuItem>+ <DropdownMenuItem+ asChild+ onClick={(e) => {+ e.stopPropagation()+ if (addJoinAccessDisabledReason) {+ return+ }+ openNewExpressionModal(item.name)+ }}+ >+ <ButtonPrimitive+ menuItem+ disabledReasons={+ addJoinAccessDisabledReason ? { [addJoinAccessDisabledReason]: true } : {}+ }+ >+ Add expression+ </ButtonPrimitive>+ </DropdownMenuItem><DropdownMenuItemasChildonClick={(e) => {@@ -914,6 +975,27 @@ export const QueryDatabase = ({</ButtonPrimitive></DropdownMenuItem>) : null}+ {addJoinSourceTableName ? (+ <DropdownMenuItem+ asChild+ onClick={(e) => {+ e.stopPropagation()+ if (addJoinAccessDisabledReason) {+ return+ }+ openNewExpressionModal(addJoinSourceTableName)+ }}+ >+ <ButtonPrimitive+ menuItem+ disabledReasons={+ addJoinAccessDisabledReason ? { [addJoinAccessDisabledReason]: true } : {}+ }+ >+ Add expression+ </ButtonPrimitive>+ </DropdownMenuItem>+ ) : null}{item.record.type === 'view' ? (<DropdownMenuItemasChild@@ -1207,7 +1289,23 @@ export const QueryDatabase = ({}}renderItemIcon={(item) => {if (item.record?.type === 'column') {- return getFieldTypeIcon(item.record.field?.type)+ const icon = getFieldTypeIcon(item.record.field?.type)+ const savedExpression =+ item.record?.table && item.record?.field+ ? expressionsByFieldName[`${item.record.table}.${item.record.field.name}`]+ : null+ if (savedExpression) {+ return (+ <span className="relative inline-flex">+ {icon}+ <span+ className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-accent"+ aria-hidden="true"+ />+ </span>+ )+ }+ return icon}return <TreeNodeDisplayIcon item={item} expandedItemIds={expandedItemIds} />}}diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.tsindex ea56429e0cc8..90fd57b4bbae 100644--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts@@ -1,3 +1,4 @@+import { newInternalTab } from 'lib/utils/newInternalTab'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { initKeaTests } from '~/test/init'@@ -10,6 +11,8 @@ import {shouldInitializeDirectConnectionExpandedFolders,} from './queryDatabaseLogic'+jest.mock('lib/utils/newInternalTab')+describe('queryDatabaseLogic', () => {it('groups direct connection tables into schema folders', () => {const grouped = groupDirectConnectionTableNodesBySchema(@@ -283,4 +286,46 @@ describe('queryDatabaseLogic', () => {expect(childNames('sources')).not.toContain("Couldn't load your schema")})})++ describe('direct connection state', () => {+ let logic: ReturnType<typeof queryDatabaseLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = queryDatabaseLogic()+ logic.mount()+ databaseTableListLogic.findMounted()?.actions.setConnection('source-id')+ })++ afterEach(() => {+ logic.unmount()+ jest.clearAllMocks()+ })++ it('shows a direct schema failure and retry at the root of the sidebar', () => {+ databaseTableListLogic.findMounted()?.actions.loadDatabaseFailure('Connection failed.')++ expect(logic.values.displayedTreeData.map((item) => item.name)).toEqual([+ "Couldn't load your schema",+ 'Try again',+ ])+ })++ it('links an empty direct schema to table configuration', () => {+ databaseTableListLogic.findMounted()?.actions.loadDatabaseSuccess({ tables: {}, joins: [] })++ expect(logic.values.displayedTreeData.map((item) => item.name)).toEqual([+ 'No queryable tables',+ 'Configure tables',+ ])++ logic.values.displayedTreeData+ .find((item) => item.record?.type === 'direct-connection-configure')+ ?.onClick?.()++ expect(newInternalTab).toHaveBeenCalledWith(+ expect.stringContaining('/data-management/sources/managed-source-id/schemas')+ )+ })+ })})diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsxindex edf21277182a..d60dd464629f 100644--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx@@ -234,7 +234,7 @@ const shouldHideFieldName = (fieldName: string): boolean => {return fieldName === 'team_id'}-const shouldUseDirectConnectionTree = (connectionId: string | null): boolean => {+const shouldUseDirectConnectionTree = (connectionId: string | null): connectionId is string => {return !!connectionId && connectionId !== POSTHOG_WAREHOUSE}@@ -394,6 +394,30 @@ const createSchemaErrorNodes = (prefix: string, onRetry: () => void): TreeDataIt},]+const createDirectConnectionEmptyNodes = (connectionId: string): TreeDataItem[] => [+ {+ id: 'direct-connection-empty/',+ name: 'No queryable tables',+ displayName: <>No queryable tables</>,+ icon: <IconDatabase />,+ disableSelect: true,+ type: 'node',+ record: {+ type: 'direct-connection-empty',+ },+ },+ {+ id: 'direct-connection-configure/',+ name: 'Configure tables',+ displayName: <>Configure tables</>,+ icon: <IconPlus />,+ onClick: () => newInternalTab(urls.dataWarehouseSource(`managed-${connectionId}`, 'schemas')),+ record: {+ type: 'direct-connection-configure',+ },+ },+]+const createLazyTableEmptyNode = (lazyNodeId: string): TreeDataItem => {return {id: `${lazyNodeId}-empty/`,@@ -1812,7 +1836,10 @@ export interface queryDatabaseLogicMeta {| {job_inputs?: Record<string, any>}- | undefined+ | undefined,+ databaseLoading: boolean,+ databaseLoadError: string | null,+ allTablesMap: Record<string, DatabaseSchemaTable>) => TreeDataItem[]activeExpandedFolderIds: (searchTerm: string,@@ -2868,13 +2895,25 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([},],displayedTreeData: [- (s) => [s.searchTerm, s.searchTreeData, s.treeData, s.connectionId, s.selectedDirectSource],+ (s) => [+ s.searchTerm,+ s.searchTreeData,+ s.treeData,+ s.connectionId,+ s.selectedDirectSource,+ s.databaseLoading,+ s.databaseLoadError,+ s.allTablesMap,+ ],(searchTerm: string,searchTreeData: TreeDataItem[],treeData: TreeDataItem[],connectionId: string | null,- selectedDirectSource: { job_inputs?: Record<string, any> } | undefined+ selectedDirectSource: { job_inputs?: Record<string, any> } | undefined,+ databaseLoading: boolean,+ databaseLoadError: string | null,+ allTablesMap: Record<string, DatabaseSchemaTable>): TreeDataItem[] => {const sourceData = searchTerm ? searchTreeData : treeData@@ -2918,6 +2957,17 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([additionalItems.push(item)})+ const hasLoadedTables = Object.keys(allTablesMap).length > 0+ if (!databaseLoading && databaseLoadError) {+ return [+ ...createSchemaErrorNodes('direct-connection', () => actions.refreshDatabaseSchema()),+ ...additionalItems,+ ]+ }+ if (!databaseLoading && !hasLoadedTables) {+ return [...createDirectConnectionEmptyNodes(connectionId), ...additionalItems]+ }+return [...groupDirectConnectionTableNodesBySchema(flattenedTables, !!searchTerm, defaultSchemaName),...(flattenedViews.length > 0diff --git a/frontend/src/scenes/data-warehouse/expressionModalLogic.test.ts b/frontend/src/scenes/data-warehouse/expressionModalLogic.test.tsnew file mode 100644index 000000000000..dc77214e2a4e--- /dev/null+++ b/frontend/src/scenes/data-warehouse/expressionModalLogic.test.ts@@ -0,0 +1,44 @@+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'++import { NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { warehouseExpressionsList } from 'products/data_warehouse/frontend/generated/api'++import { expressionModalLogic } from './expressionModalLogic'++jest.mock('products/data_warehouse/frontend/generated/api', () => ({+ warehouseExpressionsList: jest.fn(),+}))++const mockWarehouseExpressionsList = warehouseExpressionsList as jest.Mock++describe('expressionModalLogic', () => {+ let databaseLogic: ReturnType<typeof databaseTableListLogic.build>+ let logic: ReturnType<typeof expressionModalLogic.build>++ beforeEach(() => {+ initKeaTests()+ mockWarehouseExpressionsList.mockReset().mockResolvedValue({ results: [] })+ databaseLogic = databaseTableListLogic()+ databaseLogic.mount()+ logic = expressionModalLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ databaseLogic.unmount()+ })++ it('scopes the expression editor query to the active connection', () => {+ databaseLogic.actions.setConnection('connection-123')+ logic.actions.openNewExpressionModal('auth_group')++ expect(logic.values.expressionSourceQuery).toEqual({+ kind: NodeKind.HogQLQuery,+ query: 'SELECT * FROM auth_group',+ connectionId: 'connection-123',+ })+ })+})diff --git a/frontend/src/scenes/data-warehouse/expressionModalLogic.tsx b/frontend/src/scenes/data-warehouse/expressionModalLogic.tsxnew file mode 100644index 000000000000..7585d692d3f9--- /dev/null+++ b/frontend/src/scenes/data-warehouse/expressionModalLogic.tsx@@ -0,0 +1,327 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { deleteWithUndo } from 'lib/utils/deleteWithUndo'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'+import { teamLogic } from 'scenes/teamLogic'++import { DatabaseSchemaTable, HogQLQuery, NodeKind } from '~/queries/schema/schema-general'++import {+ warehouseExpressionsCreate,+ warehouseExpressionsList,+ warehouseExpressionsPartialUpdate,+} from 'products/data_warehouse/frontend/generated/api'+import type { DataWarehouseExpressionApi } from 'products/data_warehouse/frontend/generated/api.schemas'++export interface ExpressionFormValues {+ field_name: string+ expression: string+}++const NEW_EXPRESSION: ExpressionFormValues = { field_name: '', expression: '' }++// Mirrors the backend whitelist in DataWarehouseExpressionSerializer.+const FIELD_NAME_REGEX = /^[A-Za-z_$][A-Za-z0-9_$]*$/++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface expressionModalLogicValues {+ allTablesMap: Record<string, DatabaseSchemaTable> // databaseTableListLogic+ connectionId: string | null // databaseTableListLogic+ currentTeamId: number | null // teamLogic+ activeConnectionId: string | null+ error: string | null+ expressionForm: ExpressionFormValues+ expressionFormAllErrors: Record<string, any>+ expressionFormChanged: boolean+ expressionFormErrors: DeepPartialMap<ExpressionFormValues, ValidationErrorType>+ expressionFormHasErrors: boolean+ expressionFormManualErrors: Record<string, any>+ expressionFormTouched: boolean+ expressionFormTouches: Record<string, boolean>+ expressionFormValidationErrors: DeepPartialMap<ExpressionFormValues, ValidationErrorType>+ expressionSourceQuery: HogQLQuery | undefined+ expressionToEdit: DataWarehouseExpressionApi | null+ expressions: DataWarehouseExpressionApi[]+ expressionsByFieldName: Record<string, DataWarehouseExpressionApi>+ expressionsLoading: boolean+ isExpressionFormSubmitting: boolean+ isExpressionFormValid: boolean+ isExpressionModalOpen: boolean+ isPostHogTable: boolean+ selectedTableName: string | null+ showExpressionFormErrors: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface expressionModalLogicActions {+ loadDatabase: (+ args_0?:+ | {+ force?: boolean+ }+ | undefined+ ) => {+ force?: boolean+ } // databaseTableListLogic+ closeExpressionModal: () => {+ value: true+ }+ deleteExpression: (expression: DataWarehouseExpressionApi) => {+ expression: DataWarehouseExpressionApi+ }+ loadExpressions: () => any+ loadExpressionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadExpressionsSuccess: (+ expressions: DataWarehouseExpressionApi[],+ payload?: any+ ) => {+ expressions: DataWarehouseExpressionApi[]+ payload?: any+ }+ openEditExpressionModal: (expression: DataWarehouseExpressionApi) => {+ expression: DataWarehouseExpressionApi+ }+ openNewExpressionModal: (tableName: string) => {+ tableName: string+ }+ resetExpressionForm: (values?: ExpressionFormValues) => {+ values?: ExpressionFormValues+ }+ setError: (error: string | null) => {+ error: string | null+ }+ setExpressionFormManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setExpressionFormValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setExpressionFormValues: (values: DeepPartial<ExpressionFormValues>) => {+ values: DeepPartial<ExpressionFormValues>+ }+ submitExpressionForm: () => {+ value: boolean+ }+ submitExpressionFormFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitExpressionFormRequest: (expressionForm: ExpressionFormValues) => {+ expressionForm: ExpressionFormValues+ }+ submitExpressionFormSuccess: (expressionForm: ExpressionFormValues) => {+ expressionForm: ExpressionFormValues+ }+ touchExpressionFormField: (key: string) => {+ key: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface expressionModalLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ activeConnectionId: (connectionId: string | null) => string | null+ expressionSourceQuery: (+ selectedTableName: string | null,+ activeConnectionId: string | null+ ) => HogQLQuery | undefined+ isPostHogTable: (selectedTableName: string | null, allTablesMap: Record<string, DatabaseSchemaTable>) => boolean+ expressionsByFieldName: (+ expressions: DataWarehouseExpressionApi[],+ activeConnectionId: string | null+ ) => Record<string, DataWarehouseExpressionApi>+ }+}++export type expressionModalLogicType = MakeLogicType<+ expressionModalLogicValues,+ expressionModalLogicActions,+ Record<string, any>,+ expressionModalLogicMeta+>++export const expressionModalLogic = kea<expressionModalLogicType>([+ path(['scenes', 'data-warehouse', 'expressionModalLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId'], databaseTableListLogic, ['connectionId', 'allTablesMap']],+ actions: [databaseTableListLogic, ['loadDatabase']],+ })),+ actions({+ openNewExpressionModal: (tableName: string) => ({ tableName }),+ openEditExpressionModal: (expression: DataWarehouseExpressionApi) => ({ expression }),+ closeExpressionModal: true,+ deleteExpression: (expression: DataWarehouseExpressionApi) => ({ expression }),+ setError: (error: string | null) => ({ error }),+ }),+ loaders(({ values }) => ({+ expressions: [+ [] as DataWarehouseExpressionApi[],+ {+ loadExpressions: async () => {+ const response = await warehouseExpressionsList(String(values.currentTeamId))+ return response.results+ },+ },+ ],+ })),+ forms(({ actions, values }) => ({+ expressionForm: {+ defaults: NEW_EXPRESSION,+ errors: ({ field_name, expression }) => ({+ field_name: !field_name+ ? 'Enter a field name'+ : !FIELD_NAME_REGEX.test(field_name)+ ? "Use only letters, numbers, underscores and $. The name can't start with a number."+ : undefined,+ expression: !expression ? 'Enter an expression' : undefined,+ }),+ submit: async ({ field_name, expression }) => {+ if (!values.selectedTableName) {+ return+ }+ try {+ if (values.expressionToEdit) {+ await warehouseExpressionsPartialUpdate(+ String(values.currentTeamId),+ values.expressionToEdit.id,+ { field_name, expression }+ )+ lemonToast.success('Expression updated')+ } else {+ await warehouseExpressionsCreate(String(values.currentTeamId), {+ table_name: values.selectedTableName,+ field_name,+ expression,+ connection_id: values.activeConnectionId,+ })+ lemonToast.success('Expression created')+ }+ actions.closeExpressionModal()+ actions.loadExpressions()+ actions.loadDatabase()+ } catch (error: any) {+ actions.setError(error.detail ?? "Couldn't save the expression. Check it and try again.")+ throw error+ }+ },+ },+ })),+ reducers({+ isExpressionModalOpen: [+ false,+ {+ openNewExpressionModal: () => true,+ openEditExpressionModal: () => true,+ closeExpressionModal: () => false,+ },+ ],+ expressionToEdit: [+ null as DataWarehouseExpressionApi | null,+ {+ openNewExpressionModal: () => null,+ openEditExpressionModal: (_, { expression }) => expression,+ closeExpressionModal: () => null,+ },+ ],+ selectedTableName: [+ null as string | null,+ {+ openNewExpressionModal: (_, { tableName }) => tableName,+ openEditExpressionModal: (_, { expression }) => expression.table_name,+ closeExpressionModal: () => null,+ },+ ],+ error: [+ null as string | null,+ {+ openNewExpressionModal: () => null,+ openEditExpressionModal: () => null,+ closeExpressionModal: () => null,+ setError: (_, { error }) => error,+ },+ ],+ }),+ selectors({+ activeConnectionId: [+ (s) => [s.connectionId],+ (connectionId: string | null): string | null =>+ connectionId && connectionId !== POSTHOG_WAREHOUSE ? connectionId : null,+ ],+ expressionSourceQuery: [+ (s) => [s.selectedTableName, s.activeConnectionId],+ (selectedTableName: string | null, activeConnectionId: string | null): HogQLQuery | undefined =>+ selectedTableName+ ? {+ kind: NodeKind.HogQLQuery,+ query: `SELECT * FROM ${selectedTableName}`,+ connectionId: activeConnectionId ?? undefined,+ }+ : undefined,+ ],+ // Reflects the database loaded for the active connection: a direct connection's+ // database contains no posthog-type tables, so the shadowing notice stays hidden there.+ isPostHogTable: [+ (s) => [s.selectedTableName, s.allTablesMap],+ (selectedTableName: string | null, allTablesMap: Record<string, DatabaseSchemaTable>): boolean => {+ const tableType = selectedTableName ? allTablesMap[selectedTableName]?.type : undefined+ return tableType === 'posthog' || tableType === 'system'+ },+ ],+ // Only expressions scoped to the active connection (null scope means the default warehouse)+ expressionsByFieldName: [+ (s) => [s.expressions, s.activeConnectionId],+ (+ expressions: DataWarehouseExpressionApi[],+ activeConnectionId: string | null+ ): Record<string, DataWarehouseExpressionApi> =>+ Object.fromEntries(+ expressions+ .filter((expression) => (expression.connection_id ?? null) === activeConnectionId)+ .map((expression) => [`${expression.table_name}.${expression.field_name}`, expression])+ ),+ ],+ }),+ listeners(({ actions, values }) => ({+ openNewExpressionModal: () => {+ actions.resetExpressionForm()+ },+ openEditExpressionModal: ({ expression }) => {+ actions.resetExpressionForm({+ field_name: expression.field_name,+ expression: expression.expression,+ })+ },+ deleteExpression: ({ expression }) => {+ void deleteWithUndo({+ endpoint: `projects/${values.currentTeamId}/warehouse_expressions`,+ object: { ...expression, name: `${expression.field_name} on ${expression.table_name}` },+ callback: () => {+ actions.loadExpressions()+ actions.loadDatabase()+ },+ })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadExpressions()+ }),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a06c06fc82a4..34452449e95c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6019,6 +6019,7 @@ export enum ActivityScope {OAUTH_APPLICATION = 'OAuthApplication',LEGAL_DOCUMENT = 'LegalDocument',ERROR_TRACKING_ISSUE = 'ErrorTrackingIssue',+ DATA_WAREHOUSE_EXPRESSION = 'DataWarehouseExpression',DATA_WAREHOUSE_SAVED_QUERY = 'DataWarehouseSavedQuery',USER_INTERVIEW = 'UserInterview',TAG = 'Tag',diff --git a/posthog/api/test/__snapshots__/test_element.ambr b/posthog/api/test/__snapshots__/test_element.ambrindex 24ab3ad33064..5148b51a1e6c 100644--- a/posthog/api/test/__snapshots__/test_element.ambr+++ b/posthog/api/test/__snapshots__/test_element.ambr@@ -222,141 +222,21 @@# ---# name: TestElement.test_element_stats_postgres_queries_are_as_expected.13'''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."event_retention_months",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."llm_gateway_overspend_allowance_usd",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model",- "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_hipaa",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_team"- INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")- WHERE "posthog_team"."id" = 99999- ORDER BY "posthog_team"."id" ASC- LIMIT 1+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)'''# ---# name: TestElement.test_element_stats_postgres_queries_are_as_expected.2diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.pyindex c1cdf0146b11..4b53ce576c9b 100644--- a/posthog/api/test/test_event.py+++ b/posthog/api/test/test_event.py@@ -107,8 +107,9 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):# sparse dataset; the schema is built once and shared). Group-type-mapping is read via# personhog, not Postgres, so it's not in this count. Was 16 before passing team=team# into get_restricted_properties_for_team, which lets is_property_access_control_enabled- # skip its per-call Team+organization lookup.- with self.assertNumQueries(15):+ # skip its per-call Team+organization lookup. +1 for the saved-expressions fetch in the+ # HogQL database build.+ with self.assertNumQueries(16):response = self.client.get(f"/api/projects/{self.team.id}/events/?event=event_name").json()assert response["results"][0]["event"] == "event_name"@@ -139,7 +140,8 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):# Group-type-mapping is read via personhog, not Postgres, so it's not in this count.# Was 24 before passing team=team into get_restricted_properties_for_team, which lets# is_property_access_control_enabled skip its per-call Team+organization lookup.- expected_queries = 22 if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else 23+ # +1 for the saved-expressions fetch in the HogQL database build.+ expected_queries = 23 if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else 24with self.assertNumQueries(expected_queries):response = self.client.get(diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex 4e3a5abc4c28..b1b694b3fae6 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -1741,8 +1741,9 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):returned_ids = []# The property-access-control feature check reuses the request's already-loaded team,- # so listing persons no longer pays a per-request Team lookup (was 16).- with self.assertNumQueries(15):+ # so listing persons no longer pays a per-request Team lookup (was 16). +1 for the+ # saved-expressions fetch in the HogQL database build.+ with self.assertNumQueries(16):response = self.client.get("/api/person/?limit=10").json()self.assertEqual(len(response["results"]), 9)returned_ids += [x["distinct_ids"][0] for x in response["results"]]@@ -1753,8 +1754,9 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):created_ids.reverse() # ids are returned in desc orderself.assertEqual(returned_ids, created_ids, returned_ids)- # 15 as above, plus the include_total counting queries (was 20).- with self.assertNumQueries(19):+ # 16 as above, plus the include_total counting queries (was 20); the count runs a second+ # HogQL database build, which pays the saved-expressions fetch again.+ with self.assertNumQueries(21):response_include_total = self.client.get("/api/person/?limit=10&include_total").json()self.assertEqual(response_include_total["count"], 20) # With `include_total`, the total count is returned toodiff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 417dbbb37f6d..111ac0c2e84d 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -180,6 +180,7 @@ if TYPE_CHECKING:from posthog.shared_link_user import SharedLinkUserfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+ from products.data_tools.backend.models.expression import DataWarehouseExpressionfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.revenue_analytics.backend.views import RevenueAnalyticsBaseViewfrom products.warehouse_sources.backend.facade.models import (@@ -229,6 +230,7 @@ class HogQLDatabaseSources:revenue_views: list[RevenueAnalyticsBaseView]warehouse_tables: list[DataWarehouseTable] # filtered to what build needs, schemas preloadeddata_warehouse_joins: list[DataWarehouseJoin]+ data_warehouse_expressions: list[DataWarehouseExpression]# dataWarehouseEventsModifiers path: saved query per modifier table name (None if no matching row).event_modifier_saved_queries: dict[str, Optional[DataWarehouseSavedQuery]]# Dual-mode: a synced (warehouse) source queried live via connection_id. Its physical rows are@@ -886,6 +888,18 @@ class Database(BaseModel):self._denied_tables.add(saved_query.name)return True+ def _is_warehouse_expression_denied(self, expression: Any) -> bool:+ """+ Expression counterpart of `_is_warehouse_view_denied`: a user denied access to a saved+ expression doesn't get its virtual field injected, so their queries see "Field not found".+ Userless context (no UserAccessControl) fails closed - every expression is denied.+ """+ uac = self.user_access_control+ return not (+ uac is not None+ and (uac.is_organization_admin or uac.check_access_level_for_object(expression, required_level="viewer"))+ )+def serialize(self,context: HogQLContext,@@ -1265,6 +1279,7 @@ class Database(BaseModel):from posthog.shared_link_user import SharedLinkUser # noqa: PLC0415from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery # noqa: PLC0415+ from products.data_tools.backend.models.expression import DataWarehouseExpression # noqa: PLC0415from products.data_tools.backend.models.join import DataWarehouseJoin # noqa: PLC0415from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415DataWarehouseTable,@@ -1499,6 +1514,20 @@ class Database(BaseModel):with timings.measure("data_warehouse_joins", emit_span=True):data_warehouse_joins = list(DataWarehouseJoin.objects.filter(team_id=team.pk).exclude(deleted=True))+ with timings.measure("data_warehouse_expressions", emit_span=True):+ # canonical=True with the already-loaded team: for_team's own resolution queries the+ # default DB, which some callers (e.g. ClickHouse-backed tests) can't reach.+ expressions_query = DataWarehouseExpression.objects.for_team(+ team.parent_team_id or team.pk, canonical=True+ ).exclude(deleted=True)+ # An expression is scoped either to one connection's direct-query database or to the+ # default warehouse database; never both.+ if is_direct_query:+ expressions_query = expressions_query.filter(connection_id=connection_id)+ else:+ expressions_query = expressions_query.filter(connection_id__isnull=True)+ data_warehouse_expressions = list(expressions_query)+with timings.measure("attach_credentials", emit_span=True):# Tables and view-backing tables share the credential pool; attach across all of them.credentialed_tables: list[DataWarehouseTable] = [*warehouse_tables]@@ -1551,6 +1580,7 @@ class Database(BaseModel):revenue_views=revenue_views,warehouse_tables=warehouse_tables,data_warehouse_joins=data_warehouse_joins,+ data_warehouse_expressions=data_warehouse_expressions,event_modifier_saved_queries=event_modifier_saved_queries,virtual_source=virtual_source,virtual_schemas=virtual_schemas,@@ -2176,6 +2206,31 @@ class Database(BaseModel):except Exception as e:capture_exception(e)+ # After joins, so a saved expression can never shadow a join field either.+ with timings.measure("data_warehouse_expressions", emit_span=True):+ for saved_expression in sources.data_warehouse_expressions:+ if (+ sources.is_hogql_warehouse_access_control_enabled+ and not sources.bypass_warehouse_access_control+ and database._is_warehouse_expression_denied(saved_expression)+ ):+ continue+ if not database.has_table(saved_expression.table_name):+ continue+ try:+ expression_table = database.get_table(saved_expression.table_name)+ # Expressions must never override existing fields; first-come-first-served on the+ # off chance duplicates exist.+ if saved_expression.field_name in expression_table.fields:+ continue+ expression_table.fields[saved_expression.field_name] = ExpressionField(+ name=saved_expression.field_name,+ expr=parse_expr(saved_expression.expression),+ isolate_scope=True,+ )+ except Exception as e:+ capture_exception(e)+database.apply_schema_scope()return database@@ -2769,11 +2824,16 @@ def serialize_fields())elif isinstance(field, ExpressionField):- field_expr = resolve_types_from_table(field.expr, table_chain, context, "hogql")- assert field_expr.type is not None- constant_type = field_expr.type.resolve_constant_type(context)-- field_type = _constant_type_to_serialized_field_type(constant_type)+ # A stale expression (e.g. a saved expression whose referenced column was since+ # removed) must degrade to a generic "expression" field instead of failing the+ # whole schema serialization.+ try:+ field_expr = resolve_types_from_table(field.expr, table_chain, context, "hogql")+ assert field_expr.type is not None+ constant_type = field_expr.type.resolve_constant_type(context)+ field_type = _constant_type_to_serialized_field_type(constant_type)+ except Exception:+ field_type = Noneif field_type is None:field_type = DatabaseSerializedFieldType.EXPRESSIONdiff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 9703e45a73f2..8b06e40ce08a 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -226,6 +226,79 @@'''# ---# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.10+ '''+ SELECT "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."column_order",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in"+ FROM "posthog_datawarehousetable"+ LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")+ WHERE ("posthog_datawarehousetable"."team_id" = 99999+ AND NOT ("posthog_datawarehousetable"."deleted"+ AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."access_method" = 'direct'+ AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC+ '''+# ---+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.11'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -245,7 +318,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.11+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.13'''SELECT "posthog_datawarehousecredential"."created_by_id","posthog_datawarehousecredential"."created_at",@@ -395,6 +487,25 @@'''# ---# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.5+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.6'''SELECT "posthog_datawarehousecredential"."created_by_id","posthog_datawarehousecredential"."created_at",@@ -412,7 +523,7 @@AND "posthog_datawarehousecredential"."team_id" = 99999)'''# ----# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.6+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.7'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -514,7 +625,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.7+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.8'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -608,7 +719,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.8+# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.9'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -646,79 +757,6 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.9- '''- SELECT "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_datawarehousetable"- LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")- WHERE ("posthog_datawarehousetable"."team_id" = 99999- AND NOT ("posthog_datawarehousetable"."deleted"- AND "posthog_datawarehousetable"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."access_method" = 'direct'- AND "posthog_externaldatasource"."access_method" IS NOT NULL))- ORDER BY "posthog_datawarehousetable"."created_at" DESC- '''-# ---# name: TestDatabase.test_serialize_database_no_person_on_events'''{diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex c35824048787..5d365eccf918 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -763,8 +763,9 @@ class TestDatabase(BaseTest, QueryMatchingTest):)# initialization team query doesn't run; the extra query is the single bulk credential fetch- # (credentials are decrypted once each here instead of re-decrypted per table/view row)- with self.assertNumQueries(6):+ # (credentials are decrypted once each here instead of re-decrypted per table/view row),+ # plus the saved-expressions fetch+ with self.assertNumQueries(7):modifiers = create_default_modifiers_for_team(self.team, modifiers=HogQLQueryModifiers(useMaterializedViews=True))diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.pyindex 24f0dfc64143..5230b541e9af 100644--- a/posthog/hogql/printer/postgres.py+++ b/posthog/hogql/printer/postgres.py@@ -191,6 +191,14 @@ class PostgresPrinter(BasePrinter):if func_name == "count" and not args and not node.distinct:# ClickHouse's zero-arg count() is spelled count(*) everywhere else.args_str = "*"+ elif func_name == "concat":+ # concat(any...) cannot infer psycopg's untyped string parameters without an explicit cast.+ args_str = ", ".join(+ f"CAST({rendered_arg} AS TEXT)"+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str)+ else rendered_arg+ for arg, rendered_arg in zip(node.args, args, strict=True)+ )if node.distinct:args_str = f"DISTINCT {args_str}"diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 9a7051c99ee7..39205b99ee0a 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -6796,6 +6796,15 @@ class TestPostgresPrinter(BaseTest):def test_null_comparisons_in_postgres(self, _name: str, expr: str, expected: str):self.assertEqual(self._expr(expr), expected)+ def test_concat_casts_bound_string_parameters_to_text(self):+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)++ self.assertEqual(+ self._expr("f'{event} {event}'", context=context),+ "concat(events.event, CAST(%(hogql_val_0)s AS TEXT), events.event)",+ )+ self.assertEqual(context.values, {"hogql_val_0": " "})+@parameterized.expand([(diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 5bf2f2036e29..3f0dadf874a3 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -2342,8 +2342,9 @@ class Resolver(CloningVisitor):node.type = loop_typeif isinstance(node.type, ast.ExpressionFieldType):- # only swap out expression fields in ClickHouse- if self.dialect == "clickhouse":+ # HogQL preserves the virtual field name for display; execution dialects must expand+ # the expression so its child fields resolve before the target printer sees them.+ if self.dialect != "hogql":new_expr = clone_expr(node.type.expr)new_node: ast.Expr = ast.Alias(alias=node.type.name, expr=new_expr, hidden=True)@@ -2353,7 +2354,16 @@ class Resolver(CloningVisitor):table_type = table_type.table_typeself.scopes.append(ast.SelectQueryType(tables={node.type.name: table_type}))- new_node = self.visit(new_node)+ try:+ new_node = self.visit(new_node)+ except RecursionError:+ # Saved expressions are validated against a database that may not yet contain a+ # concurrently-saved sibling, so a mutually recursive pair can reach this point.+ # Surface it as a query error instead of a 500.+ raise QueryError(+ f'Expression field "{node.type.name}" is nested too deeply. '+ f"Expression fields can't reference themselves, directly or through another expression."+ )if node.type.isolate_scope:self.scopes.pop()diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex c7afc5f29b7a..799d19b8009b 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -53,6 +53,7 @@ ActivityScope = Literal["Team","Project","ErrorTrackingIssue",+ "DataWarehouseExpression","DataWarehouseSavedQuery","LegalDocument","Organization",@@ -657,6 +658,7 @@ field_exclusions: dict[AuditableScope, list[str]] = {"_old_api_token",],"Project": ["id", "created_at"],+ "DataWarehouseExpression": ["deleted_at"],"DataWarehouseSavedQuery": ["name","columns",diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex ea2469bc6bb6..1193bd329a07 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -464,6 +464,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:return "warehouse_view"if name == "datawarehousesavedqueryfolder":return "warehouse_view"+ if name == "datawarehouseexpression":+ return "warehouse_view"if name == "datawarehousetable":return "warehouse_table"if name == "customerjourney":diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambrindex a0442a4ca297..34ea2189a202 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr@@ -1371,6 +1371,25 @@'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.33+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.34'''SELECT "posthog_propertydefinition"."id","posthog_propertydefinition"."team_id",@@ -1394,7 +1413,7 @@5 /* ... */))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.34+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.35'''SELECT COUNT(*)FROM@@ -1403,7 +1422,7 @@WHERE "ee_single_session_summary"."team_id" = 99999) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.35+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.36'''SELECT "posthog_user"."id","posthog_user"."password",@@ -1449,7 +1468,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.36+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.37'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -1493,7 +1512,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.37+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.38'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1633,7 +1652,7 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.38+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.39'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -1686,31 +1705,6 @@LIMIT 21'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.39- '''- SELECT "ee_accesscontrol"."id",- "ee_accesscontrol"."team_id",- "ee_accesscontrol"."access_level",- "ee_accesscontrol"."resource",- "ee_accesscontrol"."resource_id",- "ee_accesscontrol"."organization_member_id",- "ee_accesscontrol"."role_id",- "ee_accesscontrol"."created_by_id",- "ee_accesscontrol"."created_at",- "ee_accesscontrol"."updated_at",- "posthog_team"."organization_id" AS "_team_organization_id"- FROM "ee_accesscontrol"- INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")- LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")- WHERE (("ee_accesscontrol"."organization_member_id" IS NULL- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999)- OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999))- '''-# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.4'''SELECT "posthog_organization"."id",@@ -1756,6 +1750,31 @@'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.40+ '''+ SELECT "ee_accesscontrol"."id",+ "ee_accesscontrol"."team_id",+ "ee_accesscontrol"."access_level",+ "ee_accesscontrol"."resource",+ "ee_accesscontrol"."resource_id",+ "ee_accesscontrol"."organization_member_id",+ "ee_accesscontrol"."role_id",+ "ee_accesscontrol"."created_by_id",+ "ee_accesscontrol"."created_at",+ "ee_accesscontrol"."updated_at",+ "posthog_team"."organization_id" AS "_team_organization_id"+ FROM "ee_accesscontrol"+ INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")+ LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")+ WHERE (("ee_accesscontrol"."organization_member_id" IS NULL+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999)+ OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999))+ '''+# ---+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.41'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -1806,7 +1825,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.41+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.42'''SELECT COUNT(*) AS "__count"FROM "posthog_sessionrecordingplaylist"@@ -1817,7 +1836,7 @@AND NOT "posthog_sessionrecordingplaylist"."deleted")'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.42+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.43'''SELECT "posthog_sessionrecordingplaylist"."id","posthog_sessionrecordingplaylist"."short_id",@@ -2032,7 +2051,7 @@LIMIT 93'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.43+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.44'''SELECT "posthog_sessionrecordingplaylistitem"."playlist_id" AS "playlist_id",COUNT("posthog_sessionrecordingplaylistitem"."id") AS "c"@@ -2049,7 +2068,7 @@GROUP BY 1'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.44+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.45'''SELECT "posthog_sessionrecordingplaylistitem"."playlist_id" AS "playlist_id","posthog_sessionrecordingplaylistitem"."recording_id" AS "recording_id"@@ -2063,7 +2082,7 @@5 /* ... */))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.45+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.46'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -2072,7 +2091,7 @@AND "posthog_sessionrecordingviewed"."session_id" IN ('00000000-0000-0000-0000-000000000000'))'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.46+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.47'''SELECT COUNT(*) AS "__count"FROM "posthog_sessionrecordingviewed"@@ -2080,7 +2099,7 @@AND "posthog_sessionrecordingviewed"."user_id" = 99999)'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.47+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.48'''SELECT COUNT(*)FROM@@ -2092,7 +2111,7 @@AND NOT ("posthog_comment"."item_id" IS NULL))) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.48+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.49'''SELECT COUNT(*)FROM@@ -2103,21 +2122,6 @@AND NOT ("posthog_sharingconfiguration"."recording_id" IS NULL))) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.49- '''- SELECT COUNT(*)- FROM- (SELECT DISTINCT ("posthog_exportedasset"."export_context" -> 'session_recording_id') AS "export_context__session_recording_id"- FROM "posthog_exportedasset"- WHERE (("posthog_exportedasset"."expires_after" >= '2025-01-01 12:00:00+00:00'::timestamptz- OR "posthog_exportedasset"."expires_after" IS NULL)- AND "posthog_exportedasset"."team_id" = 99999- AND "posthog_exportedasset"."export_context" ? 'session_recording_id'- AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') IS NULL)- AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') = '""'::jsonb- AND "posthog_exportedasset"."export_context" IS NOT NULL))) subquery- '''-# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.5'''SELECT "posthog_team"."id",@@ -2259,6 +2263,21 @@'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.50+ '''+ SELECT COUNT(*)+ FROM+ (SELECT DISTINCT ("posthog_exportedasset"."export_context" -> 'session_recording_id') AS "export_context__session_recording_id"+ FROM "posthog_exportedasset"+ WHERE (("posthog_exportedasset"."expires_after" >= '2025-01-01 12:00:00+00:00'::timestamptz+ OR "posthog_exportedasset"."expires_after" IS NULL)+ AND "posthog_exportedasset"."team_id" = 99999+ AND "posthog_exportedasset"."export_context" ? 'session_recording_id'+ AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') IS NULL)+ AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') = '""'::jsonb+ AND "posthog_exportedasset"."export_context" IS NOT NULL))) subquery+ '''+# ---+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.51'''SELECT COUNT(*)FROMdiff --git a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambrindex 85b7e086ad1f..45e8f7dd3a23 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr@@ -191,6 +191,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -221,7 +240,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.13+# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -232,7 +251,7 @@'old_session'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.14+# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -245,7 +264,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.15+# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -960,6 +979,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -989,7 +1027,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.13+# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -999,7 +1037,7 @@'session1'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.14+# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -1011,7 +1049,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.15+# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -1725,6 +1763,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -1753,7 +1810,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.13+# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -1762,7 +1819,7 @@AND "posthog_sessionrecordingviewed"."session_id" IN ('session_with_duration'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.14+# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -1773,7 +1830,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.15+# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -2486,6 +2543,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -2514,7 +2590,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.13+# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -2523,7 +2599,7 @@AND "posthog_sessionrecordingviewed"."session_id" IN ('session_many_ids'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.14+# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -2534,7 +2610,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.15+# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -3247,6 +3323,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -3276,7 +3371,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.13+# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -3286,7 +3381,7 @@'at_base_time'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.14+# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -3298,7 +3393,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.15+# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -4012,6 +4107,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -4041,7 +4155,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.13+# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -4051,7 +4165,7 @@'at_base_time'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.14+# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -4063,7 +4177,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.15+# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -4777,6 +4891,25 @@'''# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.12+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.13'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -4806,7 +4939,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.13+# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.14'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -4816,7 +4949,7 @@'at_base_time_plus_20'))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.14+# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.15'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -4828,7 +4961,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.15+# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.16'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -5470,25 +5603,63 @@# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.100'''- SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",- ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",- "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"- FROM "ee_single_session_summary"- WHERE ("ee_single_session_summary"."session_id" IN ('6',- '5',- '4',- '3',- '2',- '1')- AND "ee_single_session_summary"."team_id" = 99999- AND "ee_single_session_summary"."extra_summary_context" IS NULL)- ORDER BY 1 ASC,- "ee_single_session_summary"."created_at" DESC+ SELECT "posthog_externaldatasource"."created_by_id",+ "posthog_externaldatasource"."created_at",+ "posthog_externaldatasource"."updated_at",+ "posthog_externaldatasource"."deleted",+ "posthog_externaldatasource"."deleted_at",+ "posthog_externaldatasource"."id",+ "posthog_externaldatasource"."source_id",+ "posthog_externaldatasource"."connection_id",+ "posthog_externaldatasource"."destination_id",+ "posthog_externaldatasource"."team_id",+ "posthog_externaldatasource"."sync_frequency",+ "posthog_externaldatasource"."status",+ "posthog_externaldatasource"."source_type",+ "posthog_externaldatasource"."api_version",+ "posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."connection_metadata",+ "posthog_externaldatasource"."are_tables_created",+ "posthog_externaldatasource"."prefix",+ "posthog_externaldatasource"."description",+ "posthog_externaldatasource"."created_via",+ "posthog_externaldatasource"."access_method",+ "posthog_externaldatasource"."direct_query_enabled",+ "posthog_externaldatasource"."auto_sync_new_schemas",+ "posthog_externaldatasource"."auto_sync_schema_patterns",+ "posthog_externaldatasource"."revenue_analytics_enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",+ "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"+ FROM "posthog_externaldatasource"+ LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")+ WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')+ AND "posthog_externaldatasource"."team_id" = 99999+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.101'''- SELECT "posthog_user"."id",+ SELECT "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."column_order",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib",+ "posthog_user"."id","posthog_user"."password","posthog_user"."last_login","posthog_user"."first_name",@@ -5503,6 +5674,7 @@"posthog_user"."distinct_id","posthog_user"."is_email_verified","posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at","posthog_user"."requested_2fa_reset_at","posthog_user"."has_seen_product_intro_for","posthog_user"."strapi_id",@@ -5527,111 +5699,305 @@"posthog_user"."onboarding_delegation_accepted_at","posthog_user"."events_column_config","posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE ("posthog_user"."is_active"- AND "posthog_user"."id" = 99999)+ FROM "posthog_datawarehousetable"+ LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")+ WHERE ("posthog_datawarehousetable"."team_id" = 99999+ AND NOT ("posthog_datawarehousetable"."deleted"+ AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."access_method" = 'direct'+ AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.102'''- SELECT "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_hipaa",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organization"- WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid- LIMIT 21+ SELECT "posthog_datawarehousejoin"."created_by_id",+ "posthog_datawarehousejoin"."created_at",+ "posthog_datawarehousejoin"."deleted",+ "posthog_datawarehousejoin"."deleted_at",+ "posthog_datawarehousejoin"."id",+ "posthog_datawarehousejoin"."team_id",+ "posthog_datawarehousejoin"."source_table_name",+ "posthog_datawarehousejoin"."source_table_key",+ "posthog_datawarehousejoin"."joining_table_name",+ "posthog_datawarehousejoin"."joining_table_key",+ "posthog_datawarehousejoin"."field_name",+ "posthog_datawarehousejoin"."configuration"+ FROM "posthog_datawarehousejoin"+ WHERE ("posthog_datawarehousejoin"."team_id" = 99999+ AND NOT ("posthog_datawarehousejoin"."deleted"+ AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.103'''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."event_retention_months",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."llm_gateway_overspend_allowance_usd",- "posthog_team"."heatmaps_opt_in",+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.104+ '''+ SELECT "posthog_sessionrecording"."id",+ "posthog_sessionrecording"."session_id",+ "posthog_sessionrecording"."team_id",+ "posthog_sessionrecording"."created_at",+ "posthog_sessionrecording"."deleted",+ "posthog_sessionrecording"."object_storage_path",+ "posthog_sessionrecording"."full_recording_v2_path",+ "posthog_sessionrecording"."distinct_id",+ "posthog_sessionrecording"."duration",+ "posthog_sessionrecording"."active_seconds",+ "posthog_sessionrecording"."inactive_seconds",+ "posthog_sessionrecording"."start_time",+ "posthog_sessionrecording"."end_time",+ "posthog_sessionrecording"."click_count",+ "posthog_sessionrecording"."keypress_count",+ "posthog_sessionrecording"."mouse_activity_count",+ "posthog_sessionrecording"."console_log_count",+ "posthog_sessionrecording"."console_warn_count",+ "posthog_sessionrecording"."console_error_count",+ "posthog_sessionrecording"."start_url",+ "posthog_sessionrecording"."storage_version",+ "posthog_sessionrecording"."retention_period_days"+ FROM "posthog_sessionrecording"+ WHERE ("posthog_sessionrecording"."session_id" IN ('1',+ '2',+ '3',+ '4',+ '5',+ '6')+ AND "posthog_sessionrecording"."team_id" = 99999)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.105+ '''+ SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"+ FROM "posthog_sessionrecordingviewed"+ WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999+ AND "posthog_sessionrecordingviewed"."user_id" = 99999+ AND "posthog_sessionrecordingviewed"."session_id" IN ('6',+ '5',+ '4',+ '3',+ '2',+ '1'))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.106+ '''+ SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",+ "posthog_user"."email" AS "user__email"+ FROM "posthog_sessionrecordingviewed"+ INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")+ WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('6',+ '5',+ '4',+ '3',+ '2',+ '1')+ AND "posthog_sessionrecordingviewed"."team_id" = 99999+ AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.107+ '''+ SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",+ ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",+ "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"+ FROM "ee_single_session_summary"+ WHERE ("ee_single_session_summary"."session_id" IN ('6',+ '5',+ '4',+ '3',+ '2',+ '1')+ AND "ee_single_session_summary"."team_id" = 99999+ AND "ee_single_session_summary"."extra_summary_context" IS NULL)+ ORDER BY 1 ASC,+ "ee_single_session_summary"."created_at" DESC+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.108+ '''+ SELECT "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in"+ FROM "posthog_user"+ WHERE ("posthog_user"."is_active"+ AND "posthog_user"."id" = 99999)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.109+ '''+ SELECT "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."enforce_verified_domains",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."members_can_see_org_members",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organization"+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid+ LIMIT 21+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.11+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.110+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."uuid",+ "posthog_team"."organization_id",+ "posthog_team"."parent_team_id",+ "posthog_team"."project_id",+ "posthog_team"."api_token",+ "posthog_team"."app_urls",+ "posthog_team"."name",+ "posthog_team"."slack_incoming_webhook",+ "posthog_team"."created_at",+ "posthog_team"."updated_at",+ "posthog_team"."anonymize_ips",+ "posthog_team"."completed_snippet_onboarding",+ "posthog_team"."has_completed_onboarding_for",+ "posthog_team"."onboarding_tasks",+ "posthog_team"."ingested_event",+ "posthog_team"."ingested_production_event",+ "posthog_team"."ingested_production_event_last_checked_at",+ "posthog_team"."person_processing_opt_out",+ "posthog_team"."secret_api_token",+ "posthog_team"."secret_api_token_backup",+ "posthog_team"."session_recording_opt_in",+ "posthog_team"."session_recording_sample_rate",+ "posthog_team"."session_recording_minimum_duration_milliseconds",+ "posthog_team"."session_recording_linked_flag",+ "posthog_team"."session_recording_network_payload_capture_config",+ "posthog_team"."session_recording_masking_config",+ "posthog_team"."session_recording_url_trigger_config",+ "posthog_team"."session_recording_url_blocklist_config",+ "posthog_team"."session_recording_event_trigger_config",+ "posthog_team"."session_recording_trigger_match_type_config",+ "posthog_team"."session_recording_trigger_groups",+ "posthog_team"."session_replay_config",+ "posthog_team"."session_recording_retention_period",+ "posthog_team"."event_retention_months",+ "posthog_team"."conversations_enabled",+ "posthog_team"."conversations_settings",+ "posthog_team"."proactive_tasks_enabled",+ "posthog_team"."survey_config",+ "posthog_team"."surveys_opt_in",+ "posthog_team"."product_tours_opt_in",+ "posthog_team"."capture_console_log_opt_in",+ "posthog_team"."capture_performance_opt_in",+ "posthog_team"."capture_dead_clicks",+ "posthog_team"."autocapture_opt_out",+ "posthog_team"."autocapture_web_vitals_opt_in",+ "posthog_team"."autocapture_web_vitals_allowed_metrics",+ "posthog_team"."autocapture_exceptions_opt_in",+ "posthog_team"."autocapture_exceptions_errors_to_ignore",+ "posthog_team"."logs_settings",+ "posthog_team"."llm_gateway_enabled_at",+ "posthog_team"."llm_gateway_revoked_at",+ "posthog_team"."llm_gateway_overspend_allowance_usd",+ "posthog_team"."heatmaps_opt_in","posthog_team"."receive_org_level_activity_logs","posthog_team"."web_analytics_pre_aggregated_tables_enabled","posthog_team"."web_analytics_pre_aggregated_tables_version",@@ -5716,7 +6082,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.104+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.111'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -5769,7 +6135,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.105+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.112'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -5794,7 +6160,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.106+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.113'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -5845,7 +6211,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.107+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.114'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -5947,7 +6313,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.108+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.115'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -6041,7 +6407,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.109+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.116'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -6079,53 +6445,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.11- '''- SELECT "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE ("posthog_user"."is_active"- AND "posthog_user"."id" = 99999)- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.110+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.117'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -6198,7 +6518,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.111+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.118'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -6218,7 +6538,72 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.112+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.119+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.12+ '''+ SELECT "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in"+ FROM "posthog_user"+ WHERE ("posthog_user"."is_active"+ AND "posthog_user"."id" = 99999)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.120'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -6253,7 +6638,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.113+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.121'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -6268,7 +6653,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.114+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.122'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -6285,7 +6670,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.115+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.123'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -6304,7 +6689,7 @@"ee_single_session_summary"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.116+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.124'''SELECT "posthog_user"."id","posthog_user"."password",@@ -6350,7 +6735,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.117+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.125'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -6394,7 +6779,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.118+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.126'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -6534,7 +6919,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.119+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.127'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -6587,9 +6972,41 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.12+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.128'''- SELECT "posthog_organization"."id",+ SELECT "ee_accesscontrol"."id",+ "ee_accesscontrol"."team_id",+ "ee_accesscontrol"."access_level",+ "ee_accesscontrol"."resource",+ "ee_accesscontrol"."resource_id",+ "ee_accesscontrol"."organization_member_id",+ "ee_accesscontrol"."role_id",+ "ee_accesscontrol"."created_by_id",+ "ee_accesscontrol"."created_at",+ "ee_accesscontrol"."updated_at",+ "posthog_team"."organization_id" AS "_team_organization_id"+ FROM "ee_accesscontrol"+ INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")+ LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")+ WHERE (("ee_accesscontrol"."organization_member_id" IS NULL+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999)+ OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.129+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id","posthog_organization"."name","posthog_organization"."slug","posthog_organization"."logo_media_id",@@ -6626,46 +7043,14 @@"posthog_organization"."personalization","posthog_organization"."domain_whitelist","posthog_organization"."is_platform"- FROM "posthog_organization"- WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid- LIMIT 21- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.120- '''- SELECT "ee_accesscontrol"."id",- "ee_accesscontrol"."team_id",- "ee_accesscontrol"."access_level",- "ee_accesscontrol"."resource",- "ee_accesscontrol"."resource_id",- "ee_accesscontrol"."organization_member_id",- "ee_accesscontrol"."role_id",- "ee_accesscontrol"."created_by_id",- "ee_accesscontrol"."created_at",- "ee_accesscontrol"."updated_at",- "posthog_team"."organization_id" AS "_team_organization_id"- FROM "ee_accesscontrol"- INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")- LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")- WHERE (("ee_accesscontrol"."organization_member_id" IS NULL- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999)- OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999))+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.121+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.13'''- SELECT "posthog_organizationmembership"."id",- "posthog_organizationmembership"."organization_id",- "posthog_organizationmembership"."user_id",- "posthog_organizationmembership"."level",- "posthog_organizationmembership"."joined_at",- "posthog_organizationmembership"."updated_at",- "posthog_organizationmembership"."invited_by_id",- "posthog_organization"."id",+ SELECT "posthog_organization"."id","posthog_organization"."name","posthog_organization"."slug","posthog_organization"."logo_media_id",@@ -6702,12 +7087,12 @@"posthog_organization"."personalization","posthog_organization"."domain_whitelist","posthog_organization"."is_platform"- FROM "posthog_organizationmembership"- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE "posthog_organizationmembership"."user_id" = 99999+ FROM "posthog_organization"+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid+ LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.122+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.130'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -6809,7 +7194,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.123+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.131'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -6903,7 +7288,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.124+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.132'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -6941,7 +7326,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.125+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.133'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -7014,7 +7399,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.126+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.134'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -7034,7 +7419,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.127+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.135+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.136'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -7070,7 +7474,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.128+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.137'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -7086,7 +7490,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.129+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.138'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -7104,7 +7508,27 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.13+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.139+ '''+ SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",+ ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",+ "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"+ FROM "ee_single_session_summary"+ WHERE ("ee_single_session_summary"."session_id" IN ('8',+ '7',+ '6',+ '5',+ '4',+ '3',+ '2',+ '1')+ AND "ee_single_session_summary"."team_id" = 99999+ AND "ee_single_session_summary"."extra_summary_context" IS NULL)+ ORDER BY 1 ASC,+ "ee_single_session_summary"."created_at" DESC+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.14'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -7244,27 +7668,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.130- '''- SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",- ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",- "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"- FROM "ee_single_session_summary"- WHERE ("ee_single_session_summary"."session_id" IN ('8',- '7',- '6',- '5',- '4',- '3',- '2',- '1')- AND "ee_single_session_summary"."team_id" = 99999- AND "ee_single_session_summary"."extra_summary_context" IS NULL)- ORDER BY 1 ASC,- "ee_single_session_summary"."created_at" DESC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.131+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.140'''SELECT "posthog_user"."id","posthog_user"."password",@@ -7310,7 +7714,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.132+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.141'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -7354,7 +7758,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.133+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.142'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -7494,7 +7898,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.134+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.143'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -7547,7 +7951,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.135+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.144'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -7572,7 +7976,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.136+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.145'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -7623,7 +8027,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.137+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.146'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -7725,7 +8129,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.138+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.147'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -7819,7 +8223,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.139+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.148'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -7857,60 +8261,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.14- '''- SELECT "posthog_organizationmembership"."id",- "posthog_organizationmembership"."organization_id",- "posthog_organizationmembership"."user_id",- "posthog_organizationmembership"."level",- "posthog_organizationmembership"."joined_at",- "posthog_organizationmembership"."updated_at",- "posthog_organizationmembership"."invited_by_id",- "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_hipaa",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organizationmembership"- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999)- LIMIT 21- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.140+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.149'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -7983,7 +8334,60 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.141+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.15+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."enforce_verified_domains",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."members_can_see_org_members",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.150'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -8003,7 +8407,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.142+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.151+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.152'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -8040,7 +8463,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.143+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.153'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -8057,7 +8480,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.144+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.154'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -8076,7 +8499,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.145+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.155'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -8097,7 +8520,7 @@"ee_single_session_summary"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.146+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.156'''SELECT "posthog_user"."id","posthog_user"."password",@@ -8143,7 +8566,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.147+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.157'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -8187,7 +8610,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.148+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.158'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -8327,7 +8750,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.149+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.159'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -8380,7 +8803,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.15+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.16'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -8405,7 +8828,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.150+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.160'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -8430,7 +8853,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.151+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.161'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -8481,7 +8904,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.152+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.162'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -8583,7 +9006,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.153+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.163'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -8677,7 +9100,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.154+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.164'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -8715,7 +9138,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.155+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.165'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -8788,7 +9211,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.156+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.166'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -8808,7 +9231,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.157+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.167+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.168'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -8846,7 +9288,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.158+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.169'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -8864,27 +9306,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.159- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('9',- '8',- '7',- '6',- '5',- '4',- '3',- '2',- '10',- '1')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.16+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.17'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -8935,7 +9357,27 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.160+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.170+ '''+ SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",+ "posthog_user"."email" AS "user__email"+ FROM "posthog_sessionrecordingviewed"+ INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")+ WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('9',+ '8',+ '7',+ '6',+ '5',+ '4',+ '3',+ '2',+ '10',+ '1')+ AND "posthog_sessionrecordingviewed"."team_id" = 99999+ AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.171'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -8957,7 +9399,7 @@"ee_single_session_summary"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.17+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.18'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -9059,7 +9501,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.18+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.19'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -9153,44 +9595,6 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.19- '''- SELECT "posthog_externaldatasource"."created_by_id",- "posthog_externaldatasource"."created_at",- "posthog_externaldatasource"."updated_at",- "posthog_externaldatasource"."deleted",- "posthog_externaldatasource"."deleted_at",- "posthog_externaldatasource"."id",- "posthog_externaldatasource"."source_id",- "posthog_externaldatasource"."connection_id",- "posthog_externaldatasource"."destination_id",- "posthog_externaldatasource"."team_id",- "posthog_externaldatasource"."sync_frequency",- "posthog_externaldatasource"."status",- "posthog_externaldatasource"."source_type",- "posthog_externaldatasource"."api_version",- "posthog_externaldatasource"."job_inputs",- "posthog_externaldatasource"."connection_metadata",- "posthog_externaldatasource"."are_tables_created",- "posthog_externaldatasource"."prefix",- "posthog_externaldatasource"."description",- "posthog_externaldatasource"."created_via",- "posthog_externaldatasource"."access_method",- "posthog_externaldatasource"."direct_query_enabled",- "posthog_externaldatasource"."auto_sync_new_schemas",- "posthog_externaldatasource"."auto_sync_schema_patterns",- "posthog_externaldatasource"."revenue_analytics_enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",- "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"- FROM "posthog_externaldatasource"- LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")- WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')- AND "posthog_externaldatasource"."team_id" = 99999- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL))- '''-# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.2'''SELECT "posthog_team"."id",@@ -9333,19 +9737,57 @@# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.20'''- SELECT "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",+ SELECT "posthog_externaldatasource"."created_by_id",+ "posthog_externaldatasource"."created_at",+ "posthog_externaldatasource"."updated_at",+ "posthog_externaldatasource"."deleted",+ "posthog_externaldatasource"."deleted_at",+ "posthog_externaldatasource"."id",+ "posthog_externaldatasource"."source_id",+ "posthog_externaldatasource"."connection_id",+ "posthog_externaldatasource"."destination_id",+ "posthog_externaldatasource"."team_id",+ "posthog_externaldatasource"."sync_frequency",+ "posthog_externaldatasource"."status",+ "posthog_externaldatasource"."source_type",+ "posthog_externaldatasource"."api_version",+ "posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."connection_metadata",+ "posthog_externaldatasource"."are_tables_created",+ "posthog_externaldatasource"."prefix",+ "posthog_externaldatasource"."description",+ "posthog_externaldatasource"."created_via",+ "posthog_externaldatasource"."access_method",+ "posthog_externaldatasource"."direct_query_enabled",+ "posthog_externaldatasource"."auto_sync_new_schemas",+ "posthog_externaldatasource"."auto_sync_schema_patterns",+ "posthog_externaldatasource"."revenue_analytics_enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",+ "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"+ FROM "posthog_externaldatasource"+ LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")+ WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')+ AND "posthog_externaldatasource"."team_id" = 99999+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.21+ '''+ SELECT "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id","posthog_datawarehousetable"."columns","posthog_datawarehousetable"."column_order","posthog_datawarehousetable"."options",@@ -9404,7 +9846,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.21+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.22'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -9424,7 +9866,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.22+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.23+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.24'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -9453,7 +9914,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.23+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.25'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -9462,7 +9923,7 @@AND "posthog_sessionrecordingviewed"."session_id" IN ('1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.24+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.26'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -9473,7 +9934,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.25+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.27'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -9486,7 +9947,7 @@"ee_single_session_summary"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.26+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.28'''SELECT "posthog_user"."id","posthog_user"."password",@@ -9532,7 +9993,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.27+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.29'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -9576,7 +10037,60 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.28+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.3+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."enforce_verified_domains",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."members_can_see_org_members",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.30'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -9716,60 +10230,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.29- '''- SELECT "posthog_organizationmembership"."id",- "posthog_organizationmembership"."organization_id",- "posthog_organizationmembership"."user_id",- "posthog_organizationmembership"."level",- "posthog_organizationmembership"."joined_at",- "posthog_organizationmembership"."updated_at",- "posthog_organizationmembership"."invited_by_id",- "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_hipaa",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organizationmembership"- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999)- LIMIT 21- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.3+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.31'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -9822,7 +10283,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.30+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.32'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -9847,7 +10308,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.31+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.33'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -9898,7 +10359,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.32+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.34'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -10000,7 +10461,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.33+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.35'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -10094,7 +10555,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.34+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.36'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -10132,7 +10593,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.35+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.37'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -10205,7 +10666,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.36+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.38'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -10225,7 +10686,51 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.37+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.39+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.4+ '''+ SELECT "ee_accesscontrol"."id",+ "ee_accesscontrol"."team_id",+ "ee_accesscontrol"."access_level",+ "ee_accesscontrol"."resource",+ "ee_accesscontrol"."resource_id",+ "ee_accesscontrol"."organization_member_id",+ "ee_accesscontrol"."role_id",+ "ee_accesscontrol"."created_by_id",+ "ee_accesscontrol"."created_at",+ "ee_accesscontrol"."updated_at",+ "posthog_team"."organization_id" AS "_team_organization_id"+ FROM "ee_accesscontrol"+ INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")+ LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")+ WHERE (("ee_accesscontrol"."organization_member_id" IS NULL+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999)+ OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.40'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -10255,7 +10760,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.38+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.41'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -10265,7 +10770,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.39+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.42'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -10277,32 +10782,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.4- '''- SELECT "ee_accesscontrol"."id",- "ee_accesscontrol"."team_id",- "ee_accesscontrol"."access_level",- "ee_accesscontrol"."resource",- "ee_accesscontrol"."resource_id",- "ee_accesscontrol"."organization_member_id",- "ee_accesscontrol"."role_id",- "ee_accesscontrol"."created_by_id",- "ee_accesscontrol"."created_at",- "ee_accesscontrol"."updated_at",- "posthog_team"."organization_id" AS "_team_organization_id"- FROM "ee_accesscontrol"- INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")- LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")- WHERE (("ee_accesscontrol"."organization_member_id" IS NULL- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999)- OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.40+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.43'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -10316,7 +10796,7 @@"ee_single_session_summary"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.41+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.44'''SELECT "posthog_user"."id","posthog_user"."password",@@ -10362,7 +10842,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.42+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.45'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -10406,7 +10886,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.43+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.46'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -10546,7 +11026,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.44+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.47'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -10599,7 +11079,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.45+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.48'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -10624,7 +11104,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.46+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.49'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -10675,7 +11155,58 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.47+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.5+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."enforce_verified_domains",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."members_can_see_org_members",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE "posthog_organizationmembership"."user_id" = 99999+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.50'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -10777,7 +11308,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.48+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.51'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -10871,7 +11402,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.49+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.52'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -10909,58 +11440,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.5- '''- SELECT "posthog_organizationmembership"."id",- "posthog_organizationmembership"."organization_id",- "posthog_organizationmembership"."user_id",- "posthog_organizationmembership"."level",- "posthog_organizationmembership"."joined_at",- "posthog_organizationmembership"."updated_at",- "posthog_organizationmembership"."invited_by_id",- "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_hipaa",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organizationmembership"- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE "posthog_organizationmembership"."user_id" = 99999- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.50+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.53'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -11033,7 +11513,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.51+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.54'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -11053,7 +11533,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.52+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.55+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.56'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -11084,7 +11583,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.53+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.57'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -11095,7 +11594,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.54+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.58'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -11108,7 +11607,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.55+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.59'''SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",@@ -11123,7 +11622,109 @@"ee_single_session_summary"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.56+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.6+ '''+ SELECT "posthog_datawarehousesavedquery"."created_by_id",+ "posthog_datawarehousesavedquery"."created_at",+ "posthog_datawarehousesavedquery"."updated_at",+ "posthog_datawarehousesavedquery"."deleted",+ "posthog_datawarehousesavedquery"."deleted_at",+ "posthog_datawarehousesavedquery"."id",+ "posthog_datawarehousesavedquery"."name",+ "posthog_datawarehousesavedquery"."team_id",+ "posthog_datawarehousesavedquery"."latest_error",+ "posthog_datawarehousesavedquery"."columns",+ "posthog_datawarehousesavedquery"."column_order",+ "posthog_datawarehousesavedquery"."external_tables",+ "posthog_datawarehousesavedquery"."query",+ "posthog_datawarehousesavedquery"."status",+ "posthog_datawarehousesavedquery"."last_run_at",+ "posthog_datawarehousesavedquery"."sync_frequency_interval",+ "posthog_datawarehousesavedquery"."table_id",+ "posthog_datawarehousesavedquery"."is_materialized",+ "posthog_datawarehousesavedquery"."deleted_name",+ "posthog_datawarehousesavedquery"."managed_viewset_id",+ "posthog_datawarehousesavedquery"."folder_id",+ "posthog_datawarehousesavedquery"."origin",+ "posthog_datawarehousesavedquery"."is_test",+ "posthog_datawarehousesavedquery"."expires_at",+ "posthog_datawarehousesavedquery"."semantic_enrichment_hash",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in",+ "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."column_order",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib",+ "posthog_datawarehousemanagedviewset"."created_by_id",+ "posthog_datawarehousemanagedviewset"."created_at",+ "posthog_datawarehousemanagedviewset"."updated_at",+ "posthog_datawarehousemanagedviewset"."id",+ "posthog_datawarehousemanagedviewset"."team_id",+ "posthog_datawarehousemanagedviewset"."kind"+ FROM "posthog_datawarehousesavedquery"+ LEFT OUTER JOIN "posthog_datawarehousemanagedviewset" ON ("posthog_datawarehousesavedquery"."managed_viewset_id" = "posthog_datawarehousemanagedviewset"."id")+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")+ WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999+ AND NOT ("posthog_datawarehousesavedquery"."deleted"+ AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL)+ AND "posthog_datawarehousesavedquery"."managed_viewset_id" IS NULL)+ ORDER BY "posthog_datawarehousesavedquery"."name" ASC+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.60'''SELECT "posthog_user"."id","posthog_user"."password",@@ -11169,7 +11770,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.57+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.61'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -11213,7 +11814,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.58+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.62'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -11353,7 +11954,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.59+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.63'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -11406,109 +12007,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.6- '''- SELECT "posthog_datawarehousesavedquery"."created_by_id",- "posthog_datawarehousesavedquery"."created_at",- "posthog_datawarehousesavedquery"."updated_at",- "posthog_datawarehousesavedquery"."deleted",- "posthog_datawarehousesavedquery"."deleted_at",- "posthog_datawarehousesavedquery"."id",- "posthog_datawarehousesavedquery"."name",- "posthog_datawarehousesavedquery"."team_id",- "posthog_datawarehousesavedquery"."latest_error",- "posthog_datawarehousesavedquery"."columns",- "posthog_datawarehousesavedquery"."column_order",- "posthog_datawarehousesavedquery"."external_tables",- "posthog_datawarehousesavedquery"."query",- "posthog_datawarehousesavedquery"."status",- "posthog_datawarehousesavedquery"."last_run_at",- "posthog_datawarehousesavedquery"."sync_frequency_interval",- "posthog_datawarehousesavedquery"."table_id",- "posthog_datawarehousesavedquery"."is_materialized",- "posthog_datawarehousesavedquery"."deleted_name",- "posthog_datawarehousesavedquery"."managed_viewset_id",- "posthog_datawarehousesavedquery"."folder_id",- "posthog_datawarehousesavedquery"."origin",- "posthog_datawarehousesavedquery"."is_test",- "posthog_datawarehousesavedquery"."expires_at",- "posthog_datawarehousesavedquery"."semantic_enrichment_hash",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in",- "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib",- "posthog_datawarehousemanagedviewset"."created_by_id",- "posthog_datawarehousemanagedviewset"."created_at",- "posthog_datawarehousemanagedviewset"."updated_at",- "posthog_datawarehousemanagedviewset"."id",- "posthog_datawarehousemanagedviewset"."team_id",- "posthog_datawarehousemanagedviewset"."kind"- FROM "posthog_datawarehousesavedquery"- LEFT OUTER JOIN "posthog_datawarehousemanagedviewset" ON ("posthog_datawarehousesavedquery"."managed_viewset_id" = "posthog_datawarehousemanagedviewset"."id")- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")- LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")- WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999- AND NOT ("posthog_datawarehousesavedquery"."deleted"- AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL)- AND "posthog_datawarehousesavedquery"."managed_viewset_id" IS NULL)- ORDER BY "posthog_datawarehousesavedquery"."name" ASC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.60+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.64'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -11533,7 +12032,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.61+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.65'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -11584,7 +12083,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.62+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.66'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -11686,7 +12185,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.63+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.67'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -11780,7 +12279,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.64+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.68'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -11818,7 +12317,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.65+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.69'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -11891,7 +12390,101 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.66+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.7+ '''+ SELECT "posthog_datawarehousesavedquery"."created_by_id",+ "posthog_datawarehousesavedquery"."created_at",+ "posthog_datawarehousesavedquery"."updated_at",+ "posthog_datawarehousesavedquery"."deleted",+ "posthog_datawarehousesavedquery"."deleted_at",+ "posthog_datawarehousesavedquery"."id",+ "posthog_datawarehousesavedquery"."name",+ "posthog_datawarehousesavedquery"."team_id",+ "posthog_datawarehousesavedquery"."latest_error",+ "posthog_datawarehousesavedquery"."columns",+ "posthog_datawarehousesavedquery"."column_order",+ "posthog_datawarehousesavedquery"."external_tables",+ "posthog_datawarehousesavedquery"."query",+ "posthog_datawarehousesavedquery"."status",+ "posthog_datawarehousesavedquery"."last_run_at",+ "posthog_datawarehousesavedquery"."sync_frequency_interval",+ "posthog_datawarehousesavedquery"."table_id",+ "posthog_datawarehousesavedquery"."is_materialized",+ "posthog_datawarehousesavedquery"."deleted_name",+ "posthog_datawarehousesavedquery"."managed_viewset_id",+ "posthog_datawarehousesavedquery"."folder_id",+ "posthog_datawarehousesavedquery"."origin",+ "posthog_datawarehousesavedquery"."is_test",+ "posthog_datawarehousesavedquery"."expires_at",+ "posthog_datawarehousesavedquery"."semantic_enrichment_hash",+ "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in",+ "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."column_order",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib"+ FROM "posthog_datawarehousesavedquery"+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")+ LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")+ WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999+ AND "posthog_datawarehousesavedquery"."origin" = 'endpoint'+ AND NOT ("posthog_datawarehousesavedquery"."deleted"+ AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.70'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -11911,7 +12504,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.67+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.71+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.72'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -11943,7 +12555,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.68+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.73'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -11955,7 +12567,7 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.69+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.74'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id","posthog_user"."email" AS "user__email"@@ -11969,119 +12581,25 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.7+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.75'''- SELECT "posthog_datawarehousesavedquery"."created_by_id",- "posthog_datawarehousesavedquery"."created_at",- "posthog_datawarehousesavedquery"."updated_at",- "posthog_datawarehousesavedquery"."deleted",- "posthog_datawarehousesavedquery"."deleted_at",- "posthog_datawarehousesavedquery"."id",- "posthog_datawarehousesavedquery"."name",- "posthog_datawarehousesavedquery"."team_id",- "posthog_datawarehousesavedquery"."latest_error",- "posthog_datawarehousesavedquery"."columns",- "posthog_datawarehousesavedquery"."column_order",- "posthog_datawarehousesavedquery"."external_tables",- "posthog_datawarehousesavedquery"."query",- "posthog_datawarehousesavedquery"."status",- "posthog_datawarehousesavedquery"."last_run_at",- "posthog_datawarehousesavedquery"."sync_frequency_interval",- "posthog_datawarehousesavedquery"."table_id",- "posthog_datawarehousesavedquery"."is_materialized",- "posthog_datawarehousesavedquery"."deleted_name",- "posthog_datawarehousesavedquery"."managed_viewset_id",- "posthog_datawarehousesavedquery"."folder_id",- "posthog_datawarehousesavedquery"."origin",- "posthog_datawarehousesavedquery"."is_test",- "posthog_datawarehousesavedquery"."expires_at",- "posthog_datawarehousesavedquery"."semantic_enrichment_hash",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in",- "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib"- FROM "posthog_datawarehousesavedquery"- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")- LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")- WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999- AND "posthog_datawarehousesavedquery"."origin" = 'endpoint'- AND NOT ("posthog_datawarehousesavedquery"."deleted"- AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.70- '''- SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",- ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",- "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"- FROM "ee_single_session_summary"- WHERE ("ee_single_session_summary"."session_id" IN ('4',- '3',- '2',- '1')- AND "ee_single_session_summary"."team_id" = 99999- AND "ee_single_session_summary"."extra_summary_context" IS NULL)- ORDER BY 1 ASC,- "ee_single_session_summary"."created_at" DESC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.71- '''- SELECT "posthog_user"."id",+ SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",+ ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",+ "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"+ FROM "ee_single_session_summary"+ WHERE ("ee_single_session_summary"."session_id" IN ('4',+ '3',+ '2',+ '1')+ AND "ee_single_session_summary"."team_id" = 99999+ AND "ee_single_session_summary"."extra_summary_context" IS NULL)+ ORDER BY 1 ASC,+ "ee_single_session_summary"."created_at" DESC+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.76+ '''+ SELECT "posthog_user"."id","posthog_user"."password","posthog_user"."last_login","posthog_user"."first_name",@@ -12125,7 +12643,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.72+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.77'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -12169,7 +12687,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.73+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.78'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -12309,7 +12827,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.74+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.79'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -12362,7 +12880,45 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.75+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.8+ '''+ SELECT "posthog_externaldatasource"."created_by_id",+ "posthog_externaldatasource"."created_at",+ "posthog_externaldatasource"."updated_at",+ "posthog_externaldatasource"."deleted",+ "posthog_externaldatasource"."deleted_at",+ "posthog_externaldatasource"."id",+ "posthog_externaldatasource"."source_id",+ "posthog_externaldatasource"."connection_id",+ "posthog_externaldatasource"."destination_id",+ "posthog_externaldatasource"."team_id",+ "posthog_externaldatasource"."sync_frequency",+ "posthog_externaldatasource"."status",+ "posthog_externaldatasource"."source_type",+ "posthog_externaldatasource"."api_version",+ "posthog_externaldatasource"."job_inputs",+ "posthog_externaldatasource"."connection_metadata",+ "posthog_externaldatasource"."are_tables_created",+ "posthog_externaldatasource"."prefix",+ "posthog_externaldatasource"."description",+ "posthog_externaldatasource"."created_via",+ "posthog_externaldatasource"."access_method",+ "posthog_externaldatasource"."direct_query_enabled",+ "posthog_externaldatasource"."auto_sync_new_schemas",+ "posthog_externaldatasource"."auto_sync_schema_patterns",+ "posthog_externaldatasource"."revenue_analytics_enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",+ "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",+ "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"+ FROM "posthog_externaldatasource"+ LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")+ WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')+ AND "posthog_externaldatasource"."team_id" = 99999+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.80'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -12387,7 +12943,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.76+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.81'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -12438,7 +12994,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.77+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.82'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -12540,7 +13096,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.78+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.83'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -12634,45 +13190,7 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.79- '''- SELECT "posthog_externaldatasource"."created_by_id",- "posthog_externaldatasource"."created_at",- "posthog_externaldatasource"."updated_at",- "posthog_externaldatasource"."deleted",- "posthog_externaldatasource"."deleted_at",- "posthog_externaldatasource"."id",- "posthog_externaldatasource"."source_id",- "posthog_externaldatasource"."connection_id",- "posthog_externaldatasource"."destination_id",- "posthog_externaldatasource"."team_id",- "posthog_externaldatasource"."sync_frequency",- "posthog_externaldatasource"."status",- "posthog_externaldatasource"."source_type",- "posthog_externaldatasource"."api_version",- "posthog_externaldatasource"."job_inputs",- "posthog_externaldatasource"."connection_metadata",- "posthog_externaldatasource"."are_tables_created",- "posthog_externaldatasource"."prefix",- "posthog_externaldatasource"."description",- "posthog_externaldatasource"."created_via",- "posthog_externaldatasource"."access_method",- "posthog_externaldatasource"."direct_query_enabled",- "posthog_externaldatasource"."auto_sync_new_schemas",- "posthog_externaldatasource"."auto_sync_schema_patterns",- "posthog_externaldatasource"."revenue_analytics_enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",- "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"- FROM "posthog_externaldatasource"- LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")- WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')- AND "posthog_externaldatasource"."team_id" = 99999- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.8+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.84'''SELECT "posthog_externaldatasource"."created_by_id","posthog_externaldatasource"."created_at",@@ -12710,7 +13228,7 @@AND "posthog_externaldatasource"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.80+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.85'''SELECT "posthog_datawarehousetable"."created_by_id","posthog_datawarehousetable"."created_at",@@ -12783,7 +13301,7 @@ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.81+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.86'''SELECT "posthog_datawarehousejoin"."created_by_id","posthog_datawarehousejoin"."created_at",@@ -12803,7 +13321,26 @@AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.82+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.87+ '''+ SELECT "data_tools_datawarehouseexpression"."deleted",+ "data_tools_datawarehouseexpression"."deleted_at",+ "data_tools_datawarehouseexpression"."id",+ "data_tools_datawarehouseexpression"."team_id",+ "data_tools_datawarehouseexpression"."created_at",+ "data_tools_datawarehouseexpression"."created_by_id",+ "data_tools_datawarehouseexpression"."table_name",+ "data_tools_datawarehouseexpression"."field_name",+ "data_tools_datawarehouseexpression"."expression",+ "data_tools_datawarehouseexpression"."connection_id"+ FROM "data_tools_datawarehouseexpression"+ WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999+ AND NOT ("data_tools_datawarehouseexpression"."deleted"+ AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)+ AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.88'''SELECT "posthog_sessionrecording"."id","posthog_sessionrecording"."session_id",@@ -12836,7 +13373,7 @@AND "posthog_sessionrecording"."team_id" = 99999)'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.83+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.89'''SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"FROM "posthog_sessionrecordingviewed"@@ -12849,41 +13386,27 @@'1'))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.84- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('5',- '4',- '3',- '2',- '1')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.85- '''- SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",- ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",- "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"- FROM "ee_single_session_summary"- WHERE ("ee_single_session_summary"."session_id" IN ('5',- '4',- '3',- '2',- '1')- AND "ee_single_session_summary"."team_id" = 99999- AND "ee_single_session_summary"."extra_summary_context" IS NULL)- ORDER BY 1 ASC,- "ee_single_session_summary"."created_at" DESC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.86+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.9'''- SELECT "posthog_user"."id",+ SELECT "posthog_datawarehousetable"."created_by_id",+ "posthog_datawarehousetable"."created_at",+ "posthog_datawarehousetable"."updated_at",+ "posthog_datawarehousetable"."deleted",+ "posthog_datawarehousetable"."deleted_at",+ "posthog_datawarehousetable"."id",+ "posthog_datawarehousetable"."name",+ "posthog_datawarehousetable"."format",+ "posthog_datawarehousetable"."team_id",+ "posthog_datawarehousetable"."url_pattern",+ "posthog_datawarehousetable"."queryable_folder",+ "posthog_datawarehousetable"."credential_id",+ "posthog_datawarehousetable"."external_data_source_id",+ "posthog_datawarehousetable"."columns",+ "posthog_datawarehousetable"."column_order",+ "posthog_datawarehousetable"."options",+ "posthog_datawarehousetable"."row_count",+ "posthog_datawarehousetable"."size_in_s3_mib",+ "posthog_user"."id","posthog_user"."password","posthog_user"."last_login","posthog_user"."first_name",@@ -12898,6 +13421,7 @@"posthog_user"."distinct_id","posthog_user"."is_email_verified","posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_password_reset_at","posthog_user"."requested_2fa_reset_at","posthog_user"."has_seen_product_intro_for","posthog_user"."strapi_id",@@ -12922,12 +13446,98 @@"posthog_user"."onboarding_delegation_accepted_at","posthog_user"."events_column_config","posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE ("posthog_user"."is_active"- AND "posthog_user"."id" = 99999)+ FROM "posthog_datawarehousetable"+ LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")+ LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")+ WHERE ("posthog_datawarehousetable"."team_id" = 99999+ AND NOT ("posthog_datawarehousetable"."deleted"+ AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."access_method" = 'direct'+ AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.87+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.90+ '''+ SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",+ "posthog_user"."email" AS "user__email"+ FROM "posthog_sessionrecordingviewed"+ INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")+ WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('5',+ '4',+ '3',+ '2',+ '1')+ AND "posthog_sessionrecordingviewed"."team_id" = 99999+ AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.91+ '''+ SELECT DISTINCT ON ("ee_single_session_summary"."session_id") "ee_single_session_summary"."session_id" AS "session_id",+ ("ee_single_session_summary"."summary" -> 'session_outcome') AS "summary__session_outcome",+ "ee_single_session_summary"."extra_summary_context" AS "extra_summary_context"+ FROM "ee_single_session_summary"+ WHERE ("ee_single_session_summary"."session_id" IN ('5',+ '4',+ '3',+ '2',+ '1')+ AND "ee_single_session_summary"."team_id" = 99999+ AND "ee_single_session_summary"."extra_summary_context" IS NULL)+ ORDER BY 1 ASC,+ "ee_single_session_summary"."created_at" DESC+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.92+ '''+ SELECT "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in"+ FROM "posthog_user"+ WHERE ("posthog_user"."is_active"+ AND "posthog_user"."id" = 99999)+ '''+# ---+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.93'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -12971,7 +13581,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.88+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.94'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -13111,7 +13721,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.89+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.95'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -13164,80 +13774,7 @@LIMIT 21'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.9- '''- SELECT "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_datawarehousetable"- LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")- WHERE ("posthog_datawarehousetable"."team_id" = 99999- AND NOT ("posthog_datawarehousetable"."deleted"- AND "posthog_datawarehousetable"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."access_method" = 'direct'- AND "posthog_externaldatasource"."access_method" IS NOT NULL))- ORDER BY "posthog_datawarehousetable"."created_at" DESC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.90+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.96'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -13262,7 +13799,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.91+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.97'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -13313,7 +13850,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.92+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.98'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -13415,7 +13952,7 @@ORDER BY "posthog_datawarehousesavedquery"."name" ASC'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.93+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.99'''SELECT "posthog_datawarehousesavedquery"."created_by_id","posthog_datawarehousesavedquery"."created_at",@@ -13509,198 +14046,3 @@AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.94- '''- SELECT "posthog_externaldatasource"."created_by_id",- "posthog_externaldatasource"."created_at",- "posthog_externaldatasource"."updated_at",- "posthog_externaldatasource"."deleted",- "posthog_externaldatasource"."deleted_at",- "posthog_externaldatasource"."id",- "posthog_externaldatasource"."source_id",- "posthog_externaldatasource"."connection_id",- "posthog_externaldatasource"."destination_id",- "posthog_externaldatasource"."team_id",- "posthog_externaldatasource"."sync_frequency",- "posthog_externaldatasource"."status",- "posthog_externaldatasource"."source_type",- "posthog_externaldatasource"."api_version",- "posthog_externaldatasource"."job_inputs",- "posthog_externaldatasource"."connection_metadata",- "posthog_externaldatasource"."are_tables_created",- "posthog_externaldatasource"."prefix",- "posthog_externaldatasource"."description",- "posthog_externaldatasource"."created_via",- "posthog_externaldatasource"."access_method",- "posthog_externaldatasource"."direct_query_enabled",- "posthog_externaldatasource"."auto_sync_new_schemas",- "posthog_externaldatasource"."auto_sync_schema_patterns",- "posthog_externaldatasource"."revenue_analytics_enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",- "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"- FROM "posthog_externaldatasource"- LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")- WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')- AND "posthog_externaldatasource"."team_id" = 99999- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.95- '''- SELECT "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_datawarehousetable"- LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")- WHERE ("posthog_datawarehousetable"."team_id" = 99999- AND NOT ("posthog_datawarehousetable"."deleted"- AND "posthog_datawarehousetable"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."access_method" = 'direct'- AND "posthog_externaldatasource"."access_method" IS NOT NULL))- ORDER BY "posthog_datawarehousetable"."created_at" DESC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.96- '''- SELECT "posthog_datawarehousejoin"."created_by_id",- "posthog_datawarehousejoin"."created_at",- "posthog_datawarehousejoin"."deleted",- "posthog_datawarehousejoin"."deleted_at",- "posthog_datawarehousejoin"."id",- "posthog_datawarehousejoin"."team_id",- "posthog_datawarehousejoin"."source_table_name",- "posthog_datawarehousejoin"."source_table_key",- "posthog_datawarehousejoin"."joining_table_name",- "posthog_datawarehousejoin"."joining_table_key",- "posthog_datawarehousejoin"."field_name",- "posthog_datawarehousejoin"."configuration"- FROM "posthog_datawarehousejoin"- WHERE ("posthog_datawarehousejoin"."team_id" = 99999- AND NOT ("posthog_datawarehousejoin"."deleted"- AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.97- '''- SELECT "posthog_sessionrecording"."id",- "posthog_sessionrecording"."session_id",- "posthog_sessionrecording"."team_id",- "posthog_sessionrecording"."created_at",- "posthog_sessionrecording"."deleted",- "posthog_sessionrecording"."object_storage_path",- "posthog_sessionrecording"."full_recording_v2_path",- "posthog_sessionrecording"."distinct_id",- "posthog_sessionrecording"."duration",- "posthog_sessionrecording"."active_seconds",- "posthog_sessionrecording"."inactive_seconds",- "posthog_sessionrecording"."start_time",- "posthog_sessionrecording"."end_time",- "posthog_sessionrecording"."click_count",- "posthog_sessionrecording"."keypress_count",- "posthog_sessionrecording"."mouse_activity_count",- "posthog_sessionrecording"."console_log_count",- "posthog_sessionrecording"."console_warn_count",- "posthog_sessionrecording"."console_error_count",- "posthog_sessionrecording"."start_url",- "posthog_sessionrecording"."storage_version",- "posthog_sessionrecording"."retention_period_days"- FROM "posthog_sessionrecording"- WHERE ("posthog_sessionrecording"."session_id" IN ('1',- '2',- '3',- '4',- '5',- '6')- AND "posthog_sessionrecording"."team_id" = 99999)- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.98- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"- FROM "posthog_sessionrecordingviewed"- WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999- AND "posthog_sessionrecordingviewed"."user_id" = 99999- AND "posthog_sessionrecordingviewed"."session_id" IN ('6',- '5',- '4',- '3',- '2',- '1'))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.99- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('6',- '5',- '4',- '3',- '2',- '1')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---diff --git a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.pyindex a94140357d90..6cca6bc78869 100644--- a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py+++ b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py@@ -399,9 +399,6 @@ def _patched_terminalize_collaborators():patch("products.warehouse_sources.backend.facade.pipelines.BatchQueue") as batch_queue,patch("products.warehouse_sources.backend.facade.pipelines.mark_job_failed_if_not_terminal") as mark_failed,patch("products.warehouse_sources.backend.facade.pipelines.release_v3_pipeline_lock") as release_lock,- # The real close_old_connections trips pytest-django's DB blocker when an- # earlier test on the same xdist worker left an initialized connection.- patch("django.db.close_old_connections"),):batch_queue.fail_batches_for_job_sync.return_value = 2yield batch_queue, mark_failed, release_lockdiff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 73996450869d..7f436459fc54 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -30,6 +30,7 @@ model_activity:products.business_knowledge.backend.signals.handle_knowledge_sourmodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_widget_changemodel_activity:products.data_catalog.backend.activity_logging.handle_metric_activity+model_activity:products.data_tools.backend.activity_logging.handle_expression_activitymodel_activity:products.experiments.backend.activity_logging.handle_experiment_changemodel_activity:products.exports.backend.models.subscription.log_subscription_activitymodel_activity:products.feature_flags.backend.activity_logging.handle_feature_flag_changediff --git a/products/data_tools/backend/activity_logging.py b/products/data_tools/backend/activity_logging.pynew file mode 100644index 000000000000..3fd24580c6fd--- /dev/null+++ b/products/data_tools/backend/activity_logging.py@@ -0,0 +1,48 @@+"""Activity-log receiver for warehouse expressions.++``ModelActivityMixin`` emits ``model_activity_signal`` on every expression save; this persists the+audit trail (create, edit, soft delete, restore). Registered from ``apps.ready()``.+"""++from typing import Any, Optional, cast++from posthog.models import User+from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from .models.expression import DataWarehouseExpression+++@mutable_receiver(model_activity_signal, sender=DataWarehouseExpression)+def handle_expression_activity(+ sender: type,+ scope: str,+ before_update: Optional[DataWarehouseExpression],+ after_update: Optional[DataWarehouseExpression],+ activity: str,+ user: Optional[User],+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ if instance is None:+ return++ changes = changes_between(cast(AuditableScope, scope), previous=before_update, current=after_update)++ # Soft delete and restore go through save(), so the mixin reports them as "updated";+ # remap so the audit trail reads as the action the user actually took.+ deleted_change = next((change for change in changes if change.field == "deleted"), None)+ if deleted_change:+ activity = "deleted" if deleted_change.after else "restored"++ log_activity(+ organization_id=None,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(instance.id),+ scope=scope,+ activity=activity,+ detail=Detail(name=f"{instance.table_name}.{instance.field_name}", changes=changes),+ )diff --git a/products/data_tools/backend/apps.py b/products/data_tools/backend/apps.pyindex 1d0ead06eb98..c802161fb30b 100644--- a/products/data_tools/backend/apps.py+++ b/products/data_tools/backend/apps.py@@ -6,3 +6,8 @@ from django.apps import AppConfigclass DataToolsConfig(AppConfig):name = "products.data_tools.backend"label = "data_tools"++ def ready(self) -> None:+ # Deferred to app-ready time so importing the signal receiver (which imports+ # models) doesn't run during django.setup().+ from . import activity_logging # noqa: F401, PLC0415diff --git a/products/data_tools/backend/facade/models.py b/products/data_tools/backend/facade/models.pyindex 1bc1515f2e81..5c32ed204d19 100644--- a/products/data_tools/backend/facade/models.py+++ b/products/data_tools/backend/facade/models.py@@ -6,7 +6,8 @@ folder, join, and query-tab-state surfaces). Light — Django models loaded at s"""from products.data_tools.backend.models.datawarehouse_saved_query_folder import DataWarehouseSavedQueryFolder+from products.data_tools.backend.models.expression import DataWarehouseExpressionfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.data_tools.backend.models.query_tab_state import QueryTabState-__all__ = ["DataWarehouseJoin", "DataWarehouseSavedQueryFolder", "QueryTabState"]+__all__ = ["DataWarehouseExpression", "DataWarehouseJoin", "DataWarehouseSavedQueryFolder", "QueryTabState"]diff --git a/products/data_tools/backend/migrations/0003_datawarehouseexpression.py b/products/data_tools/backend/migrations/0003_datawarehouseexpression.pynew file mode 100644index 000000000000..041aaa233e36--- /dev/null+++ b/products/data_tools/backend/migrations/0003_datawarehouseexpression.py@@ -0,0 +1,82 @@+# Generated by Django 5.2.14 on 2026-08-05 12:29++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("data_tools", "0002_migrate_data_modeling_models"),+ ("posthog", "1286_cleanup_orphaned_identity_provider_configs"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="DataWarehouseExpression",+ fields=[+ ("deleted", models.BooleanField(blank=True, default=False, null=True)),+ ("deleted_at", models.DateTimeField(blank=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("table_name", models.CharField(max_length=400)),+ ("field_name", models.CharField(max_length=400)),+ ("expression", models.TextField()),+ ("connection_id", models.UUIDField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(+ ("deleted", False),+ ("deleted__isnull", True),+ _connector="OR",+ ),+ fields=("team", "table_name", "field_name", "connection_id"),+ name="uniq_dw_expression_active_connection",+ ),+ models.UniqueConstraint(+ condition=models.Q(+ models.Q(+ ("deleted", False),+ ("deleted__isnull", True),+ _connector="OR",+ ),+ ("connection_id__isnull", True),+ ),+ fields=("team", "table_name", "field_name"),+ name="uniq_dw_expression_active_default",+ ),+ ],+ },+ ),+ ]diff --git a/products/data_tools/backend/migrations/max_migration.txt b/products/data_tools/backend/migrations/max_migration.txtindex 0559dd24aef7..91157b9fea63 100644--- a/products/data_tools/backend/migrations/max_migration.txt+++ b/products/data_tools/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_migrate_data_modeling_models+0003_datawarehouseexpressiondiff --git a/products/data_tools/backend/models/__init__.py b/products/data_tools/backend/models/__init__.pyindex 66e478b50545..16e152de447e 100644--- a/products/data_tools/backend/models/__init__.py+++ b/products/data_tools/backend/models/__init__.py@@ -1,8 +1,10 @@from .datawarehouse_saved_query_folder import DataWarehouseSavedQueryFolder+from .expression import DataWarehouseExpressionfrom .join import DataWarehouseJoin, DataWarehouseViewLinkfrom .query_tab_state import QueryTabState__all__ = [+ "DataWarehouseExpression","DataWarehouseJoin","DataWarehouseSavedQueryFolder","DataWarehouseViewLink",diff --git a/products/data_tools/backend/models/expression.py b/products/data_tools/backend/models/expression.pynew file mode 100644index 000000000000..a639cb5840cb--- /dev/null+++ b/products/data_tools/backend/models/expression.py@@ -0,0 +1,53 @@+from django.conf import settings+from django.db import models+from django.utils import timezone++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import DeletedMetaFields, UUIDTModel+++class DataWarehouseExpression(ModelActivityMixin, TeamScopedRootMixin, UUIDTModel, DeletedMetaFields):+ """A saved HogQL expression exposed as a virtual field on a table.++ The expression is injected into the team's HogQL database on every build, so the+ field is available in all SQL queries. It can never shadow an existing field:+ injection skips names already present on the table.+ """++ # db_constraint=False on the hot-table FKs (team, created_by) so CreateModel takes no lock+ # on posthog_team / posthog_user; app-level enforcement is enough here.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_at = models.DateTimeField(auto_now_add=True, blank=True)+ created_by = models.ForeignKey(+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )+ table_name = models.CharField(max_length=400)+ field_name = models.CharField(max_length=400)+ expression = models.TextField()+ # ExternalDataSource id when the expression is scoped to one connection's direct-query+ # database; null scopes it to the default warehouse database.+ connection_id = models.UUIDField(null=True, blank=True)++ class Meta:+ # Backstop for the serializer's check-then-act duplicate validation. Two constraints+ # because Postgres treats NULLs as distinct, so a null connection_id needs its own guard.+ # `deleted` is nullable and null counts as active, hence the isnull clause.+ constraints = [+ models.UniqueConstraint(+ fields=["team", "table_name", "field_name", "connection_id"],+ condition=models.Q(deleted=False) | models.Q(deleted__isnull=True),+ name="uniq_dw_expression_active_connection",+ ),+ models.UniqueConstraint(+ fields=["team", "table_name", "field_name"],+ condition=(models.Q(deleted=False) | models.Q(deleted__isnull=True))+ & models.Q(connection_id__isnull=True),+ name="uniq_dw_expression_active_default",+ ),+ ]++ def soft_delete(self) -> None:+ self.deleted = True+ self.deleted_at = timezone.now()+ self.save()diff --git a/products/data_warehouse/backend/presentation/views/expression.py b/products/data_warehouse/backend/presentation/views/expression.pynew file mode 100644index 000000000000..ba030f8f1769--- /dev/null+++ b/products/data_warehouse/backend/presentation/views/expression.py@@ -0,0 +1,273 @@+import hashlib+from typing import Any, Optional, cast++from django.core.validators import RegexValidator+from django.db import IntegrityError, connection, transaction++from rest_framework import filters, response, serializers, viewsets++from posthog.hogql import ast+from posthog.hogql.constants import HogQLDialect+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.models import ExpressionField+from posthog.hogql.direct_connection import resolve_database_for_connection+from posthog.hogql.direct_sql import get_adapter+from posthog.hogql.errors import BaseHogQLError, ExposedHogQLError+from posthog.hogql.parser import parse_expr+from posthog.hogql.printer import prepare_and_print_ast++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.models.user import User+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin++from products.data_tools.backend.facade.models import DataWarehouseExpression++# Same simple-identifier shape as `escape_hogql_identifier`. A whitelist rather than a+# blacklist: names outside it range from unqueryable to actively dangerous ("*" resolves+# as a wildcard, so an injected "*" field would smuggle a bare star into every teammate's+# SELECT * and expose hidden physical columns).+FIELD_NAME_REGEX = r"^[A-Za-z_$][A-Za-z0-9_$]*$"++# Every saved expression is fetched and parsed on every HogQL database build for the team,+# so both per-expression size and total count have to stay bounded.+MAX_EXPRESSION_LENGTH = 10_000+MAX_EXPRESSIONS_PER_TEAM = 500++# First key of the two-key advisory lock serializing per-team cap checks; the second key is the+# team id. Same keying scheme as HealthIssue's upsert lock.+_EXPRESSION_CAP_LOCK_KEY = int.from_bytes(hashlib.sha256(b"dw_expression_cap").digest()[:4], "big", signed=True)+++class DataWarehouseExpressionSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True)++ class Meta:+ model = DataWarehouseExpression+ fields = [+ "id",+ "deleted",+ "created_by",+ "created_at",+ "table_name",+ "field_name",+ "expression",+ "connection_id",+ ]+ read_only_fields = ["id", "created_by", "created_at"]+ extra_kwargs = {+ "deleted": {"help_text": "Whether this expression has been soft-deleted."},+ "table_name": {"help_text": "Name of the table the expression field is added to, for example events."},+ "field_name": {+ "help_text": "Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.",+ "validators": [+ RegexValidator(+ regex=FIELD_NAME_REGEX,+ message="Field name can only contain letters, numbers, underscores and $, and can't start with a number.",+ )+ ],+ },+ "expression": {+ "help_text": "HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).",+ "max_length": MAX_EXPRESSION_LENGTH,+ },+ "connection_id": {+ "help_text": "ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database."+ },+ }++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ instance = cast(Optional[DataWarehouseExpression], self.instance)+ table_name = attrs.get("table_name", instance.table_name if instance else None)+ field_name = attrs.get("field_name", instance.field_name if instance else None)+ expression = attrs.get("expression", instance.expression if instance else None)+ connection_id = attrs.get("connection_id", instance.connection_id if instance else None)+ team = self.context["get_team"]()+ team_id = team.pk++ if not table_name:+ raise serializers.ValidationError({"table_name": ["Table name must not be empty."]})+ if not field_name:+ raise serializers.ValidationError({"field_name": ["Field name must not be empty."]})+ if not expression:+ raise serializers.ValidationError({"expression": ["Expression must not be empty."]})++ # Fast-fail before the expensive probe below; the authoritative, race-safe check runs+ # under an advisory lock inside create()/update().+ if self._becomes_active(attrs) and (instance is None or instance.deleted):+ self._enforce_expression_cap(team_id, instance)++ try:+ source, database = resolve_database_for_connection(+ team=team,+ connection_id=str(connection_id) if connection_id else None,+ user=cast(User, self.context["request"].user),+ error_factory=ValueError,+ )+ except Exception:+ if connection_id:+ raise serializers.ValidationError({"connection_id": ["Invalid connection."]})+ raise+ try:+ table = database.get_table(table_name)+ except Exception:+ raise serializers.ValidationError({"table_name": [f"Invalid table: {table_name}"]})++ # The field this instance already contributes to the built database is the one name it may keep.+ is_own_field = (+ instance is not None+ and not instance.deleted+ and instance.table_name == table_name+ and instance.field_name == field_name+ and instance.connection_id == connection_id+ )+ if not is_own_field and table.fields.get(field_name) is not None:+ raise serializers.ValidationError(+ {+ "field_name": [+ f'Field "{field_name}" already exists on table "{table_name}". Expressions can\'t override existing fields.'+ ]+ }+ )++ duplicates = DataWarehouseExpression.objects.for_team(team_id).filter(+ table_name=table_name, field_name=field_name, connection_id=connection_id, deleted=False+ )+ if instance is not None:+ duplicates = duplicates.exclude(id=instance.id)+ if duplicates.exists():+ raise serializers.ValidationError(+ {"field_name": [f'An expression named "{field_name}" already exists on table "{table_name}".']}+ )++ try:+ expr_node = parse_expr(expression)+ except ExposedHogQLError as e:+ raise serializers.ValidationError({"expression": [str(e)]})++ # Print a probe query with the new field present on the table. Printing (unlike type+ # resolution) fully expands expression fields, so an unknown column or a recursive+ # expression fails here instead of breaking every later query against the table.+ previous_field = table.fields.get(field_name)+ table.fields[field_name] = ExpressionField(name=field_name, expr=expr_node, isolate_scope=True)+ try:+ dialect: HogQLDialect = "clickhouse"+ if source is not None:+ adapter = get_adapter(source.direct_engine)+ dialect = adapter.dialect if adapter is not None and adapter.dialect is not None else "postgres"+ context = HogQLContext(+ team_id=team_id,+ database=database,+ enable_select_queries=True,+ is_direct_query=source is not None,+ )+ probe_query = ast.SelectQuery(+ select=[ast.Field(chain=[field_name])],+ select_from=ast.JoinExpr(table=ast.Field(chain=cast(list[str | int], table_name.split(".")))),+ )+ prepare_and_print_ast(probe_query, context, dialect)+ except ExposedHogQLError as e:+ raise serializers.ValidationError({"expression": [str(e)]})+ except RecursionError:+ raise serializers.ValidationError(+ {"expression": ["Expression can't reference itself, directly or through another expression."]}+ )+ except BaseHogQLError:+ raise serializers.ValidationError(+ {"expression": [f'This expression can\'t be used on table "{table_name}".']}+ )+ finally:+ if previous_field is None:+ table.fields.pop(field_name, None)+ else:+ table.fields[field_name] = previous_field++ return attrs++ def _duplicate_error(self, field_name: str, table_name: str) -> serializers.ValidationError:+ return serializers.ValidationError(+ {"field_name": [f'An expression named "{field_name}" already exists on table "{table_name}".']}+ )++ def _becomes_active(self, validated_data: dict[str, Any]) -> bool:+ instance = cast(Optional[DataWarehouseExpression], self.instance)+ return not validated_data.get("deleted", instance.deleted if instance else False)++ def _enforce_expression_cap(self, team_id: int, instance: Optional[DataWarehouseExpression]) -> None:+ active = DataWarehouseExpression.objects.for_team(team_id).exclude(deleted=True)+ if instance is not None:+ active = active.exclude(id=instance.id)+ if active.count() >= MAX_EXPRESSIONS_PER_TEAM:+ raise serializers.ValidationError(+ f"This project has {MAX_EXPRESSIONS_PER_TEAM} saved expressions, the maximum. Delete one to add another."+ )++ def _lock_and_enforce_expression_cap(+ self, team_id: int, instance: Optional[DataWarehouseExpression], validated_data: dict[str, Any]+ ) -> None:+ """Race-safe cap check for any write that lands in the active state, including restores.++ Must run inside the write's transaction: the advisory lock serializes concurrent+ writers for the team, and the recount under it sees their committed rows.+ """+ if not self._becomes_active(validated_data):+ return+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [_EXPRESSION_CAP_LOCK_KEY, team_id])+ self._enforce_expression_cap(team_id, instance)++ def create(self, validated_data: dict[str, Any]) -> DataWarehouseExpression:+ validated_data["team_id"] = self.context["team_id"]+ validated_data["created_by"] = self.context["request"].user+ try:+ # atomic() takes a savepoint so the caught IntegrityError can't poison an+ # enclosing transaction.+ with transaction.atomic():+ self._lock_and_enforce_expression_cap(validated_data["team_id"], None, validated_data)+ return DataWarehouseExpression.objects.create(**validated_data)+ except IntegrityError:+ # The unique constraints backstop the check-then-act duplicate validation above;+ # losing that race must surface as the same 400, not a 500.+ raise self._duplicate_error(validated_data["field_name"], validated_data["table_name"])++ def update(self, instance: DataWarehouseExpression, validated_data: dict[str, Any]) -> DataWarehouseExpression:+ try:+ with transaction.atomic():+ self._lock_and_enforce_expression_cap(instance.team_id, instance, validated_data)+ return super().update(instance, validated_data)+ except IntegrityError:+ raise self._duplicate_error(+ validated_data.get("field_name", instance.field_name),+ validated_data.get("table_name", instance.table_name),+ )+++class DataWarehouseExpressionViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):+ """+ Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ """++ scope_object = "warehouse_view"+ # `.unscoped()` avoids the fail-closed manager raising at import (no team context yet);+ # `safely_get_queryset` re-scopes every real query to the team.+ queryset = DataWarehouseExpression.objects.unscoped()+ serializer_class = DataWarehouseExpressionSerializer+ filter_backends = [filters.SearchFilter]+ search_fields = ["field_name", "table_name"]+ ordering = "-created_at"++ def safely_get_queryset(self, queryset):+ return queryset.filter(team_id=self.team_id).prefetch_related("created_by").order_by(self.ordering)++ def list(self, request, *args, **kwargs):+ queryset = self.filter_queryset(self.get_queryset().exclude(deleted=True))+ page = self.paginate_queryset(queryset)+ if page is not None:+ serializer = self.get_serializer(page, many=True)+ return self.get_paginated_response(serializer.data)++ serializer = self.get_serializer(queryset, many=True)+ return response.Response(serializer.data)++ def perform_destroy(self, instance: DataWarehouseExpression) -> None:+ instance.soft_delete()diff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.pyindex f9940dd0f47d..e9e380a7e0b8 100644--- a/products/data_warehouse/backend/routes.py+++ b/products/data_warehouse/backend/routes.py@@ -6,6 +6,7 @@ from products.data_warehouse.backend.presentation.views import (column_statistics,data_modeling_job,data_warehouse,+ expression,managed_viewset,modeling,query_tab_state,@@ -37,6 +38,12 @@ def register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"warehouse_view_link", view_link.ViewLinkViewSet, "project_warehouse_view_link", ["team_id"])+ routers.projects.register(+ r"warehouse_expressions",+ expression.DataWarehouseExpressionViewSet,+ "project_warehouse_expressions",+ ["team_id"],+ )routers.projects.register(r"data_warehouse", data_warehouse.DataWarehouseViewSet, "project_data_warehouse", ["team_id"])diff --git a/products/data_warehouse/backend/tests/api/test_expression.py b/products/data_warehouse/backend/tests/api/test_expression.pynew file mode 100644index 000000000000..74037f0d3c53--- /dev/null+++ b/products/data_warehouse/backend/tests/api/test_expression.py@@ -0,0 +1,279 @@+from types import SimpleNamespace+from uuid import uuid4++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework.exceptions import ValidationError as DRFValidationError++from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.database.models import ExpressionField+from posthog.hogql.errors import QueryError+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_and_print_ast++from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.scoping import team_scope++from products.data_tools.backend.models.expression import DataWarehouseExpression+from products.data_warehouse.backend.presentation.views.expression import (+ MAX_EXPRESSION_LENGTH,+ DataWarehouseExpressionSerializer,+)+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+++class TestExpressionApi(APIBaseTest):+ def _create(self, table_name="events", field_name="browser", expression="properties.$browser"):+ return self.client.post(+ f"/api/environments/{self.team.id}/warehouse_expressions/",+ {"table_name": table_name, "field_name": field_name, "expression": expression},+ )++ def _database(self) -> Database:+ return Database.create_for(team_id=self.team.pk, user=self.user)++ def test_create_injects_field_usable_in_queries(self):+ response = self._create()+ self.assertEqual(response.status_code, 201, response.content)+ data = response.json()+ self.assertEqual(data["table_name"], "events")+ self.assertEqual(data["field_name"], "browser")+ self.assertEqual(data["expression"], "properties.$browser")++ database = self._database()+ field = database.get_table("events").fields.get("browser")+ self.assertIsInstance(field, ExpressionField)++ context = HogQLContext(team_id=self.team.pk, database=database, enable_select_queries=True)+ printed, _ = prepare_and_print_ast(parse_select("SELECT browser FROM events"), context, "clickhouse")+ self.assertIn("JSONExtractRaw(events.properties", printed)+ self.assertIn("$browser", context.values.values())++ @parameterized.expand(+ [+ ("override_existing_field", "events", "event", "properties.$browser"),+ ("field_name_with_period", "events", "my.field", "properties.$browser"),+ # "*" resolves as a wildcard, so if it were saved it would smuggle a bare star+ # into every teammate's SELECT * and expose hidden physical columns.+ ("field_name_star", "events", "*", "properties.$browser"),+ ("field_name_with_backtick", "events", "bro`wser", "properties.$browser"),+ ("unknown_table", "not_a_table", "browser", "properties.$browser"),+ ("syntax_error", "events", "browser", "properties.$browser +"),+ ("unknown_column", "events", "browser", "upper(nonexistent_column)"),+ ("empty_expression", "events", "browser", ""),+ ("expression_too_long", "events", "browser", "1 + " + "1" * MAX_EXPRESSION_LENGTH),+ ]+ )+ def test_invalid_input_rejected(self, _name, table_name, field_name, expression):+ response = self._create(table_name=table_name, field_name=field_name, expression=expression)+ self.assertEqual(response.status_code, 400, response.content)+ self.assertEqual(DataWarehouseExpression.objects.for_team(self.team.pk).count(), 0)++ def test_per_team_count_cap(self):+ with patch(+ "products.data_warehouse.backend.presentation.views.expression.MAX_EXPRESSIONS_PER_TEAM",+ 1,+ ):+ self.assertEqual(self._create().status_code, 201)+ response = self._create(field_name="os", expression="properties.$os")+ self.assertEqual(response.status_code, 400, response.content)++ # Soft-deleted rows don't count toward the cap on create, and restoring one+ # past the cap must be blocked too - otherwise create-deleted-then-restore+ # bypasses the limit entirely.+ deleted_response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_expressions/",+ {"table_name": "events", "field_name": "os", "expression": "properties.$os", "deleted": True},+ )+ self.assertEqual(deleted_response.status_code, 201, deleted_response.content)+ restore_url = f"/api/environments/{self.team.id}/warehouse_expressions/{deleted_response.json()['id']}/"+ self.assertEqual(self.client.patch(restore_url, {"deleted": False}).status_code, 400)++ # Restoring is fine once the team is back under the cap.+ active_id = DataWarehouseExpression.objects.for_team(self.team.pk).get(deleted=False).id+ self.client.delete(f"/api/environments/{self.team.id}/warehouse_expressions/{active_id}/")+ self.assertEqual(self.client.patch(restore_url, {"deleted": False}).status_code, 200)++ def test_mutually_recursive_expressions_fail_as_query_error(self):+ # Bypasses API validation the way a concurrent-save race would: each expression was+ # validated against a database that didn't yet contain the other.+ with team_scope(self.team.pk):+ DataWarehouseExpression.objects.create(+ team=self.team, table_name="events", field_name="field_a", expression="field_b"+ )+ DataWarehouseExpression.objects.create(+ team=self.team, table_name="events", field_name="field_b", expression="field_a"+ )++ context = HogQLContext(team_id=self.team.pk, database=self._database(), enable_select_queries=True)+ with self.assertRaises(QueryError):+ prepare_and_print_ast(parse_select("SELECT field_a FROM events"), context, "clickhouse")++ def test_duplicate_field_name_rejected(self):+ self.assertEqual(self._create().status_code, 201)+ response = self._create(expression="properties.$os")+ self.assertEqual(response.status_code, 400, response.content)++ def test_losing_duplicate_race_surfaces_as_validation_error(self):+ self.assertEqual(self._create().status_code, 201)++ # Calling create() directly skips validate()'s duplicate check, like a request that+ # passed validation concurrently and lost the race to the unique constraint.+ serializer = DataWarehouseExpressionSerializer(+ context={"team_id": self.team.pk, "request": SimpleNamespace(user=self.user)}+ )+ with team_scope(self.team.pk), self.assertRaises(DRFValidationError):+ serializer.create({"table_name": "events", "field_name": "browser", "expression": "1"})++ def test_update_changes_expression_and_rejects_self_reference(self):+ expression_id = self._create().json()["id"]++ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_expressions/{expression_id}/",+ {"expression": "upper(properties.$os)"},+ )+ self.assertEqual(response.status_code, 200, response.content)++ database = self._database()+ field = database.get_table("events").fields["browser"]+ assert isinstance(field, ExpressionField)+ self.assertEqual(field.expr.to_hogql(), "upper(properties.$os)")++ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_expressions/{expression_id}/",+ {"expression": "upper(browser)"},+ )+ self.assertEqual(response.status_code, 400, response.content)++ def test_soft_delete_removes_field(self):+ expression_id = self._create().json()["id"]++ response = self.client.delete(f"/api/environments/{self.team.id}/warehouse_expressions/{expression_id}/")+ self.assertEqual(response.status_code, 204, response.content)++ self.assertNotIn("browser", self._database().get_table("events").fields)+ self.assertEqual(+ self.client.get(f"/api/environments/{self.team.id}/warehouse_expressions/").json()["results"], []+ )+ expression = DataWarehouseExpression.objects.for_team(self.team.pk).get(id=expression_id)+ self.assertTrue(expression.deleted)++ def test_activity_log_records_who_did_what(self):+ expression_id = self._create().json()["id"]+ self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_expressions/{expression_id}/",+ {"expression": "upper(properties.$os)"},+ )+ self.client.delete(f"/api/environments/{self.team.id}/warehouse_expressions/{expression_id}/")++ logs = list(+ ActivityLog.objects.filter(team_id=self.team.pk, scope="DataWarehouseExpression", item_id=expression_id)+ .order_by("created_at")+ .values_list("activity", "user__email", "detail__name")+ )+ self.assertEqual(+ logs,+ [+ ("created", self.user.email, "events.browser"),+ ("updated", self.user.email, "events.browser"),+ ("deleted", self.user.email, "events.browser"),+ ],+ )++ @parameterized.expand(+ [+ (+ "postgres",+ "Postgres",+ {+ "host": "localhost",+ "port": 5432,+ "database": "postgres",+ "user": "postgres",+ "password": "postgres",+ "schema": "public",+ },+ ),+ (+ "clickhouse",+ "ClickHouse",+ {+ "host": "localhost",+ "port": 8443,+ "database": "posthog",+ "user": "default",+ "password": "password",+ },+ ),+ ]+ )+ def test_connection_scoped_expression_saves_in_source_dialect(+ self, _name: str, source_type: str, job_inputs: dict[str, object]+ ) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status=ExternalDataSource.Status.COMPLETED,+ source_type=source_type,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix="direct",+ job_inputs=job_inputs,+ )+ DataWarehouseTable.objects.create(+ name="events",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern="",+ columns={+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},+ "team_id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},+ },+ )++ create_response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_expressions/",+ {+ "table_name": "events",+ "field_name": "scoped_field",+ "expression": "id + 1",+ "connection_id": str(source.id),+ },+ )+ self.assertEqual(create_response.status_code, 201, create_response.content)++ expression_id = create_response.json()["id"]+ update_response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_expressions/{expression_id}/",+ {"expression": "id + 2"},+ )+ self.assertEqual(update_response.status_code, 200, update_response.content)+ self.assertEqual(update_response.json()["expression"], "id + 2")++ direct_database = Database.create_for(+ team=self.team,+ user=self.user,+ connection_id=str(source.id),+ )+ field = direct_database.get_table("events").fields["scoped_field"]+ assert isinstance(field, ExpressionField)+ self.assertNotIn("scoped_field", self._database().get_table("events").fields)++ def test_stale_expression_degrades_instead_of_breaking_schema(self):+ # Bypasses API validation the way a valid expression goes stale in real life: the+ # referenced column exists at save time and disappears later.+ with team_scope(self.team.pk):+ DataWarehouseExpression.objects.create(+ team=self.team, table_name="events", field_name="broken", expression="upper(gone_column)"+ )++ database = self._database()+ self.assertIsInstance(database.get_table("events").fields.get("broken"), ExpressionField)++ context = HogQLContext(team_id=self.team.pk, database=database)+ serialized = database.serialize(context)+ self.assertIn("broken", serialized["events"].fields)diff --git a/products/data_warehouse/backend/tests/api/test_expression_access_control.py b/products/data_warehouse/backend/tests/api/test_expression_access_control.pynew file mode 100644index 000000000000..e68d8cce24b2--- /dev/null+++ b/products/data_warehouse/backend/tests/api/test_expression_access_control.py@@ -0,0 +1,59 @@+from uuid import uuid4++import pytest++from rest_framework import status++from posthog.hogql.database.database import Database++from products.warehouse_sources.backend.tests.api._access_control_base import WarehouseAccessControlTestMixin+++class TestExpressionAccessControl(WarehouseAccessControlTestMixin):+ # DataWarehouseExpressionViewSet scope_object = "warehouse_view", which inherits from+ # "warehouse_objects" in RESOURCE_INHERITANCE_MAP — grant at the umbrella.+ resource = "warehouse_objects"++ def _url(self, expression_id: str | None = None) -> str:+ base = f"/api/environments/{self.team.pk}/warehouse_expressions/"+ return f"{base}{expression_id}/" if expression_id else base++ def test_object_grant_on_unrelated_view_does_not_authorize_expressions(self):+ expression_id = self.client.post(+ self._url(),+ {"table_name": "events", "field_name": "browser", "expression": "properties.$browser"},+ ).json()["id"]++ self._create_project_default(access_level="none")+ # An object-level grant on one unrelated saved view passes the generic resource+ # permission check; it must not extend to other users' expressions.+ self._create_access_control(+ self.viewer_user, resource="warehouse_view", resource_id=str(uuid4()), access_level="editor"+ )+ self.client.force_login(self.viewer_user)++ list_response = self.client.get(self._url())+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ self.assertEqual(list_response.json()["results"], [])++ patch_response = self.client.patch(self._url(expression_id), {"expression": "upper(event)"})+ self.assertEqual(patch_response.status_code, status.HTTP_403_FORBIDDEN, patch_response.content)++ delete_response = self.client.delete(self._url(expression_id))+ self.assertEqual(delete_response.status_code, status.HTTP_403_FORBIDDEN, delete_response.content)++ def test_object_denied_expression_is_not_injected_into_queries(self):+ expression_id = self.client.post(+ self._url(),+ {"table_name": "events", "field_name": "browser", "expression": "properties.$browser"},+ ).json()["id"]+ self._create_access_control(+ self.viewer_user, resource="warehouse_view", resource_id=expression_id, access_level="none"+ )++ for user, should_have_field in ((self.viewer_user, False), (self.editor_user, True)):+ sources = Database._fetch_sources(team=self.team, user=user)+ sources.is_hogql_warehouse_access_control_enabled = True+ database = Database._build_from_sources(sources)+ self.assertEqual("browser" in database.get_table("events").fields, should_have_field, user.email)diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 593da7dac757..5377867549da 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -797,6 +797,79 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+export interface DataWarehouseExpressionApi {+ readonly id: string+ /**+ * Whether this expression has been soft-deleted.+ * @nullable+ */+ deleted?: boolean | null+ readonly created_by: UserBasicApi+ readonly created_at: string+ /**+ * Name of the table the expression field is added to, for example events.+ * @maxLength 400+ */+ table_name: string+ /**+ * Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.+ * @maxLength 400+ * @pattern ^[A-Za-z_$][A-Za-z0-9_$]*$+ */+ field_name: string+ /**+ * HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).+ * @maxLength 10000+ */+ expression: string+ /**+ * ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database.+ * @nullable+ */+ connection_id?: string | null+}++export interface PaginatedDataWarehouseExpressionListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DataWarehouseExpressionApi[]+}++export interface PatchedDataWarehouseExpressionApi {+ readonly id?: string+ /**+ * Whether this expression has been soft-deleted.+ * @nullable+ */+ deleted?: boolean | null+ readonly created_by?: UserBasicApi+ readonly created_at?: string+ /**+ * Name of the table the expression field is added to, for example events.+ * @maxLength 400+ */+ table_name?: string+ /**+ * Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.+ * @maxLength 400+ * @pattern ^[A-Za-z_$][A-Za-z0-9_$]*$+ */+ field_name?: string+ /**+ * HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).+ * @maxLength 10000+ */+ expression?: string+ /**+ * ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database.+ * @nullable+ */+ connection_id?: string | null+}+export interface DataWarehouseModelPathApi {readonly id: stringreadonly path: readonly string[]@@ -4341,6 +4414,21 @@ export type WarehouseColumnStatisticsListParams = {table_id?: string}+export type WarehouseExpressionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * A search term.+ */+ search?: string+}+export type WarehouseModelPathsListParams = {/*** Number of results to return per page.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 929b1756f4e3..fc40f5861861 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -16,6 +16,7 @@ import type {DataModelingJobsListParams,DataWarehouseCheckDatabaseNameRetrieveParams,DataWarehouseCheckSchemaNameRetrieveParams,+ DataWarehouseExpressionApi,DataWarehouseManagedWarehouseSourceSchemasRetrieveParams,DataWarehouseModelPathApi,DataWarehouseSavedQueryApi,@@ -33,6 +34,7 @@ import type {OnboardWarehouseTeamRequestApi,OnboardWarehouseTeamResponseApi,PaginatedDataModelingJobListApi,+ PaginatedDataWarehouseExpressionListApi,PaginatedDataWarehouseModelPathListApi,PaginatedDataWarehouseSavedQueryColumnAnnotationListApi,PaginatedDataWarehouseSavedQueryDraftListApi,@@ -43,6 +45,7 @@ import type {PaginatedViewLinkListApi,PaginatedWarehouseColumnAnnotationListApi,PaginatedWarehouseColumnStatisticsListApi,+ PatchedDataWarehouseExpressionApi,PatchedDataWarehouseSavedQueryApi,PatchedDataWarehouseSavedQueryColumnAnnotationApi,PatchedDataWarehouseSavedQueryDraftApi,@@ -68,6 +71,7 @@ import type {WarehouseColumnAnnotationsListParams,WarehouseColumnStatisticsApi,WarehouseColumnStatisticsListParams,+ WarehouseExpressionsListParams,WarehouseModelPathsListParams,WarehouseSavedQueriesListParams,WarehouseSavedQueryDraftsListParams,@@ -1298,6 +1302,134 @@ export const warehouseDagList = async (projectId: string, options?: RequestInit)})}+export const getWarehouseExpressionsListUrl = (projectId: string, params?: WarehouseExpressionsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/warehouse_expressions/?${stringifiedParams}`+ : `/api/projects/${projectId}/warehouse_expressions/`+}++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsList = async (+ projectId: string,+ params?: WarehouseExpressionsListParams,+ options?: RequestInit+): Promise<PaginatedDataWarehouseExpressionListApi> => {+ return apiMutator<PaginatedDataWarehouseExpressionListApi>(getWarehouseExpressionsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseExpressionsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/warehouse_expressions/`+}++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsCreate = async (+ projectId: string,+ dataWarehouseExpressionApi: NonReadonly<DataWarehouseExpressionApi>,+ options?: RequestInit+): Promise<DataWarehouseExpressionApi> => {+ return apiMutator<DataWarehouseExpressionApi>(getWarehouseExpressionsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataWarehouseExpressionApi),+ })+}++export const getWarehouseExpressionsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_expressions/${id}/`+}++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<DataWarehouseExpressionApi> => {+ return apiMutator<DataWarehouseExpressionApi>(getWarehouseExpressionsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseExpressionsUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_expressions/${id}/`+}++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsUpdate = async (+ projectId: string,+ id: string,+ dataWarehouseExpressionApi: NonReadonly<DataWarehouseExpressionApi>,+ options?: RequestInit+): Promise<DataWarehouseExpressionApi> => {+ return apiMutator<DataWarehouseExpressionApi>(getWarehouseExpressionsUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataWarehouseExpressionApi),+ })+}++export const getWarehouseExpressionsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_expressions/${id}/`+}++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsPartialUpdate = async (+ projectId: string,+ id: string,+ patchedDataWarehouseExpressionApi?: NonReadonly<PatchedDataWarehouseExpressionApi>,+ options?: RequestInit+): Promise<DataWarehouseExpressionApi> => {+ return apiMutator<DataWarehouseExpressionApi>(getWarehouseExpressionsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataWarehouseExpressionApi),+ })+}++export const getWarehouseExpressionsDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_expressions/${id}/`+}++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsDestroy = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getWarehouseExpressionsDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}+export const getWarehouseModelPathsListUrl = (projectId: string, params?: WarehouseModelPathsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex 0b036f17c1ab..a7d75c0f8e56 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -273,6 +273,120 @@ export const WarehouseColumnAnnotationsPartialUpdateBody = /* @__PURE__ */ zod"Shared serializer for the physical-table and saved-query-view annotation surfaces.\n\nSubclasses add a `Meta` (model + fields) and the parent foreign-key field (`table`\/`saved_query`),\nand set `parent_field_name` to that FK's name. The shared field definitions and the\nimmutable-FK-on-update rule live here; column-name validation lives on the viewset so it runs after\nthe editor-access check (avoiding a schema leak to callers denied the parent).")+/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsCreateBodyTableNameMax = 400++export const warehouseExpressionsCreateBodyFieldNameMax = 400++export const warehouseExpressionsCreateBodyFieldNameRegExp = new RegExp('^[A-Za-z_$][A-Za-z0-9_$]\*$')+export const warehouseExpressionsCreateBodyExpressionMax = 10000++export const WarehouseExpressionsCreateBody = /* @__PURE__ */ zod.object({+ deleted: zod.boolean().nullish().describe('Whether this expression has been soft-deleted.'),+ table_name: zod+ .string()+ .max(warehouseExpressionsCreateBodyTableNameMax)+ .describe('Name of the table the expression field is added to, for example events.'),+ field_name: zod+ .string()+ .max(warehouseExpressionsCreateBodyFieldNameMax)+ .regex(warehouseExpressionsCreateBodyFieldNameRegExp)+ .describe(+ 'Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.'+ ),+ expression: zod+ .string()+ .max(warehouseExpressionsCreateBodyExpressionMax)+ .describe(+ 'HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).'+ ),+ connection_id: zod+ .uuid()+ .nullish()+ .describe(+ "ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database."+ ),+})++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsUpdateBodyTableNameMax = 400++export const warehouseExpressionsUpdateBodyFieldNameMax = 400++export const warehouseExpressionsUpdateBodyFieldNameRegExp = new RegExp('^[A-Za-z_$][A-Za-z0-9_$]\*$')+export const warehouseExpressionsUpdateBodyExpressionMax = 10000++export const WarehouseExpressionsUpdateBody = /* @__PURE__ */ zod.object({+ deleted: zod.boolean().nullish().describe('Whether this expression has been soft-deleted.'),+ table_name: zod+ .string()+ .max(warehouseExpressionsUpdateBodyTableNameMax)+ .describe('Name of the table the expression field is added to, for example events.'),+ field_name: zod+ .string()+ .max(warehouseExpressionsUpdateBodyFieldNameMax)+ .regex(warehouseExpressionsUpdateBodyFieldNameRegExp)+ .describe(+ 'Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.'+ ),+ expression: zod+ .string()+ .max(warehouseExpressionsUpdateBodyExpressionMax)+ .describe(+ 'HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).'+ ),+ connection_id: zod+ .uuid()+ .nullish()+ .describe(+ "ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database."+ ),+})++/**+ * Create, read, update and delete saved HogQL expressions that appear as virtual fields on tables.+ */+export const warehouseExpressionsPartialUpdateBodyTableNameMax = 400++export const warehouseExpressionsPartialUpdateBodyFieldNameMax = 400++export const warehouseExpressionsPartialUpdateBodyFieldNameRegExp = new RegExp('^[A-Za-z_$][A-Za-z0-9_$]\*$')+export const warehouseExpressionsPartialUpdateBodyExpressionMax = 10000++export const WarehouseExpressionsPartialUpdateBody = /* @__PURE__ */ zod.object({+ deleted: zod.boolean().nullish().describe('Whether this expression has been soft-deleted.'),+ table_name: zod+ .string()+ .max(warehouseExpressionsPartialUpdateBodyTableNameMax)+ .optional()+ .describe('Name of the table the expression field is added to, for example events.'),+ field_name: zod+ .string()+ .max(warehouseExpressionsPartialUpdateBodyFieldNameMax)+ .regex(warehouseExpressionsPartialUpdateBodyFieldNameRegExp)+ .optional()+ .describe(+ 'Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.'+ ),+ expression: zod+ .string()+ .max(warehouseExpressionsPartialUpdateBodyExpressionMax)+ .optional()+ .describe(+ 'HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).'+ ),+ connection_id: zod+ .uuid()+ .nullish()+ .describe(+ "ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database."+ ),+})+/*** Create, Read, Update and Delete Warehouse Tables.*/diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsxindex f4b6288d4332..e53fd530f2db 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx@@ -84,7 +84,8 @@ export function DirectQuerySchemasTab({ id }: DirectQuerySchemasTabProps): JSX.Econst logic = sourceSettingsLogic({ id })const { source, sourceLoading, filteredSchemas, showEnabledSchemasOnly, schemaNameFilter, refreshingSchemas } =useValues(logic)- const { setShowEnabledSchemasOnly, setSchemaNameFilter, refreshSchemas, updateSchema } = useActions(logic)+ const { setShowEnabledSchemasOnly, setSchemaNameFilter, refreshSchemas, updateSchema, updateSchemas } =+ useActions(logic)const [columnModalSchema, setColumnModalSchema] = useState<ExternalDataSourceSchema | null>(null)@@ -127,6 +128,7 @@ export function DirectQuerySchemasTab({ id }: DirectQuerySchemasTabProps): JSX.EgroupedSchemas={groupedSchemas}isLoading={sourceLoading}updateSchema={updateSchema}+ updateSchemas={updateSchemas}onConfigureColumns={setColumnModalSchema}/><ColumnSelectionModal@@ -149,12 +151,14 @@ function DirectQuerySchemaGroups({groupedSchemas,isLoading,updateSchema,+ updateSchemas,onConfigureColumns,}: {source: ExternalDataSource | nullgroupedSchemas: { schemaName: string; schemas: ExternalDataSourceSchema[] }[]isLoading: booleanupdateSchema: (schema: ExternalDataSourceSchema) => void+ updateSchemas: (schemas: ExternalDataSourceSchema[]) => voidonConfigureColumns?: (schema: ExternalDataSourceSchema) => void}): JSX.Element {const [initialLoad, setInitialLoad] = useState(true)@@ -201,16 +205,17 @@ function DirectQuerySchemaGroups({const toggleDirectQuerySchemaGroup = useCallback((schemaName: string, shouldSync: boolean) => {const schemaGroup = groupedSchemas.find((group) => group.schemaName === schemaName)- for (const schema of schemaGroup?.schemas ?? []) {- setDirectQuerySchemaEnabled(schema, shouldSync)- }+ const updatedSchemas = (schemaGroup?.schemas ?? [])+ .filter((schema) => schema.should_sync !== shouldSync)+ .map((schema) => ({ ...schema, should_sync: shouldSync }))+ updateSchemas(updatedSchemas)setExpandedSchemaKeys((currentKeys) =>shouldSync? Array.from(new Set([...currentKeys, schemaName])): currentKeys.filter((key) => key !== schemaName))},- [groupedSchemas, setDirectQuerySchemaEnabled]+ [groupedSchemas, updateSchemas])if (initialLoad) {diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.tsindex 77ee27f33882..f403425ab9b1 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts@@ -85,6 +85,39 @@ describe('sourceSettingsLogic', () => {])})+ it('updates a large schema group optimistically with one batch save', async () => {+ const schemas = Array.from({ length: 300 }, (_, index) =>+ makeSchema({ id: `schema-${index}`, name: `public.table_${index}` })+ )+ jest.spyOn(api.externalDataSources, 'get').mockResolvedValue(makeSource(schemas))+ const bulkUpdateSchemasSpy = jest+ .spyOn(api.externalDataSources, 'bulkUpdateSchemas')+ .mockImplementation(async (_id, updates) =>+ updates.map((update) => ({ ...schemas.find((schema) => schema.id === update.id)!, ...update }))+ )++ logic = sourceSettingsLogic({ id: 'source-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ jest.useFakeTimers()++ logic.actions.updateSchemas(schemas.map((schema) => ({ ...schema, should_sync: true })))++ expect(logic.values.source?.schemas.every((schema) => schema.should_sync)).toBe(true)+ expect(bulkUpdateSchemasSpy).not.toHaveBeenCalled()++ await jest.advanceTimersByTimeAsync(500)++ expect(bulkUpdateSchemasSpy).toHaveBeenCalledTimes(1)+ expect(bulkUpdateSchemasSpy.mock.calls[0][1]).toHaveLength(300)+ expect(bulkUpdateSchemasSpy.mock.calls[0][1]).toEqual(+ expect.arrayContaining([+ { id: 'schema-0', should_sync: true },+ { id: 'schema-299', should_sync: true },+ ])+ )+ })+it('keeps newer queued changes when an older save resolves later', async () => {let resolveFirstRequest: ((schema: ExternalDataSourceSchema) => void) | null = nullconst bulkUpdateSchemasSpy = jest.spyOn(api.externalDataSources, 'bulkUpdateSchemas').mockImplementation(diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.tsindex f6ffa88d36b0..8f35935a72b4 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts@@ -116,36 +116,13 @@ interface SchemaUpdateCache {reapplyingOptimisticSource?: boolean}-function applySchemaToSource(- source: ExternalDataSource | null,- schema: ExternalDataSourceSchema-): ExternalDataSource | null {- if (!source) {- return source- }-- const clonedSource = JSON.parse(JSON.stringify(source)) as ExternalDataSource- const schemaIndex = clonedSource.schemas.findIndex((item) => item.id === schema.id)-- if (schemaIndex === -1) {- return source- }-- clonedSource.schemas[schemaIndex] = schema- return clonedSource-}-function applyPendingSchemaUpdatesToSource(source: ExternalDataSource | null,pendingSchemaUpdates: Record<string, PendingSchemaUpdate>): ExternalDataSource | null {- if (!source) {- return source- }-- return Object.values(pendingSchemaUpdates).reduce<ExternalDataSource | null>(- (currentSource, pendingUpdate) => applySchemaToSource(currentSource, pendingUpdate.schema),- source+ return applySchemasToSource(+ source,+ Object.values(pendingSchemaUpdates).map((pendingUpdate) => pendingUpdate.schema))}@@ -153,10 +130,22 @@ function applySchemasToSource(source: ExternalDataSource | null,schemas: ExternalDataSourceSchema[]): ExternalDataSource | null {- return schemas.reduce<ExternalDataSource | null>(- (currentSource, schema) => applySchemaToSource(currentSource, schema),- source- )+ if (!source || schemas.length === 0) {+ return source+ }++ const updatesById = new Map(schemas.map((schema) => [schema.id, schema]))+ let hasUpdates = false+ const nextSchemas = source.schemas.map((schema) => {+ const updatedSchema = updatesById.get(schema.id)+ if (!updatedSchema) {+ return schema+ }+ hasUpdates = true+ return updatedSchema+ })++ return hasUpdates ? { ...source, schemas: nextSchemas } : source}// PATCH body of only the changed fields (+ id). The backend writes every field it receives, so@@ -626,6 +615,9 @@ export interface sourceSettingsLogicActions {payload: ExternalDataSourceSchema | undefinedsource: ExternalDataSource | null}+ updateSchemas: (schemas: ExternalDataSourceSchema[]) => {+ schemas: ExternalDataSourceSchema[]+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -704,6 +696,7 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([refreshSchemas: true,setRefreshingSchemas: (refreshing: boolean) => ({ refreshing }),updateSchema: (schema: ExternalDataSourceSchema) => schema,+ updateSchemas: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),updateSchemaSuccess: (source: ExternalDataSource | null, payload?: ExternalDataSourceSchema) => ({source,payload,@@ -1211,32 +1204,47 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([}, SCHEMA_UPDATE_DEBOUNCE_MS)}- return {- updateSchema: (schema) => {- const nextRevision = (schemaUpdateCache.schemaUpdateRevisions[schema.id] ?? 0) + 1+ const queueSchemaUpdates = (schemas: ExternalDataSourceSchema[]): void => {+ const baselineSchemasById = new Map(values.source?.schemas.map((schema) => [schema.id, schema]) ?? [])+ let hasQueuedUpdates = false- schemaUpdateCache.schemaUpdateRevisions[schema.id] = nextRevision-- // Union this edit's changed fields with any not-yet-flushed pending edit's, so- // coalesced edits send everything that changed — not just the latest field.- const baselineSchema = values.source?.schemas.find((item) => item.id === schema.id)- const changedFields = diffSchemaPayloadFields(schema, baselineSchema)+ for (const schema of schemas) {+ const changedFields = diffSchemaPayloadFields(schema, baselineSchemasById.get(schema.id))for (const field of schemaUpdateCache.pendingSchemaUpdates[schema.id]?.changedFields ?? []) {changedFields.add(field)}+ if (changedFields.size === 0) {+ continue+ }+ const nextRevision = (schemaUpdateCache.schemaUpdateRevisions[schema.id] ?? 0) + 1+ schemaUpdateCache.schemaUpdateRevisions[schema.id] = nextRevisionschemaUpdateCache.pendingSchemaUpdates[schema.id] = { schema, revision: nextRevision, changedFields }+ hasQueuedUpdates = true+ }- const optimisticSource = applyPendingSchemaUpdatesToSource(- values.source,- getOptimisticSchemaUpdates(schemaUpdateCache)- )- if (optimisticSource) {- schemaUpdateCache.reapplyingOptimisticSource = true- actions.loadSourceSuccess(optimisticSource)- }+ if (!hasQueuedUpdates) {+ return+ }++ const optimisticSource = applyPendingSchemaUpdatesToSource(+ values.source,+ getOptimisticSchemaUpdates(schemaUpdateCache)+ )+ if (optimisticSource) {+ schemaUpdateCache.reapplyingOptimisticSource = true+ actions.loadSourceSuccess(optimisticSource)+ }- scheduleSchemaUpdateFlush()+ scheduleSchemaUpdateFlush()+ }++ return {+ updateSchema: (schema) => {+ queueSchemaUpdates([schema])+ },+ updateSchemas: ({ schemas }) => {+ queueSchemaUpdates(schemas)},loadSourceSuccess: () => {const optimisticSchemaUpdates = getOptimisticSchemaUpdates(schemaUpdateCache)diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex c0d4b194324b..55672d483ccc 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -468,6 +468,24 @@ tools:warehouse-dag-list:operation: warehouse_dag_listenabled: false+ warehouse-expressions-create:+ operation: warehouse_expressions_create+ enabled: false+ warehouse-expressions-destroy:+ operation: warehouse_expressions_destroy+ enabled: false+ warehouse-expressions-list:+ operation: warehouse_expressions_list+ enabled: false+ warehouse-expressions-partial-update:+ operation: warehouse_expressions_partial_update+ enabled: false+ warehouse-expressions-retrieve:+ operation: warehouse_expressions_retrieve+ enabled: false+ warehouse-expressions-update:+ operation: warehouse_expressions_update+ enabled: falsewarehouse-model-paths-list:operation: warehouse_model_paths_listenabled: falsediff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 6de570194bb9..10d1e9682c79 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1108,6 +1108,7 @@ export type ActivityLogListParams = {* * `Team` - Team* * `Project` - Project* * `ErrorTrackingIssue` - ErrorTrackingIssue+ * * `DataWarehouseExpression` - DataWarehouseExpression* * `DataWarehouseSavedQuery` - DataWarehouseSavedQuery* * `LegalDocument` - LegalDocument* * `Organization` - Organization@@ -1200,6 +1201,7 @@ export const ActivityLogListScope = {Team: 'Team',Project: 'Project',ErrorTrackingIssue: 'ErrorTrackingIssue',+ DataWarehouseExpression: 'DataWarehouseExpression',DataWarehouseSavedQuery: 'DataWarehouseSavedQuery',LegalDocument: 'LegalDocument',Organization: 'Organization',@@ -1279,6 +1281,7 @@ export const ActivityLogListScope = {* * `Team` - Team* * `Project` - Project* * `ErrorTrackingIssue` - ErrorTrackingIssue+ * * `DataWarehouseExpression` - DataWarehouseExpression* * `DataWarehouseSavedQuery` - DataWarehouseSavedQuery* * `LegalDocument` - LegalDocument* * `Organization` - Organization@@ -1359,6 +1362,7 @@ export const ActivityLogListScopesItem = {Team: 'Team',Project: 'Project',ErrorTrackingIssue: 'ErrorTrackingIssue',+ DataWarehouseExpression: 'DataWarehouseExpression',DataWarehouseSavedQuery: 'DataWarehouseSavedQuery',LegalDocument: 'LegalDocument',Organization: 'Organization',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 24ce68900799..736bc91b3a9b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18061,6 +18061,38 @@ export namespace Schemas {issues_summary: string[];}+ export interface DataWarehouseExpression {+ readonly id: string;+ /**+ * Whether this expression has been soft-deleted.+ * @nullable+ */+ deleted?: boolean | null;+ readonly created_by: UserBasic;+ readonly created_at: string;+ /**+ * Name of the table the expression field is added to, for example events.+ * @maxLength 400+ */+ table_name: string;+ /**+ * Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.+ * @maxLength 400+ * @pattern ^[A-Za-z_$][A-Za-z0-9_$]*$+ */+ field_name: string;+ /**+ * HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).+ * @maxLength 10000+ */+ expression: string;+ /**+ * ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database.+ * @nullable+ */+ connection_id?: string | null;+ }+export interface DataWarehouseModelPath {readonly id: string;readonly path: readonly string[];@@ -46090,6 +46122,15 @@ export namespace Schemas {results: DataModelingJob[];}+ export interface PaginatedDataWarehouseExpressionList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: DataWarehouseExpression[];+ }+export interface PaginatedDataWarehouseModelPathList {count: number;/** @nullable */@@ -52525,6 +52566,38 @@ export namespace Schemas {readonly created_by?: UserBasic;}+ export interface PatchedDataWarehouseExpression {+ readonly id?: string;+ /**+ * Whether this expression has been soft-deleted.+ * @nullable+ */+ deleted?: boolean | null;+ readonly created_by?: UserBasic;+ readonly created_at?: string;+ /**+ * Name of the table the expression field is added to, for example events.+ * @maxLength 400+ */+ table_name?: string;+ /**+ * Name of the virtual field the expression is exposed as. Letters, numbers, underscores and $ only, starting with a letter, underscore or $. Must not clash with an existing field on the table.+ * @maxLength 400+ * @pattern ^[A-Za-z_$][A-Za-z0-9_$]*$+ */+ field_name?: string;+ /**+ * HogQL expression evaluated in the context of the table, for example properties.$browser or lower(email).+ * @maxLength 10000+ */+ expression?: string;+ /**+ * ExternalDataSource id to scope the expression to that connection's direct-query database. Null applies it to the default warehouse database.+ * @nullable+ */+ connection_id?: string | null;+ }+export type PatchedDataWarehouseSavedQueryQueryKind = typeof PatchedDataWarehouseSavedQueryQueryKind[keyof typeof PatchedDataWarehouseSavedQueryQueryKind];@@ -79231,6 +79304,7 @@ export namespace Schemas {* * `Team` - Team* * `Project` - Project* * `ErrorTrackingIssue` - ErrorTrackingIssue+ * * `DataWarehouseExpression` - DataWarehouseExpression* * `DataWarehouseSavedQuery` - DataWarehouseSavedQuery* * `LegalDocument` - LegalDocument* * `Organization` - Organization@@ -79324,6 +79398,7 @@ export namespace Schemas {Team: 'Team',Project: 'Project',ErrorTrackingIssue: 'ErrorTrackingIssue',+ DataWarehouseExpression: 'DataWarehouseExpression',DataWarehouseSavedQuery: 'DataWarehouseSavedQuery',LegalDocument: 'LegalDocument',Organization: 'Organization',@@ -79403,6 +79478,7 @@ export namespace Schemas {* * `Team` - Team* * `Project` - Project* * `ErrorTrackingIssue` - ErrorTrackingIssue+ * * `DataWarehouseExpression` - DataWarehouseExpression* * `DataWarehouseSavedQuery` - DataWarehouseSavedQuery* * `LegalDocument` - LegalDocument* * `Organization` - Organization@@ -79484,6 +79560,7 @@ export namespace Schemas {Team: 'Team',Project: 'Project',ErrorTrackingIssue: 'ErrorTrackingIssue',+ DataWarehouseExpression: 'DataWarehouseExpression',DataWarehouseSavedQuery: 'DataWarehouseSavedQuery',LegalDocument: 'LegalDocument',Organization: 'Organization',@@ -87888,6 +87965,21 @@ export namespace Schemas {table_id?: string;};+ export type WarehouseExpressionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * A search term.+ */+ search?: string;+ };+export type WarehouseModelPathsListParams = {/*** Number of results to return per page.