summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/SQLStore/EntityStore/PropertySubjectsLookup.php
blob: 4866c18b9c99571f0c3c252c6d380132fdbe4387 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php

namespace SMW\SQLStore\EntityStore;

use SMW\SQLStore\SQLStore;
use SMW\SQLStore\PropertyTableDefinition as TableDefinition;
use SMWDataItem as DataItem;
use SMW\DIContainer;
use SMW\RequestOptions;
use SMW\Options;
use SMW\MediaWiki\DatabaseHelper;
use SMW\ApplicationFactory;
use SMW\SQLStore\RequestOptionsProc;
use RuntimeException;

/**
 * @license GNU GPL v2
 * @since 3.0
 *
 * @author mwjames
 */
class PropertySubjectsLookup {

	/**
	 * @var SQLStore
	 */
	private $store;

	/**
	 * @var IteratorFactory
	 */
	private $iteratorFactory;

	/**
	 * @var Options
	 */
	private $options;

	/**
	 * @var DataItemHandler
	 */
	private $dataItemHandler;

	/**
	 * @since 3.0
	 *
	 * @param SQLStore $store
	 */
	public function __construct( SQLStore $store ) {
		$this->store = $store;
		$this->iteratorFactory = ApplicationFactory::getInstance()->getIteratorFactory();
	}

	/**
	 * @see Store::getPropertySubjects
	 *
	 * @since 3.0
	 *
	 * {@inheritDoc}
	 */
	public function fetchFromTable( $pid, TableDefinition $proptable, DataItem $dataItem = null, RequestOptions $requestOptions = null ) {

		$connection = $this->store->getConnection( 'mw.db' );
		$group = false;

		$dataItemHandler = $this->store->getDataItemHandlerForDIType(
			$proptable->getDiType()
		);

		$sortField = $dataItemHandler->getSortField();
		$query = $connection->newQuery();
		$query->type( 'SELECT' );

		if ( $requestOptions === null ) {
			$requestOptions = new RequestOptions();
		} else{
			// Clone a `RequestOptions` instance so that it can be modified freely
			// for the current request without a possible interference on an
			// upcoming request (as in case where it is called from within a loop
			// with the same initial RequestOptions instance)
			$requestOptions = clone $requestOptions;
		}

		if ( $sortField === '' ) {
			$sortField = 'smw_sort';
		}

		$index = '';

		// For certain tables (blob) the query planner chooses a suboptimal plan
		// and causes an unacceptable query time therefore force an index for
		// those tables where the behaviour has been observed.
		if ( $dataItemHandler->getIndexHint( 'property.subjects' ) !== '' && $dataItem === null ) {

			// For tables with only a few entries, the index hint seems to create
			// a disadvantage, yet when the amount reaches a certain level the
			// index hint becomes necessary to retain an acceptable response
			// time.
			//
			// Table with < 100 entries
			//
			// SELECT smw_id, smw_title, smw_namespace, smw_iw, smw_subobject, smw_sortkey, smw_sort
			// FROM `smw_object_ids` INNER JOIN `smw_di_number` AS t1 ON t1.s_id=smw_id
			// WHERE (t1.p_id='196959') AND (smw_iw!=':smw') AND (smw_iw!=':smw-delete') AND (smw_iw!=':smw-redi')
			// GROUP BY smw_sort, smw_id LIMIT 21	8.2510ms (without index hint)
			//
			// SELECT smw_id, smw_title, smw_namespace, smw_iw, smw_subobject, smw_sortkey, smw_sort
			// FROM `smw_object_ids` INNER JOIN `smw_di_number` AS t1 FORCE INDEX(s_id) ON t1.s_id=smw_id
			// WHERE (t1.p_id='196959') AND (smw_iw!=':smw') AND (smw_iw!=':smw-delete') AND (smw_iw!=':smw-redi')
			// GROUP BY smw_sort, smw_id LIMIT 21	7548.6171ms (with index hint)
			//
			// vs.
			//
			// Table with > 5000 entries
			//
			// SELECT smw_id, smw_title, smw_namespace, smw_iw, smw_subobject, smw_sortkey, smw_sort
			// FROM `smw_object_ids` INNER JOIN `smw_di_blob` AS t1 FORCE INDEX(s_id) ON t1.s_id=smw_id
			// WHERE (t1.p_id='310170') AND (smw_iw!=':smw') AND (smw_iw!=':smw-delete') AND (smw_iw!=':smw-redi')
			// GROUP BY smw_sort, smw_id LIMIT 21	62.6249ms (with index hint)
			//
			// SELECT smw_id, smw_title, smw_namespace, smw_iw, smw_subobject, smw_sortkey, smw_sort
			// FROM `smw_object_ids` INNER JOIN `smw_di_blob` AS t1 ON t1.s_id=smw_id
			// WHERE (t1.p_id='310170') AND (smw_iw!=':smw') AND (smw_iw!=':smw-delete') AND (smw_iw!=':smw-redi')
			// GROUP BY smw_sort, smw_id LIMIT 21	8856.1242ms (without index hint)
			//
			$cq = $connection->newQuery();
			$cq->type( 'SELECT' );
			$cq->table( SQLStore::PROPERTY_STATISTICS_TABLE );
			$cq->field( 'usage_count' );
			$cq->condition( $cq->eq( 'p_id', $pid ) );
			$res = $cq->execute( __METHOD__ );

			foreach ( $res as $r ) {
				// 5000? It just showed to be a sweet spot while doing some
				// exploratory queries
				if ( $r->usage_count > 5000 ) {
					$index = 'FORCE INDEX(' . $dataItemHandler->getIndexHint( 'property.subjects' ) . ')';
				}
			}
		}

		$result = [];

		if ( $proptable->usesIdSubject() ) {
			$group = true;

			$query->table( SQLStore::ID_TABLE );

			$query->join(
				'INNER JOIN',
				[ $proptable->getName() => "t1 $index ON t1.s_id=smw_id" ]
			);

			$query->fields(
				[
					'smw_id',
					'smw_title',
					'smw_namespace',
					'smw_iw',
					'smw_subobject',
					'smw_sortkey',
					'smw_sort'
				]
			);

		} else { // no join needed, title+namespace as given in proptable
			$query->table( $proptable->getName(), "t1" );

			$query->fields(
				[
					's_title AS smw_title',
					's_namespace AS smw_namespace',
					'\'\' AS smw_iw',
					'\'\' AS smw_subobject',
					's_title AS smw_sortkey',
					's_title AS smw_sort'
				]
			);

			$requestOptions->setOption( 'ORDER BY', false );
		}

		if ( !$proptable->isFixedPropertyTable() ) {
			$query->condition( $query->eq( "t1.p_id", $pid ) );
		}

		$this->getWhereConds( $query, $dataItem );

		if ( $requestOptions !== null ) {
			foreach ( $requestOptions->getExtraConditions() as $extraCondition ) {
				if ( isset( $extraCondition['o_id'] ) ) {
					$query->condition( $query->eq( 't1.o_id', $extraCondition['o_id'] ) );
				}

				if ( is_callable( $extraCondition ) ) {
					$extraCondition( $query );
				}
			}
		}

		if ( $proptable->usesIdSubject() ) {
			foreach ( [ SMW_SQL3_SMWIW_OUTDATED, SMW_SQL3_SMWDELETEIW, SMW_SQL3_SMWREDIIW ] as $v ) {
				$query->condition( $query->neq( "smw_iw", $v ) );
			}
		}

		if ( $group && $connection->isType( 'postgres') ) {
			// Avoid a "... 42803 ERROR:  column "s....smw_title" must appear in
			// the GROUP BY clause or be used in an aggregate function ..."
			// https://stackoverflow.com/questions/1769361/postgresql-group-by-different-from-mysql
			$requestOptions->setOption( 'DISTINCT', 'ON (smw_sort, smw_id)' );
			$requestOptions->setOption( 'ORDER BY', false );
		} elseif ( $group ) {
			// Using GROUP BY will sort on the field and since we disinguish smw_sort
			// and the ID at the end of the field, we ensure
			// the filter duplicates while sorting the list without using DISTINCT which
			// would cause a filesort
			// http://www.mysqltutorial.org/mysql-distinct.aspx
			$requestOptions->setOption( 'GROUP BY', $sortField . ', smw_id' );
			$requestOptions->setOption( 'ORDER BY', false );
		} else {
			$requestOptions->setOption( 'DISTINCT', true );
		}

		$cond = $this->store->getSQLConditions(
			$requestOptions,
			'smw_sortkey',
			'smw_sortkey',
			false
		);

		$query->condition( $cond );

		$opts = $this->store->getSQLOptions(
			$requestOptions,
			$sortField
		);

		$query->options( $opts );

		$res = $connection->query(
			$query,
			__METHOD__
		);

		$this->dataItemHandler = $this->store->getDataItemHandlerForDIType(
			DataItem::TYPE_WIKIPAGE
		);

		// Return an iterator and avoid resolving the resources directly as it
		// may contain a large list of possible matches
		$res = $this->iteratorFactory->newMappingIterator(
			$this->iteratorFactory->newResultIterator( $res ),
			[ $this, 'newFromRow' ]
		);

		return $res;
	}

	/**
	 * @since 3.0
	 *
	 * @param stdClass $row
	 *
	 * @return DIWikiPage
	 */
	public function newFromRow( $row ) {

		try {
			if ( $row->smw_iw === '' || $row->smw_iw{0} != ':' ) { // filter special objects

				$keys = [
					$row->smw_title,
					$row->smw_namespace,
					$row->smw_iw,
					$row->smw_sort,
					$row->smw_subobject

				];

				$dataItem = $this->dataItemHandler->dataItemFromDBKeys( $keys );

				if ( isset( $row->smw_id ) ) {
					$dataItem->setId( $row->smw_id );
				}

				return $dataItem;
			}
		} catch ( DataItemHandlerException $e ) {
			// silently drop data, should be extremely rare and will usually fix itself at next edit
		}

		$title = ( $row->smw_title !== '' ? $row->smw_title : 'Empty' ) . '/' . $row->smw_namespace;

		// Avoid null return in Iterator
		return $this->dataItemHandler->dataItemFromDBKeys( [ 'Blankpage/' . $title, NS_SPECIAL, '', '', '' ] );
	}

	private function getWhereConds( $query, $dataItem ) {

		$conds = '';

		if ( $dataItem instanceof \SMWDIContainer ) {
			throw new RuntimeException( 'SMWDIContainer support is missing!');
		}

		if ( $dataItem !== null ) {
			$dataItemHandler = $this->store->getDataItemHandlerForDIType(
				$dataItem->getDIType()
			);

			foreach ( $dataItemHandler->getWhereConds( $dataItem ) as $fieldname => $value ) {
				$query->condition( $query->eq( "t1.$fieldname", $value ) );
			}
		}
	}

}