[MSI] Sync with Wine Staging 1.7.37. CORE-9246
[reactos.git] / reactos / dll / win32 / msi / table.c
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
3 *
4 * Copyright 2002-2005 Mike McCormack for CodeWeavers
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 */
20
21 #include "msipriv.h"
22
23 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
24
25 #define MSITABLE_HASH_TABLE_SIZE 37
26
27 typedef struct tagMSICOLUMNHASHENTRY
28 {
29 struct tagMSICOLUMNHASHENTRY *next;
30 UINT value;
31 UINT row;
32 } MSICOLUMNHASHENTRY;
33
34 typedef struct tagMSICOLUMNINFO
35 {
36 LPCWSTR tablename;
37 UINT number;
38 LPCWSTR colname;
39 UINT type;
40 UINT offset;
41 INT ref_count;
42 BOOL temporary;
43 MSICOLUMNHASHENTRY **hash_table;
44 } MSICOLUMNINFO;
45
46 struct tagMSITABLE
47 {
48 BYTE **data;
49 BOOL *data_persistent;
50 UINT row_count;
51 struct list entry;
52 MSICOLUMNINFO *colinfo;
53 UINT col_count;
54 MSICONDITION persistent;
55 INT ref_count;
56 WCHAR name[1];
57 };
58
59 /* information for default tables */
60 static const WCHAR szTables[] = {'_','T','a','b','l','e','s',0};
61 static const WCHAR szTable[] = {'T','a','b','l','e',0};
62 static const WCHAR szColumns[] = {'_','C','o','l','u','m','n','s',0};
63 static const WCHAR szNumber[] = {'N','u','m','b','e','r',0};
64 static const WCHAR szType[] = {'T','y','p','e',0};
65
66 static const MSICOLUMNINFO _Columns_cols[4] = {
67 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
68 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
69 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
70 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
71 };
72
73 static const MSICOLUMNINFO _Tables_cols[1] = {
74 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
75 };
76
77 #define MAX_STREAM_NAME 0x1f
78
79 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
80 {
81 if( MSITYPE_IS_BINARY(col->type) )
82 return 2;
83
84 if( col->type & MSITYPE_STRING )
85 return bytes_per_strref;
86
87 if( (col->type & 0xff) <= 2)
88 return 2;
89
90 if( (col->type & 0xff) != 4 )
91 ERR("Invalid column size %u\n", col->type & 0xff);
92
93 return 4;
94 }
95
96 static int utf2mime(int x)
97 {
98 if( (x>='0') && (x<='9') )
99 return x-'0';
100 if( (x>='A') && (x<='Z') )
101 return x-'A'+10;
102 if( (x>='a') && (x<='z') )
103 return x-'a'+10+26;
104 if( x=='.' )
105 return 10+26+26;
106 if( x=='_' )
107 return 10+26+26+1;
108 return -1;
109 }
110
111 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
112 {
113 DWORD count = MAX_STREAM_NAME;
114 DWORD ch, next;
115 LPWSTR out, p;
116
117 if( !bTable )
118 count = lstrlenW( in )+2;
119 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
120 p = out;
121
122 if( bTable )
123 {
124 *p++ = 0x4840;
125 count --;
126 }
127 while( count -- )
128 {
129 ch = *in++;
130 if( !ch )
131 {
132 *p = ch;
133 return out;
134 }
135 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
136 {
137 ch = utf2mime(ch) + 0x4800;
138 next = *in;
139 if( next && (next<0x80) )
140 {
141 next = utf2mime(next);
142 if( next != -1 )
143 {
144 next += 0x3ffffc0;
145 ch += (next<<6);
146 in++;
147 }
148 }
149 }
150 *p++ = ch;
151 }
152 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
153 msi_free( out );
154 return NULL;
155 }
156
157 static int mime2utf(int x)
158 {
159 if( x<10 )
160 return x + '0';
161 if( x<(10+26))
162 return x - 10 + 'A';
163 if( x<(10+26+26))
164 return x - 10 - 26 + 'a';
165 if( x == (10+26+26) )
166 return '.';
167 return '_';
168 }
169
170 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
171 {
172 WCHAR ch;
173 DWORD count = 0;
174
175 while ( (ch = *in++) )
176 {
177 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
178 {
179 if( ch >= 0x4800 )
180 ch = mime2utf(ch-0x4800);
181 else
182 {
183 ch -= 0x3800;
184 *out++ = mime2utf(ch&0x3f);
185 count++;
186 ch = mime2utf((ch>>6)&0x3f);
187 }
188 }
189 *out++ = ch;
190 count++;
191 }
192 *out = 0;
193 return count;
194 }
195
196 void enum_stream_names( IStorage *stg )
197 {
198 IEnumSTATSTG *stgenum = NULL;
199 HRESULT r;
200 STATSTG stat;
201 ULONG n, count;
202 WCHAR name[0x40];
203
204 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
205 if( FAILED( r ) )
206 return;
207
208 n = 0;
209 while( 1 )
210 {
211 count = 0;
212 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
213 if( FAILED( r ) || !count )
214 break;
215 decode_streamname( stat.pwcsName, name );
216 TRACE("stream %2d -> %s %s\n", n,
217 debugstr_w(stat.pwcsName), debugstr_w(name) );
218 CoTaskMemFree( stat.pwcsName );
219 n++;
220 }
221
222 IEnumSTATSTG_Release( stgenum );
223 }
224
225 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
226 BYTE **pdata, UINT *psz )
227 {
228 HRESULT r;
229 UINT ret = ERROR_FUNCTION_FAILED;
230 VOID *data;
231 ULONG sz, count;
232 IStream *stm = NULL;
233 STATSTG stat;
234 LPWSTR encname;
235
236 encname = encode_streamname(table, stname);
237
238 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
239
240 r = IStorage_OpenStream(stg, encname, NULL,
241 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
242 msi_free( encname );
243 if( FAILED( r ) )
244 {
245 WARN("open stream failed r = %08x - empty table?\n", r);
246 return ret;
247 }
248
249 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
250 if( FAILED( r ) )
251 {
252 WARN("open stream failed r = %08x!\n", r);
253 goto end;
254 }
255
256 if( stat.cbSize.QuadPart >> 32 )
257 {
258 WARN("Too big!\n");
259 goto end;
260 }
261
262 sz = stat.cbSize.QuadPart;
263 data = msi_alloc( sz );
264 if( !data )
265 {
266 WARN("couldn't allocate memory r=%08x!\n", r);
267 ret = ERROR_NOT_ENOUGH_MEMORY;
268 goto end;
269 }
270
271 r = IStream_Read(stm, data, sz, &count );
272 if( FAILED( r ) || ( count != sz ) )
273 {
274 msi_free( data );
275 WARN("read stream failed r = %08x!\n", r);
276 goto end;
277 }
278
279 *pdata = data;
280 *psz = sz;
281 ret = ERROR_SUCCESS;
282
283 end:
284 IStream_Release( stm );
285
286 return ret;
287 }
288
289 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
290 LPCVOID data, UINT sz, BOOL bTable )
291 {
292 HRESULT r;
293 UINT ret = ERROR_FUNCTION_FAILED;
294 ULONG count;
295 IStream *stm = NULL;
296 ULARGE_INTEGER size;
297 LARGE_INTEGER pos;
298 LPWSTR encname;
299
300 encname = encode_streamname(bTable, stname );
301 r = IStorage_OpenStream( stg, encname, NULL,
302 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
303 if( FAILED(r) )
304 {
305 r = IStorage_CreateStream( stg, encname,
306 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
307 }
308 msi_free( encname );
309 if( FAILED( r ) )
310 {
311 WARN("open stream failed r = %08x\n", r);
312 return ret;
313 }
314
315 size.QuadPart = sz;
316 r = IStream_SetSize( stm, size );
317 if( FAILED( r ) )
318 {
319 WARN("Failed to SetSize\n");
320 goto end;
321 }
322
323 pos.QuadPart = 0;
324 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
325 if( FAILED( r ) )
326 {
327 WARN("Failed to Seek\n");
328 goto end;
329 }
330
331 if (sz)
332 {
333 r = IStream_Write(stm, data, sz, &count );
334 if( FAILED( r ) || ( count != sz ) )
335 {
336 WARN("Failed to Write\n");
337 goto end;
338 }
339 }
340
341 ret = ERROR_SUCCESS;
342
343 end:
344 IStream_Release( stm );
345
346 return ret;
347 }
348
349 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
350 {
351 UINT i;
352 for (i = 0; i < count; i++) msi_free( colinfo[i].hash_table );
353 }
354
355 static void free_table( MSITABLE *table )
356 {
357 UINT i;
358 for( i=0; i<table->row_count; i++ )
359 msi_free( table->data[i] );
360 msi_free( table->data );
361 msi_free( table->data_persistent );
362 msi_free_colinfo( table->colinfo, table->col_count );
363 msi_free( table->colinfo );
364 msi_free( table );
365 }
366
367 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
368 {
369 const MSICOLUMNINFO *last_col;
370
371 if (!count)
372 return 0;
373
374 if (bytes_per_strref != LONG_STR_BYTES)
375 {
376 UINT i, size = 0;
377 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
378 return size;
379 }
380 last_col = &cols[count - 1];
381 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
382 }
383
384 /* add this table to the list of cached tables in the database */
385 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
386 {
387 BYTE *rawdata = NULL;
388 UINT rawsize = 0, i, j, row_size, row_size_mem;
389
390 TRACE("%s\n",debugstr_w(t->name));
391
392 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
393 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
394
395 /* if we can't read the table, just assume that it's empty */
396 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
397 if( !rawdata )
398 return ERROR_SUCCESS;
399
400 TRACE("Read %d bytes\n", rawsize );
401
402 if( rawsize % row_size )
403 {
404 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
405 goto err;
406 }
407
408 t->row_count = rawsize / row_size;
409 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
410 if( !t->data )
411 goto err;
412 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
413 if ( !t->data_persistent )
414 goto err;
415
416 /* transpose all the data */
417 TRACE("Transposing data from %d rows\n", t->row_count );
418 for (i = 0; i < t->row_count; i++)
419 {
420 UINT ofs = 0, ofs_mem = 0;
421
422 t->data[i] = msi_alloc( row_size_mem );
423 if( !t->data[i] )
424 goto err;
425 t->data_persistent[i] = TRUE;
426
427 for (j = 0; j < t->col_count; j++)
428 {
429 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
430 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
431 UINT k;
432
433 if ( n != 2 && n != 3 && n != 4 )
434 {
435 ERR("oops - unknown column width %d\n", n);
436 goto err;
437 }
438 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
439 {
440 for (k = 0; k < m; k++)
441 {
442 if (k < n)
443 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
444 else
445 t->data[i][ofs_mem + k] = 0;
446 }
447 }
448 else
449 {
450 for (k = 0; k < n; k++)
451 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
452 }
453 ofs_mem += m;
454 ofs += n;
455 }
456 }
457
458 msi_free( rawdata );
459 return ERROR_SUCCESS;
460 err:
461 msi_free( rawdata );
462 return ERROR_FUNCTION_FAILED;
463 }
464
465 void free_cached_tables( MSIDATABASE *db )
466 {
467 while( !list_empty( &db->tables ) )
468 {
469 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
470
471 list_remove( &t->entry );
472 free_table( t );
473 }
474 }
475
476 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
477 {
478 MSITABLE *t;
479
480 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
481 if( !strcmpW( name, t->name ) )
482 return t;
483
484 return NULL;
485 }
486
487 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
488 {
489 DWORD i;
490
491 for (i = 0; colinfo && i < count; i++)
492 {
493 assert( i + 1 == colinfo[i].number );
494 if (i) colinfo[i].offset = colinfo[i - 1].offset +
495 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
496 else colinfo[i].offset = 0;
497
498 TRACE("column %d is [%s] with type %08x ofs %d\n",
499 colinfo[i].number, debugstr_w(colinfo[i].colname),
500 colinfo[i].type, colinfo[i].offset);
501 }
502 }
503
504 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
505 {
506 const MSICOLUMNINFO *p;
507 DWORD i, n;
508
509 TRACE("%s\n", debugstr_w(name));
510
511 if (!strcmpW( name, szTables ))
512 {
513 p = _Tables_cols;
514 n = 1;
515 }
516 else if (!strcmpW( name, szColumns ))
517 {
518 p = _Columns_cols;
519 n = 4;
520 }
521 else return ERROR_FUNCTION_FAILED;
522
523 for (i = 0; i < n; i++)
524 {
525 if (colinfo && i < *sz) colinfo[i] = p[i];
526 if (colinfo && i >= *sz) break;
527 }
528 table_calc_column_offsets( db, colinfo, n );
529 *sz = n;
530 return ERROR_SUCCESS;
531 }
532
533 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
534
535 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
536 {
537 UINT r, column_count = 0;
538 MSICOLUMNINFO *columns;
539
540 /* get the number of columns in this table */
541 column_count = 0;
542 r = get_tablecolumns( db, name, NULL, &column_count );
543 if (r != ERROR_SUCCESS)
544 return r;
545
546 *pcount = column_count;
547
548 /* if there are no columns, there's no table */
549 if (!column_count)
550 return ERROR_INVALID_PARAMETER;
551
552 TRACE("table %s found\n", debugstr_w(name));
553
554 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
555 if (!columns)
556 return ERROR_FUNCTION_FAILED;
557
558 r = get_tablecolumns( db, name, columns, &column_count );
559 if (r != ERROR_SUCCESS)
560 {
561 msi_free( columns );
562 return ERROR_FUNCTION_FAILED;
563 }
564 *pcols = columns;
565 return r;
566 }
567
568 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
569 {
570 MSITABLE *table;
571 UINT r;
572
573 /* first, see if the table is cached */
574 table = find_cached_table( db, name );
575 if (table)
576 {
577 *table_ret = table;
578 return ERROR_SUCCESS;
579 }
580
581 /* nonexistent tables should be interpreted as empty tables */
582 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
583 if (!table)
584 return ERROR_FUNCTION_FAILED;
585
586 table->row_count = 0;
587 table->data = NULL;
588 table->data_persistent = NULL;
589 table->colinfo = NULL;
590 table->col_count = 0;
591 table->persistent = MSICONDITION_TRUE;
592 lstrcpyW( table->name, name );
593
594 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
595 table->persistent = MSICONDITION_NONE;
596
597 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
598 if (r != ERROR_SUCCESS)
599 {
600 free_table( table );
601 return r;
602 }
603 r = read_table_from_storage( db, table, db->storage );
604 if (r != ERROR_SUCCESS)
605 {
606 free_table( table );
607 return r;
608 }
609 list_add_head( &db->tables, &table->entry );
610 *table_ret = table;
611 return ERROR_SUCCESS;
612 }
613
614 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
615 {
616 UINT ret = 0, i;
617
618 for (i = 0; i < bytes; i++)
619 ret += data[row][col + i] << i * 8;
620
621 return ret;
622 }
623
624 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
625 {
626 UINT r, i, n = 0, table_id, count, maxcount = *sz;
627 MSITABLE *table = NULL;
628
629 TRACE("%s\n", debugstr_w(szTableName));
630
631 /* first check if there is a default table with that name */
632 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
633 if (r == ERROR_SUCCESS && *sz)
634 return r;
635
636 r = get_table( db, szColumns, &table );
637 if (r != ERROR_SUCCESS)
638 {
639 ERR("couldn't load _Columns table\n");
640 return ERROR_FUNCTION_FAILED;
641 }
642
643 /* convert table and column names to IDs from the string table */
644 r = msi_string2id( db->strings, szTableName, -1, &table_id );
645 if (r != ERROR_SUCCESS)
646 {
647 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
648 return r;
649 }
650 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
651
652 /* Note: _Columns table doesn't have non-persistent data */
653
654 /* if maxcount is non-zero, assume it's exactly right for this table */
655 if (colinfo) memset( colinfo, 0, maxcount * sizeof(*colinfo) );
656 count = table->row_count;
657 for (i = 0; i < count; i++)
658 {
659 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
660 if (colinfo)
661 {
662 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
663 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
664
665 /* check the column number is in range */
666 if (col < 1 || col > maxcount)
667 {
668 ERR("column %d out of range (maxcount: %d)\n", col, maxcount);
669 continue;
670 }
671 /* check if this column was already set */
672 if (colinfo[col - 1].number)
673 {
674 ERR("duplicate column %d\n", col);
675 continue;
676 }
677 colinfo[col - 1].tablename = msi_string_lookup( db->strings, table_id, NULL );
678 colinfo[col - 1].number = col;
679 colinfo[col - 1].colname = msi_string_lookup( db->strings, id, NULL );
680 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
681 sizeof(USHORT) ) - (1 << 15);
682 colinfo[col - 1].offset = 0;
683 colinfo[col - 1].ref_count = 0;
684 colinfo[col - 1].hash_table = NULL;
685 }
686 n++;
687 }
688 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
689
690 if (colinfo && n != maxcount)
691 {
692 ERR("missing column in table %s\n", debugstr_w(szTableName));
693 msi_free_colinfo( colinfo, maxcount );
694 return ERROR_FUNCTION_FAILED;
695 }
696 table_calc_column_offsets( db, colinfo, n );
697 *sz = n;
698 return ERROR_SUCCESS;
699 }
700
701 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
702 MSICONDITION persistent )
703 {
704 enum StringPersistence string_persistence = (persistent) ? StringPersistent : StringNonPersistent;
705 UINT r, nField;
706 MSIVIEW *tv = NULL;
707 MSIRECORD *rec = NULL;
708 column_info *col;
709 MSITABLE *table;
710 UINT i;
711
712 /* only add tables that don't exist already */
713 if( TABLE_Exists(db, name ) )
714 {
715 WARN("table %s exists\n", debugstr_w(name));
716 return ERROR_BAD_QUERY_SYNTAX;
717 }
718
719 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
720 if( !table )
721 return ERROR_FUNCTION_FAILED;
722
723 table->ref_count = 1;
724 table->row_count = 0;
725 table->data = NULL;
726 table->data_persistent = NULL;
727 table->colinfo = NULL;
728 table->col_count = 0;
729 table->persistent = persistent;
730 lstrcpyW( table->name, name );
731
732 for( col = col_info; col; col = col->next )
733 table->col_count++;
734
735 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
736 if (!table->colinfo)
737 {
738 free_table( table );
739 return ERROR_FUNCTION_FAILED;
740 }
741
742 for( i = 0, col = col_info; col; i++, col = col->next )
743 {
744 UINT table_id = msi_add_string( db->strings, col->table, -1, string_persistence );
745 UINT col_id = msi_add_string( db->strings, col->column, -1, string_persistence );
746
747 table->colinfo[ i ].tablename = msi_string_lookup( db->strings, table_id, NULL );
748 table->colinfo[ i ].number = i + 1;
749 table->colinfo[ i ].colname = msi_string_lookup( db->strings, col_id, NULL );
750 table->colinfo[ i ].type = col->type;
751 table->colinfo[ i ].offset = 0;
752 table->colinfo[ i ].ref_count = 0;
753 table->colinfo[ i ].hash_table = NULL;
754 table->colinfo[ i ].temporary = col->temporary;
755 }
756 table_calc_column_offsets( db, table->colinfo, table->col_count);
757
758 r = TABLE_CreateView( db, szTables, &tv );
759 TRACE("CreateView returned %x\n", r);
760 if( r )
761 {
762 free_table( table );
763 return r;
764 }
765
766 r = tv->ops->execute( tv, 0 );
767 TRACE("tv execute returned %x\n", r);
768 if( r )
769 goto err;
770
771 rec = MSI_CreateRecord( 1 );
772 if( !rec )
773 goto err;
774
775 r = MSI_RecordSetStringW( rec, 1, name );
776 if( r )
777 goto err;
778
779 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
780 TRACE("insert_row returned %x\n", r);
781 if( r )
782 goto err;
783
784 tv->ops->delete( tv );
785 tv = NULL;
786
787 msiobj_release( &rec->hdr );
788 rec = NULL;
789
790 if( persistent != MSICONDITION_FALSE )
791 {
792 /* add each column to the _Columns table */
793 r = TABLE_CreateView( db, szColumns, &tv );
794 if( r )
795 return r;
796
797 r = tv->ops->execute( tv, 0 );
798 TRACE("tv execute returned %x\n", r);
799 if( r )
800 goto err;
801
802 rec = MSI_CreateRecord( 4 );
803 if( !rec )
804 goto err;
805
806 r = MSI_RecordSetStringW( rec, 1, name );
807 if( r )
808 goto err;
809
810 /*
811 * need to set the table, column number, col name and type
812 * for each column we enter in the table
813 */
814 nField = 1;
815 for( col = col_info; col; col = col->next )
816 {
817 r = MSI_RecordSetInteger( rec, 2, nField );
818 if( r )
819 goto err;
820
821 r = MSI_RecordSetStringW( rec, 3, col->column );
822 if( r )
823 goto err;
824
825 r = MSI_RecordSetInteger( rec, 4, col->type );
826 if( r )
827 goto err;
828
829 r = tv->ops->insert_row( tv, rec, -1, FALSE );
830 if( r )
831 goto err;
832
833 nField++;
834 }
835 if( !col )
836 r = ERROR_SUCCESS;
837 }
838
839 err:
840 if (rec)
841 msiobj_release( &rec->hdr );
842 /* FIXME: remove values from the string table on error */
843 if( tv )
844 tv->ops->delete( tv );
845
846 if (r == ERROR_SUCCESS)
847 list_add_head( &db->tables, &table->entry );
848 else
849 free_table( table );
850
851 return r;
852 }
853
854 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
855 {
856 BYTE *rawdata = NULL;
857 UINT rawsize, i, j, row_size, row_count;
858 UINT r = ERROR_FUNCTION_FAILED;
859
860 /* Nothing to do for non-persistent tables */
861 if( t->persistent == MSICONDITION_FALSE )
862 return ERROR_SUCCESS;
863
864 TRACE("Saving %s\n", debugstr_w( t->name ) );
865
866 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
867 row_count = t->row_count;
868 for (i = 0; i < t->row_count; i++)
869 {
870 if (!t->data_persistent[i])
871 {
872 row_count = 1; /* yes, this is bizarre */
873 break;
874 }
875 }
876 rawsize = row_count * row_size;
877 rawdata = msi_alloc_zero( rawsize );
878 if( !rawdata )
879 {
880 r = ERROR_NOT_ENOUGH_MEMORY;
881 goto err;
882 }
883
884 rawsize = 0;
885 for (i = 0; i < t->row_count; i++)
886 {
887 UINT ofs = 0, ofs_mem = 0;
888
889 if (!t->data_persistent[i]) break;
890
891 for (j = 0; j < t->col_count; j++)
892 {
893 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
894 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
895 UINT k;
896
897 if (n != 2 && n != 3 && n != 4)
898 {
899 ERR("oops - unknown column width %d\n", n);
900 goto err;
901 }
902 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
903 {
904 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
905 if (id > 1 << bytes_per_strref * 8)
906 {
907 ERR("string id %u out of range\n", id);
908 goto err;
909 }
910 }
911 for (k = 0; k < n; k++)
912 {
913 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
914 }
915 ofs_mem += m;
916 ofs += n;
917 }
918 rawsize += row_size;
919 }
920
921 TRACE("writing %d bytes\n", rawsize);
922 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
923
924 err:
925 msi_free( rawdata );
926 return r;
927 }
928
929 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
930 {
931 MSITABLE *table;
932 UINT size, offset, old_count;
933 UINT n;
934
935 if (!(table = find_cached_table( db, name ))) return;
936 old_count = table->col_count;
937 msi_free_colinfo( table->colinfo, table->col_count );
938 msi_free( table->colinfo );
939 table->colinfo = NULL;
940
941 table_get_column_info( db, name, &table->colinfo, &table->col_count );
942 if (!table->col_count) return;
943
944 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
945 offset = table->colinfo[table->col_count - 1].offset;
946
947 for ( n = 0; n < table->row_count; n++ )
948 {
949 table->data[n] = msi_realloc( table->data[n], size );
950 if (old_count < table->col_count)
951 memset( &table->data[n][offset], 0, size - offset );
952 }
953 }
954
955 /* try to find the table name in the _Tables table */
956 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
957 {
958 UINT r, table_id, i;
959 MSITABLE *table;
960
961 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
962 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
963 return TRUE;
964
965 r = msi_string2id( db->strings, name, -1, &table_id );
966 if( r != ERROR_SUCCESS )
967 {
968 TRACE("Couldn't find id for %s\n", debugstr_w(name));
969 return FALSE;
970 }
971
972 r = get_table( db, szTables, &table );
973 if( r != ERROR_SUCCESS )
974 {
975 ERR("table %s not available\n", debugstr_w(szTables));
976 return FALSE;
977 }
978
979 for( i = 0; i < table->row_count; i++ )
980 {
981 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
982 return TRUE;
983 }
984
985 return FALSE;
986 }
987
988 /* below is the query interface to a table */
989
990 typedef struct tagMSITABLEVIEW
991 {
992 MSIVIEW view;
993 MSIDATABASE *db;
994 MSITABLE *table;
995 MSICOLUMNINFO *columns;
996 UINT num_cols;
997 UINT row_size;
998 WCHAR name[1];
999 } MSITABLEVIEW;
1000
1001 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1002 {
1003 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1004 UINT offset, n;
1005
1006 if( !tv->table )
1007 return ERROR_INVALID_PARAMETER;
1008
1009 if( (col==0) || (col>tv->num_cols) )
1010 return ERROR_INVALID_PARAMETER;
1011
1012 /* how many rows are there ? */
1013 if( row >= tv->table->row_count )
1014 return ERROR_NO_MORE_ITEMS;
1015
1016 if( tv->columns[col-1].offset >= tv->row_size )
1017 {
1018 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1019 ERR("%p %p\n", tv, tv->columns );
1020 return ERROR_FUNCTION_FAILED;
1021 }
1022
1023 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1024 if (n != 2 && n != 3 && n != 4)
1025 {
1026 ERR("oops! what is %d bytes per column?\n", n );
1027 return ERROR_FUNCTION_FAILED;
1028 }
1029
1030 offset = tv->columns[col-1].offset;
1031 *val = read_table_int(tv->table->data, row, offset, n);
1032
1033 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1034
1035 return ERROR_SUCCESS;
1036 }
1037
1038 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1039 {
1040 LPWSTR p, stname = NULL;
1041 UINT i, r, type, ival;
1042 DWORD len;
1043 LPCWSTR sval;
1044 MSIVIEW *view = (MSIVIEW *) tv;
1045
1046 TRACE("%p %d\n", tv, row);
1047
1048 len = lstrlenW( tv->name ) + 1;
1049 stname = msi_alloc( len*sizeof(WCHAR) );
1050 if ( !stname )
1051 {
1052 r = ERROR_OUTOFMEMORY;
1053 goto err;
1054 }
1055
1056 lstrcpyW( stname, tv->name );
1057
1058 for ( i = 0; i < tv->num_cols; i++ )
1059 {
1060 type = tv->columns[i].type;
1061 if ( type & MSITYPE_KEY )
1062 {
1063 WCHAR number[0x20];
1064
1065 r = TABLE_fetch_int( view, row, i+1, &ival );
1066 if ( r != ERROR_SUCCESS )
1067 goto err;
1068
1069 if ( tv->columns[i].type & MSITYPE_STRING )
1070 {
1071 sval = msi_string_lookup( tv->db->strings, ival, NULL );
1072 if ( !sval )
1073 {
1074 r = ERROR_INVALID_PARAMETER;
1075 goto err;
1076 }
1077 }
1078 else
1079 {
1080 static const WCHAR fmt[] = { '%','d',0 };
1081 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1082
1083 switch( n )
1084 {
1085 case 2:
1086 sprintfW( number, fmt, ival-0x8000 );
1087 break;
1088 case 4:
1089 sprintfW( number, fmt, ival^0x80000000 );
1090 break;
1091 default:
1092 ERR( "oops - unknown column width %d\n", n );
1093 r = ERROR_FUNCTION_FAILED;
1094 goto err;
1095 }
1096 sval = number;
1097 }
1098
1099 len += lstrlenW( szDot ) + lstrlenW( sval );
1100 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1101 if ( !p )
1102 {
1103 r = ERROR_OUTOFMEMORY;
1104 goto err;
1105 }
1106 stname = p;
1107
1108 lstrcatW( stname, szDot );
1109 lstrcatW( stname, sval );
1110 }
1111 else
1112 continue;
1113 }
1114
1115 *pstname = stname;
1116 return ERROR_SUCCESS;
1117
1118 err:
1119 msi_free( stname );
1120 *pstname = NULL;
1121 return r;
1122 }
1123
1124 /*
1125 * We need a special case for streams, as we need to reference column with
1126 * the name of the stream in the same table, and the table name
1127 * which may not be available at higher levels of the query
1128 */
1129 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1130 {
1131 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1132 UINT r;
1133 WCHAR *name;
1134
1135 if( !view->ops->fetch_int )
1136 return ERROR_INVALID_PARAMETER;
1137
1138 r = msi_stream_name( tv, row, &name );
1139 if (r != ERROR_SUCCESS)
1140 {
1141 ERR("fetching stream, error = %u\n", r);
1142 return r;
1143 }
1144
1145 r = msi_get_stream( tv->db, name, stm );
1146 if (r != ERROR_SUCCESS)
1147 ERR("fetching stream %s, error = %u\n", debugstr_w(name), r);
1148
1149 msi_free( name );
1150 return r;
1151 }
1152
1153 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1154 {
1155 UINT offset, n, i;
1156
1157 if( !tv->table )
1158 return ERROR_INVALID_PARAMETER;
1159
1160 if( (col==0) || (col>tv->num_cols) )
1161 return ERROR_INVALID_PARAMETER;
1162
1163 if( row >= tv->table->row_count )
1164 return ERROR_INVALID_PARAMETER;
1165
1166 if( tv->columns[col-1].offset >= tv->row_size )
1167 {
1168 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1169 ERR("%p %p\n", tv, tv->columns );
1170 return ERROR_FUNCTION_FAILED;
1171 }
1172
1173 msi_free( tv->columns[col-1].hash_table );
1174 tv->columns[col-1].hash_table = NULL;
1175
1176 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1177 if ( n != 2 && n != 3 && n != 4 )
1178 {
1179 ERR("oops! what is %d bytes per column?\n", n );
1180 return ERROR_FUNCTION_FAILED;
1181 }
1182
1183 offset = tv->columns[col-1].offset;
1184 for ( i = 0; i < n; i++ )
1185 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1186
1187 return ERROR_SUCCESS;
1188 }
1189
1190 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1191 {
1192 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1193
1194 if (!tv->table)
1195 return ERROR_INVALID_PARAMETER;
1196
1197 return msi_view_get_row(tv->db, view, row, rec);
1198 }
1199
1200 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1201 {
1202 static const WCHAR insert[] = {
1203 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1204 '`','_','S','t','r','e','a','m','s','`',' ',
1205 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1206 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1207 MSIQUERY *query = NULL;
1208 MSIRECORD *rec;
1209 UINT r;
1210
1211 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1212
1213 rec = MSI_CreateRecord( 2 );
1214 if ( !rec )
1215 return ERROR_OUTOFMEMORY;
1216
1217 r = MSI_RecordSetStringW( rec, 1, name );
1218 if ( r != ERROR_SUCCESS )
1219 goto err;
1220
1221 r = MSI_RecordSetIStream( rec, 2, data );
1222 if ( r != ERROR_SUCCESS )
1223 goto err;
1224
1225 r = MSI_DatabaseOpenViewW( db, insert, &query );
1226 if ( r != ERROR_SUCCESS )
1227 goto err;
1228
1229 r = MSI_ViewExecute( query, rec );
1230
1231 err:
1232 msiobj_release( &query->hdr );
1233 msiobj_release( &rec->hdr );
1234 return r;
1235 }
1236
1237 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1238 {
1239 MSICOLUMNINFO columninfo;
1240 UINT r;
1241 int ival;
1242
1243 if ( (iField <= 0) ||
1244 (iField > tv->num_cols) ||
1245 MSI_RecordIsNull( rec, iField ) )
1246 return ERROR_FUNCTION_FAILED;
1247
1248 columninfo = tv->columns[ iField - 1 ];
1249
1250 if ( MSITYPE_IS_BINARY(columninfo.type) )
1251 {
1252 *pvalue = 1; /* refers to the first key column */
1253 }
1254 else if ( columninfo.type & MSITYPE_STRING )
1255 {
1256 int len;
1257 const WCHAR *sval = msi_record_get_string( rec, iField, &len );
1258 if (sval)
1259 {
1260 r = msi_string2id( tv->db->strings, sval, len, pvalue );
1261 if (r != ERROR_SUCCESS)
1262 return ERROR_NOT_FOUND;
1263 }
1264 else *pvalue = 0;
1265 }
1266 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1267 {
1268 ival = MSI_RecordGetInteger( rec, iField );
1269 if (ival == 0x80000000) *pvalue = 0x8000;
1270 else
1271 {
1272 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1273 if (*pvalue & 0xffff0000)
1274 {
1275 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1276 return ERROR_FUNCTION_FAILED;
1277 }
1278 }
1279 }
1280 else
1281 {
1282 ival = MSI_RecordGetInteger( rec, iField );
1283 *pvalue = ival ^ 0x80000000;
1284 }
1285
1286 return ERROR_SUCCESS;
1287 }
1288
1289 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1290 {
1291 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1292 UINT i, val, r = ERROR_SUCCESS;
1293
1294 if ( !tv->table )
1295 return ERROR_INVALID_PARAMETER;
1296
1297 /* test if any of the mask bits are invalid */
1298 if ( mask >= (1<<tv->num_cols) )
1299 return ERROR_INVALID_PARAMETER;
1300
1301 for ( i = 0; i < tv->num_cols; i++ )
1302 {
1303 BOOL persistent;
1304
1305 /* only update the fields specified in the mask */
1306 if ( !(mask&(1<<i)) )
1307 continue;
1308
1309 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1310 (tv->table->data_persistent[row]);
1311 /* FIXME: should we allow updating keys? */
1312
1313 val = 0;
1314 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1315 {
1316 r = get_table_value_from_record (tv, rec, i + 1, &val);
1317 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1318 {
1319 IStream *stm;
1320 LPWSTR stname;
1321
1322 if ( r != ERROR_SUCCESS )
1323 return ERROR_FUNCTION_FAILED;
1324
1325 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1326 if ( r != ERROR_SUCCESS )
1327 return r;
1328
1329 r = msi_stream_name( tv, row, &stname );
1330 if ( r != ERROR_SUCCESS )
1331 {
1332 IStream_Release( stm );
1333 return r;
1334 }
1335
1336 r = msi_addstreamW( tv->db, stname, stm );
1337 IStream_Release( stm );
1338 msi_free ( stname );
1339
1340 if ( r != ERROR_SUCCESS )
1341 return r;
1342 }
1343 else if ( tv->columns[i].type & MSITYPE_STRING )
1344 {
1345 UINT x;
1346
1347 if ( r != ERROR_SUCCESS )
1348 {
1349 int len;
1350 const WCHAR *sval = msi_record_get_string( rec, i + 1, &len );
1351 val = msi_add_string( tv->db->strings, sval, len,
1352 persistent ? StringPersistent : StringNonPersistent );
1353 }
1354 else
1355 {
1356 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1357 if (val == x)
1358 continue;
1359 }
1360 }
1361 else
1362 {
1363 if ( r != ERROR_SUCCESS )
1364 return ERROR_FUNCTION_FAILED;
1365 }
1366 }
1367
1368 r = TABLE_set_int( tv, row, i+1, val );
1369 if ( r != ERROR_SUCCESS )
1370 break;
1371 }
1372 return r;
1373 }
1374
1375 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1376 {
1377 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1378 BYTE **p, *row;
1379 BOOL *b;
1380 UINT sz;
1381 BYTE ***data_ptr;
1382 BOOL **data_persist_ptr;
1383 UINT *row_count;
1384
1385 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1386
1387 if( !tv->table )
1388 return ERROR_INVALID_PARAMETER;
1389
1390 row = msi_alloc_zero( tv->row_size );
1391 if( !row )
1392 return ERROR_NOT_ENOUGH_MEMORY;
1393
1394 row_count = &tv->table->row_count;
1395 data_ptr = &tv->table->data;
1396 data_persist_ptr = &tv->table->data_persistent;
1397 if (*num == -1)
1398 *num = tv->table->row_count;
1399
1400 sz = (*row_count + 1) * sizeof (BYTE*);
1401 if( *data_ptr )
1402 p = msi_realloc( *data_ptr, sz );
1403 else
1404 p = msi_alloc( sz );
1405 if( !p )
1406 {
1407 msi_free( row );
1408 return ERROR_NOT_ENOUGH_MEMORY;
1409 }
1410
1411 sz = (*row_count + 1) * sizeof (BOOL);
1412 if( *data_persist_ptr )
1413 b = msi_realloc( *data_persist_ptr, sz );
1414 else
1415 b = msi_alloc( sz );
1416 if( !b )
1417 {
1418 msi_free( row );
1419 msi_free( p );
1420 return ERROR_NOT_ENOUGH_MEMORY;
1421 }
1422
1423 *data_ptr = p;
1424 (*data_ptr)[*row_count] = row;
1425
1426 *data_persist_ptr = b;
1427 (*data_persist_ptr)[*row_count] = !temporary;
1428
1429 (*row_count)++;
1430
1431 return ERROR_SUCCESS;
1432 }
1433
1434 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1435 {
1436 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1437
1438 TRACE("%p %p\n", tv, record);
1439
1440 TRACE("There are %d columns\n", tv->num_cols );
1441
1442 return ERROR_SUCCESS;
1443 }
1444
1445 static UINT TABLE_close( struct tagMSIVIEW *view )
1446 {
1447 TRACE("%p\n", view );
1448
1449 return ERROR_SUCCESS;
1450 }
1451
1452 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1453 {
1454 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1455
1456 TRACE("%p %p %p\n", view, rows, cols );
1457
1458 if( cols )
1459 *cols = tv->num_cols;
1460 if( rows )
1461 {
1462 if( !tv->table )
1463 return ERROR_INVALID_PARAMETER;
1464 *rows = tv->table->row_count;
1465 }
1466
1467 return ERROR_SUCCESS;
1468 }
1469
1470 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1471 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1472 LPCWSTR *table_name )
1473 {
1474 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1475
1476 TRACE("%p %d %p %p\n", tv, n, name, type );
1477
1478 if( ( n == 0 ) || ( n > tv->num_cols ) )
1479 return ERROR_INVALID_PARAMETER;
1480
1481 if( name )
1482 {
1483 *name = tv->columns[n-1].colname;
1484 if( !*name )
1485 return ERROR_FUNCTION_FAILED;
1486 }
1487
1488 if( table_name )
1489 {
1490 *table_name = tv->columns[n-1].tablename;
1491 if( !*table_name )
1492 return ERROR_FUNCTION_FAILED;
1493 }
1494
1495 if( type )
1496 *type = tv->columns[n-1].type;
1497
1498 if( temporary )
1499 *temporary = tv->columns[n-1].temporary;
1500
1501 return ERROR_SUCCESS;
1502 }
1503
1504 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1505
1506 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1507 {
1508 UINT r, row, i;
1509
1510 /* check there are no null values where they're not allowed */
1511 for( i = 0; i < tv->num_cols; i++ )
1512 {
1513 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1514 continue;
1515
1516 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1517 TRACE("skipping binary column\n");
1518 else if ( tv->columns[i].type & MSITYPE_STRING )
1519 {
1520 int len;
1521 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
1522
1523 if (!str || (!str[0] && !len))
1524 {
1525 if (column) *column = i;
1526 return ERROR_INVALID_DATA;
1527 }
1528 }
1529 else
1530 {
1531 UINT n;
1532
1533 n = MSI_RecordGetInteger( rec, i+1 );
1534 if (n == MSI_NULL_INTEGER)
1535 {
1536 if (column) *column = i;
1537 return ERROR_INVALID_DATA;
1538 }
1539 }
1540 }
1541
1542 /* check there are no duplicate keys */
1543 r = msi_table_find_row( tv, rec, &row, column );
1544 if (r == ERROR_SUCCESS)
1545 return ERROR_FUNCTION_FAILED;
1546
1547 return ERROR_SUCCESS;
1548 }
1549
1550 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1551 {
1552 UINT r, i, ivalue, x;
1553
1554 for (i = 0; i < tv->num_cols; i++ )
1555 {
1556 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1557
1558 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1559 if (r != ERROR_SUCCESS)
1560 return 1;
1561
1562 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1563 if (r != ERROR_SUCCESS)
1564 {
1565 WARN("TABLE_fetch_int should not fail here %u\n", r);
1566 return -1;
1567 }
1568 if (ivalue > x)
1569 {
1570 return 1;
1571 }
1572 else if (ivalue == x)
1573 {
1574 if (i < tv->num_cols - 1) continue;
1575 return 0;
1576 }
1577 else
1578 return -1;
1579 }
1580 return 1;
1581 }
1582
1583 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1584 {
1585 int idx, c, low = 0, high = tv->table->row_count - 1;
1586
1587 TRACE("%p %p\n", tv, rec);
1588
1589 while (low <= high)
1590 {
1591 idx = (low + high) / 2;
1592 c = compare_record( tv, idx, rec );
1593
1594 if (c < 0)
1595 high = idx - 1;
1596 else if (c > 0)
1597 low = idx + 1;
1598 else
1599 {
1600 TRACE("found %u\n", idx);
1601 return idx;
1602 }
1603 }
1604 TRACE("found %u\n", high + 1);
1605 return high + 1;
1606 }
1607
1608 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1609 {
1610 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1611 UINT i, r;
1612
1613 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1614
1615 /* check that the key is unique - can we find a matching row? */
1616 r = table_validate_new( tv, rec, NULL );
1617 if( r != ERROR_SUCCESS )
1618 return ERROR_FUNCTION_FAILED;
1619
1620 if (row == -1)
1621 row = find_insert_index( tv, rec );
1622
1623 r = table_create_new_row( view, &row, temporary );
1624 TRACE("insert_row returned %08x\n", r);
1625 if( r != ERROR_SUCCESS )
1626 return r;
1627
1628 /* shift the rows to make room for the new row */
1629 for (i = tv->table->row_count - 1; i > row; i--)
1630 {
1631 memmove(&(tv->table->data[i][0]),
1632 &(tv->table->data[i - 1][0]), tv->row_size);
1633 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1634 }
1635
1636 /* Re-set the persistence flag */
1637 tv->table->data_persistent[row] = !temporary;
1638 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1639 }
1640
1641 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1642 {
1643 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1644 UINT r, num_rows, num_cols, i;
1645
1646 TRACE("%p %d\n", tv, row);
1647
1648 if ( !tv->table )
1649 return ERROR_INVALID_PARAMETER;
1650
1651 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1652 if ( r != ERROR_SUCCESS )
1653 return r;
1654
1655 if ( row >= num_rows )
1656 return ERROR_FUNCTION_FAILED;
1657
1658 num_rows = tv->table->row_count;
1659 tv->table->row_count--;
1660
1661 /* reset the hash tables */
1662 for (i = 0; i < tv->num_cols; i++)
1663 {
1664 msi_free( tv->columns[i].hash_table );
1665 tv->columns[i].hash_table = NULL;
1666 }
1667
1668 for (i = row + 1; i < num_rows; i++)
1669 {
1670 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1671 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1672 }
1673
1674 msi_free(tv->table->data[num_rows - 1]);
1675
1676 return ERROR_SUCCESS;
1677 }
1678
1679 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1680 {
1681 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1682 UINT r, new_row;
1683
1684 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1685 * sets the fetched record apart from other records
1686 */
1687
1688 if (!tv->table)
1689 return ERROR_INVALID_PARAMETER;
1690
1691 r = msi_table_find_row(tv, rec, &new_row, NULL);
1692 if (r != ERROR_SUCCESS)
1693 {
1694 ERR("can't find row to modify\n");
1695 return ERROR_FUNCTION_FAILED;
1696 }
1697
1698 /* the row cannot be changed */
1699 if (row != new_row + 1)
1700 return ERROR_FUNCTION_FAILED;
1701
1702 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1703 }
1704
1705 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1706 {
1707 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1708 UINT r, row;
1709
1710 if (!tv->table)
1711 return ERROR_INVALID_PARAMETER;
1712
1713 r = msi_table_find_row(tv, rec, &row, NULL);
1714 if (r == ERROR_SUCCESS)
1715 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1716 else
1717 return TABLE_insert_row( view, rec, -1, FALSE );
1718 }
1719
1720 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1721 {
1722 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1723 UINT row, r;
1724
1725 r = msi_table_find_row(tv, rec, &row, NULL);
1726 if (r != ERROR_SUCCESS)
1727 return r;
1728
1729 return TABLE_delete_row(view, row);
1730 }
1731
1732 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1733 {
1734 MSIRECORD *curr;
1735 UINT r, i, count;
1736
1737 r = TABLE_get_row(view, row - 1, &curr);
1738 if (r != ERROR_SUCCESS)
1739 return r;
1740
1741 /* Close the original record */
1742 MSI_CloseRecord(&rec->hdr);
1743
1744 count = MSI_RecordGetFieldCount(rec);
1745 for (i = 0; i < count; i++)
1746 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1747
1748 msiobj_release(&curr->hdr);
1749 return ERROR_SUCCESS;
1750 }
1751
1752 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1753 MSIRECORD *rec, UINT row)
1754 {
1755 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1756 UINT r, frow, column;
1757
1758 TRACE("%p %d %p\n", view, eModifyMode, rec );
1759
1760 switch (eModifyMode)
1761 {
1762 case MSIMODIFY_DELETE:
1763 r = modify_delete_row( view, rec );
1764 break;
1765 case MSIMODIFY_VALIDATE_NEW:
1766 r = table_validate_new( tv, rec, &column );
1767 if (r != ERROR_SUCCESS)
1768 {
1769 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1770 tv->view.error_column = tv->columns[column].colname;
1771 r = ERROR_INVALID_DATA;
1772 }
1773 break;
1774
1775 case MSIMODIFY_INSERT:
1776 r = table_validate_new( tv, rec, NULL );
1777 if (r != ERROR_SUCCESS)
1778 break;
1779 r = TABLE_insert_row( view, rec, -1, FALSE );
1780 break;
1781
1782 case MSIMODIFY_INSERT_TEMPORARY:
1783 r = table_validate_new( tv, rec, NULL );
1784 if (r != ERROR_SUCCESS)
1785 break;
1786 r = TABLE_insert_row( view, rec, -1, TRUE );
1787 break;
1788
1789 case MSIMODIFY_REFRESH:
1790 r = msi_refresh_record( view, rec, row );
1791 break;
1792
1793 case MSIMODIFY_UPDATE:
1794 r = msi_table_update( view, rec, row );
1795 break;
1796
1797 case MSIMODIFY_ASSIGN:
1798 r = msi_table_assign( view, rec );
1799 break;
1800
1801 case MSIMODIFY_MERGE:
1802 /* check row that matches this record */
1803 r = msi_table_find_row( tv, rec, &frow, &column );
1804 if (r != ERROR_SUCCESS)
1805 {
1806 r = table_validate_new( tv, rec, NULL );
1807 if (r == ERROR_SUCCESS)
1808 r = TABLE_insert_row( view, rec, -1, FALSE );
1809 }
1810 break;
1811
1812 case MSIMODIFY_REPLACE:
1813 case MSIMODIFY_VALIDATE:
1814 case MSIMODIFY_VALIDATE_FIELD:
1815 case MSIMODIFY_VALIDATE_DELETE:
1816 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1817 r = ERROR_CALL_NOT_IMPLEMENTED;
1818 break;
1819
1820 default:
1821 r = ERROR_INVALID_DATA;
1822 }
1823
1824 return r;
1825 }
1826
1827 static UINT TABLE_delete( struct tagMSIVIEW *view )
1828 {
1829 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1830
1831 TRACE("%p\n", view );
1832
1833 tv->table = NULL;
1834 tv->columns = NULL;
1835
1836 msi_free( tv );
1837
1838 return ERROR_SUCCESS;
1839 }
1840
1841 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1842 UINT val, UINT *row, MSIITERHANDLE *handle )
1843 {
1844 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1845 const MSICOLUMNHASHENTRY *entry;
1846
1847 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1848
1849 if( !tv->table )
1850 return ERROR_INVALID_PARAMETER;
1851
1852 if( (col==0) || (col > tv->num_cols) )
1853 return ERROR_INVALID_PARAMETER;
1854
1855 if( !tv->columns[col-1].hash_table )
1856 {
1857 UINT i;
1858 UINT num_rows = tv->table->row_count;
1859 MSICOLUMNHASHENTRY **hash_table;
1860 MSICOLUMNHASHENTRY *new_entry;
1861
1862 if( tv->columns[col-1].offset >= tv->row_size )
1863 {
1864 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1865 ERR("%p %p\n", tv, tv->columns );
1866 return ERROR_FUNCTION_FAILED;
1867 }
1868
1869 /* allocate contiguous memory for the table and its entries so we
1870 * don't have to do an expensive cleanup */
1871 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1872 num_rows * sizeof(MSICOLUMNHASHENTRY));
1873 if (!hash_table)
1874 return ERROR_OUTOFMEMORY;
1875
1876 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1877 tv->columns[col-1].hash_table = hash_table;
1878
1879 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1880
1881 for (i = 0; i < num_rows; i++, new_entry++)
1882 {
1883 UINT row_value;
1884
1885 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1886 continue;
1887
1888 new_entry->next = NULL;
1889 new_entry->value = row_value;
1890 new_entry->row = i;
1891 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1892 {
1893 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1894 while (prev_entry->next)
1895 prev_entry = prev_entry->next;
1896 prev_entry->next = new_entry;
1897 }
1898 else
1899 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1900 }
1901 }
1902
1903 if( !*handle )
1904 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1905 else
1906 entry = (*handle)->next;
1907
1908 while (entry && entry->value != val)
1909 entry = entry->next;
1910
1911 *handle = entry;
1912 if (!entry)
1913 return ERROR_NO_MORE_ITEMS;
1914
1915 *row = entry->row;
1916
1917 return ERROR_SUCCESS;
1918 }
1919
1920 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1921 {
1922 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1923 UINT i;
1924
1925 TRACE("%p %d\n", view, tv->table->ref_count);
1926
1927 for (i = 0; i < tv->table->col_count; i++)
1928 {
1929 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1930 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1931 }
1932
1933 return InterlockedIncrement(&tv->table->ref_count);
1934 }
1935
1936 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1937 {
1938 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1939 MSIRECORD *rec = NULL;
1940 MSIVIEW *columns = NULL;
1941 UINT row, r;
1942
1943 rec = MSI_CreateRecord(2);
1944 if (!rec)
1945 return ERROR_OUTOFMEMORY;
1946
1947 MSI_RecordSetStringW(rec, 1, table);
1948 MSI_RecordSetInteger(rec, 2, number);
1949
1950 r = TABLE_CreateView(tv->db, szColumns, &columns);
1951 if (r != ERROR_SUCCESS)
1952 {
1953 msiobj_release(&rec->hdr);
1954 return r;
1955 }
1956
1957 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1958 if (r != ERROR_SUCCESS)
1959 goto done;
1960
1961 r = TABLE_delete_row(columns, row);
1962 if (r != ERROR_SUCCESS)
1963 goto done;
1964
1965 msi_update_table_columns(tv->db, table);
1966
1967 done:
1968 msiobj_release(&rec->hdr);
1969 columns->ops->delete(columns);
1970 return r;
1971 }
1972
1973 static UINT TABLE_release(struct tagMSIVIEW *view)
1974 {
1975 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1976 INT ref = tv->table->ref_count;
1977 UINT i, r;
1978
1979 TRACE("%p %d\n", view, ref);
1980
1981 for (i = 0; i < tv->table->col_count; i++)
1982 {
1983 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1984 {
1985 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1986 if (ref == 0)
1987 {
1988 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1989 tv->table->colinfo[i].number);
1990 if (r != ERROR_SUCCESS)
1991 break;
1992 }
1993 }
1994 }
1995
1996 ref = InterlockedDecrement(&tv->table->ref_count);
1997 if (ref == 0)
1998 {
1999 if (!tv->table->row_count)
2000 {
2001 list_remove(&tv->table->entry);
2002 free_table(tv->table);
2003 TABLE_delete(view);
2004 }
2005 }
2006
2007 return ref;
2008 }
2009
2010 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2011 LPCWSTR column, UINT type, BOOL hold)
2012 {
2013 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2014 MSITABLE *msitable;
2015 MSIRECORD *rec;
2016 UINT r, i;
2017
2018 rec = MSI_CreateRecord(4);
2019 if (!rec)
2020 return ERROR_OUTOFMEMORY;
2021
2022 MSI_RecordSetStringW(rec, 1, table);
2023 MSI_RecordSetInteger(rec, 2, number);
2024 MSI_RecordSetStringW(rec, 3, column);
2025 MSI_RecordSetInteger(rec, 4, type);
2026
2027 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2028 if (r != ERROR_SUCCESS)
2029 goto done;
2030
2031 msi_update_table_columns(tv->db, table);
2032
2033 if (!hold)
2034 goto done;
2035
2036 msitable = find_cached_table(tv->db, table);
2037 for (i = 0; i < msitable->col_count; i++)
2038 {
2039 if (!strcmpW( msitable->colinfo[i].colname, column ))
2040 {
2041 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2042 break;
2043 }
2044 }
2045
2046 done:
2047 msiobj_release(&rec->hdr);
2048 return r;
2049 }
2050
2051 static UINT TABLE_drop(struct tagMSIVIEW *view)
2052 {
2053 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2054 MSIVIEW *tables = NULL;
2055 MSIRECORD *rec = NULL;
2056 UINT r, row;
2057 INT i;
2058
2059 TRACE("dropping table %s\n", debugstr_w(tv->name));
2060
2061 for (i = tv->table->col_count - 1; i >= 0; i--)
2062 {
2063 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2064 tv->table->colinfo[i].number);
2065 if (r != ERROR_SUCCESS)
2066 return r;
2067 }
2068
2069 rec = MSI_CreateRecord(1);
2070 if (!rec)
2071 return ERROR_OUTOFMEMORY;
2072
2073 MSI_RecordSetStringW(rec, 1, tv->name);
2074
2075 r = TABLE_CreateView(tv->db, szTables, &tables);
2076 if (r != ERROR_SUCCESS)
2077 {
2078 msiobj_release(&rec->hdr);
2079 return r;
2080 }
2081
2082 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2083 if (r != ERROR_SUCCESS)
2084 goto done;
2085
2086 r = TABLE_delete_row(tables, row);
2087 if (r != ERROR_SUCCESS)
2088 goto done;
2089
2090 list_remove(&tv->table->entry);
2091 free_table(tv->table);
2092
2093 done:
2094 msiobj_release(&rec->hdr);
2095 tables->ops->delete(tables);
2096
2097 return r;
2098 }
2099
2100 static const MSIVIEWOPS table_ops =
2101 {
2102 TABLE_fetch_int,
2103 TABLE_fetch_stream,
2104 TABLE_get_row,
2105 TABLE_set_row,
2106 TABLE_insert_row,
2107 TABLE_delete_row,
2108 TABLE_execute,
2109 TABLE_close,
2110 TABLE_get_dimensions,
2111 TABLE_get_column_info,
2112 TABLE_modify,
2113 TABLE_delete,
2114 TABLE_find_matching_rows,
2115 TABLE_add_ref,
2116 TABLE_release,
2117 TABLE_add_column,
2118 TABLE_remove_column,
2119 NULL,
2120 TABLE_drop,
2121 };
2122
2123 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2124 {
2125 MSITABLEVIEW *tv ;
2126 UINT r, sz;
2127
2128 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2129
2130 if ( !strcmpW( name, szStreams ) )
2131 return STREAMS_CreateView( db, view );
2132 else if ( !strcmpW( name, szStorages ) )
2133 return STORAGES_CreateView( db, view );
2134
2135 sz = FIELD_OFFSET( MSITABLEVIEW, name[lstrlenW( name ) + 1] );
2136 tv = msi_alloc_zero( sz );
2137 if( !tv )
2138 return ERROR_FUNCTION_FAILED;
2139
2140 r = get_table( db, name, &tv->table );
2141 if( r != ERROR_SUCCESS )
2142 {
2143 msi_free( tv );
2144 WARN("table not found\n");
2145 return r;
2146 }
2147
2148 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2149
2150 /* fill the structure */
2151 tv->view.ops = &table_ops;
2152 tv->db = db;
2153 tv->columns = tv->table->colinfo;
2154 tv->num_cols = tv->table->col_count;
2155 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2156
2157 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2158
2159 *view = (MSIVIEW*) tv;
2160 lstrcpyW( tv->name, name );
2161
2162 return ERROR_SUCCESS;
2163 }
2164
2165 UINT MSI_CommitTables( MSIDATABASE *db )
2166 {
2167 UINT r, bytes_per_strref;
2168 HRESULT hr;
2169 MSITABLE *table = NULL;
2170
2171 TRACE("%p\n",db);
2172
2173 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2174 if( r != ERROR_SUCCESS )
2175 {
2176 WARN("failed to save string table r=%08x\n",r);
2177 return r;
2178 }
2179
2180 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2181 {
2182 r = save_table( db, table, bytes_per_strref );
2183 if( r != ERROR_SUCCESS )
2184 {
2185 WARN("failed to save table %s (r=%08x)\n",
2186 debugstr_w(table->name), r);
2187 return r;
2188 }
2189 }
2190
2191 hr = IStorage_Commit( db->storage, 0 );
2192 if (FAILED( hr ))
2193 {
2194 WARN("failed to commit changes 0x%08x\n", hr);
2195 r = ERROR_FUNCTION_FAILED;
2196 }
2197 return r;
2198 }
2199
2200 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2201 {
2202 MSITABLE *t;
2203 UINT r;
2204
2205 TRACE("%p %s\n", db, debugstr_w(table));
2206
2207 if (!table)
2208 return MSICONDITION_ERROR;
2209
2210 r = get_table( db, table, &t );
2211 if (r != ERROR_SUCCESS)
2212 return MSICONDITION_NONE;
2213
2214 return t->persistent;
2215 }
2216
2217 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2218 {
2219 UINT ret = 0, i;
2220
2221 for (i = 0; i < bytes; i++)
2222 ret += (data[col + i] << i * 8);
2223
2224 return ret;
2225 }
2226
2227 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2228 {
2229 LPWSTR stname = NULL, sval, p;
2230 DWORD len;
2231 UINT i, r;
2232
2233 TRACE("%p %p\n", tv, rec);
2234
2235 len = lstrlenW( tv->name ) + 1;
2236 stname = msi_alloc( len*sizeof(WCHAR) );
2237 if ( !stname )
2238 {
2239 r = ERROR_OUTOFMEMORY;
2240 goto err;
2241 }
2242
2243 lstrcpyW( stname, tv->name );
2244
2245 for ( i = 0; i < tv->num_cols; i++ )
2246 {
2247 if ( tv->columns[i].type & MSITYPE_KEY )
2248 {
2249 sval = msi_dup_record_field( rec, i + 1 );
2250 if ( !sval )
2251 {
2252 r = ERROR_OUTOFMEMORY;
2253 goto err;
2254 }
2255
2256 len += lstrlenW( szDot ) + lstrlenW ( sval );
2257 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2258 if ( !p )
2259 {
2260 r = ERROR_OUTOFMEMORY;
2261 msi_free(sval);
2262 goto err;
2263 }
2264 stname = p;
2265
2266 lstrcatW( stname, szDot );
2267 lstrcatW( stname, sval );
2268
2269 msi_free( sval );
2270 }
2271 else
2272 continue;
2273 }
2274
2275 *pstname = encode_streamname( FALSE, stname );
2276 msi_free( stname );
2277
2278 return ERROR_SUCCESS;
2279
2280 err:
2281 msi_free ( stname );
2282 *pstname = NULL;
2283 return r;
2284 }
2285
2286 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2287 IStorage *stg,
2288 const BYTE *rawdata, UINT bytes_per_strref )
2289 {
2290 UINT i, val, ofs = 0;
2291 USHORT mask;
2292 MSICOLUMNINFO *columns = tv->columns;
2293 MSIRECORD *rec;
2294
2295 mask = rawdata[0] | (rawdata[1] << 8);
2296 rawdata += 2;
2297
2298 rec = MSI_CreateRecord( tv->num_cols );
2299 if( !rec )
2300 return rec;
2301
2302 TRACE("row ->\n");
2303 for( i=0; i<tv->num_cols; i++ )
2304 {
2305 if ( (mask&1) && (i>=(mask>>8)) )
2306 break;
2307 /* all keys must be present */
2308 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2309 continue;
2310
2311 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2312 {
2313 LPWSTR encname;
2314 IStream *stm = NULL;
2315 UINT r;
2316
2317 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2318
2319 r = msi_record_encoded_stream_name( tv, rec, &encname );
2320 if ( r != ERROR_SUCCESS )
2321 return NULL;
2322
2323 r = IStorage_OpenStream( stg, encname, NULL,
2324 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2325 if ( r != ERROR_SUCCESS )
2326 {
2327 msi_free( encname );
2328 return NULL;
2329 }
2330
2331 MSI_RecordSetStream( rec, i+1, stm );
2332 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2333 msi_free( encname );
2334 }
2335 else if( columns[i].type & MSITYPE_STRING )
2336 {
2337 int len;
2338 const WCHAR *sval;
2339
2340 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2341 sval = msi_string_lookup( st, val, &len );
2342 msi_record_set_string( rec, i+1, sval, len );
2343 TRACE(" field %d [%s]\n", i+1, debugstr_wn(sval, len));
2344 ofs += bytes_per_strref;
2345 }
2346 else
2347 {
2348 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2349 switch( n )
2350 {
2351 case 2:
2352 val = read_raw_int(rawdata, ofs, n);
2353 if (val)
2354 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2355 TRACE(" field %d [0x%04x]\n", i+1, val );
2356 break;
2357 case 4:
2358 val = read_raw_int(rawdata, ofs, n);
2359 if (val)
2360 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2361 TRACE(" field %d [0x%08x]\n", i+1, val );
2362 break;
2363 default:
2364 ERR("oops - unknown column width %d\n", n);
2365 break;
2366 }
2367 ofs += n;
2368 }
2369 }
2370 return rec;
2371 }
2372
2373 static void dump_record( MSIRECORD *rec )
2374 {
2375 UINT i, n;
2376
2377 n = MSI_RecordGetFieldCount( rec );
2378 for( i=1; i<=n; i++ )
2379 {
2380 int len;
2381 const WCHAR *sval;
2382
2383 if( MSI_RecordIsNull( rec, i ) )
2384 TRACE("row -> []\n");
2385 else if( (sval = msi_record_get_string( rec, i, &len )) )
2386 TRACE("row -> [%s]\n", debugstr_wn(sval, len));
2387 else
2388 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2389 }
2390 }
2391
2392 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2393 {
2394 UINT i;
2395 for (i = 0; i < rawsize / 2; i++)
2396 {
2397 int len;
2398 const WCHAR *sval = msi_string_lookup( st, rawdata[i], &len );
2399 MESSAGE(" %04x %s\n", rawdata[i], debugstr_wn(sval, len) );
2400 }
2401 }
2402
2403 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2404 {
2405 UINT i, r, *data;
2406
2407 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2408 for( i=0; i<tv->num_cols; i++ )
2409 {
2410 data[i] = 0;
2411
2412 if ( ~tv->columns[i].type & MSITYPE_KEY )
2413 continue;
2414
2415 /* turn the transform column value into a row value */
2416 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2417 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2418 {
2419 int len;
2420 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
2421 if (str)
2422 {
2423 r = msi_string2id( tv->db->strings, str, len, &data[i] );
2424
2425 /* if there's no matching string in the string table,
2426 these keys can't match any record, so fail now. */
2427 if (r != ERROR_SUCCESS)
2428 {
2429 msi_free( data );
2430 return NULL;
2431 }
2432 }
2433 else data[i] = 0;
2434 }
2435 else
2436 {
2437 data[i] = MSI_RecordGetInteger( rec, i+1 );
2438
2439 if (data[i] == MSI_NULL_INTEGER)
2440 data[i] = 0;
2441 else if ((tv->columns[i].type&0xff) == 2)
2442 data[i] += 0x8000;
2443 else
2444 data[i] += 0x80000000;
2445 }
2446 }
2447 return data;
2448 }
2449
2450 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2451 {
2452 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2453
2454 for( i=0; i<tv->num_cols; i++ )
2455 {
2456 if ( ~tv->columns[i].type & MSITYPE_KEY )
2457 continue;
2458
2459 /* turn the transform column value into a row value */
2460 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2461 if ( r != ERROR_SUCCESS )
2462 {
2463 ERR("TABLE_fetch_int shouldn't fail here\n");
2464 break;
2465 }
2466
2467 /* if this key matches, move to the next column */
2468 if ( x != data[i] )
2469 {
2470 ret = ERROR_FUNCTION_FAILED;
2471 break;
2472 }
2473 if (column) *column = i;
2474 ret = ERROR_SUCCESS;
2475 }
2476 return ret;
2477 }
2478
2479 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2480 {
2481 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2482
2483 data = msi_record_to_row( tv, rec );
2484 if( !data )
2485 return r;
2486 for( i = 0; i < tv->table->row_count; i++ )
2487 {
2488 r = msi_row_matches( tv, i, data, column );
2489 if( r == ERROR_SUCCESS )
2490 {
2491 *row = i;
2492 break;
2493 }
2494 }
2495 msi_free( data );
2496 return r;
2497 }
2498
2499 typedef struct
2500 {
2501 struct list entry;
2502 LPWSTR name;
2503 } TRANSFORMDATA;
2504
2505 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2506 string_table *st, TRANSFORMDATA *transform,
2507 UINT bytes_per_strref )
2508 {
2509 BYTE *rawdata = NULL;
2510 MSITABLEVIEW *tv = NULL;
2511 UINT r, n, sz, i, mask, num_cols, colcol = 0, rawsize = 0;
2512 MSIRECORD *rec = NULL;
2513 WCHAR coltable[32];
2514 const WCHAR *name;
2515
2516 if (!transform)
2517 return ERROR_SUCCESS;
2518
2519 name = transform->name;
2520
2521 coltable[0] = 0;
2522 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2523
2524 /* read the transform data */
2525 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2526 if ( !rawdata )
2527 {
2528 TRACE("table %s empty\n", debugstr_w(name) );
2529 return ERROR_INVALID_TABLE;
2530 }
2531
2532 /* create a table view */
2533 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2534 if( r != ERROR_SUCCESS )
2535 goto err;
2536
2537 r = tv->view.ops->execute( &tv->view, NULL );
2538 if( r != ERROR_SUCCESS )
2539 goto err;
2540
2541 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2542 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2543
2544 /* interpret the data */
2545 for (n = 0; n < rawsize;)
2546 {
2547 mask = rawdata[n] | (rawdata[n + 1] << 8);
2548 if (mask & 1)
2549 {
2550 /*
2551 * if the low bit is set, columns are continuous and
2552 * the number of columns is specified in the high byte
2553 */
2554 sz = 2;
2555 num_cols = mask >> 8;
2556 if (num_cols > tv->num_cols)
2557 {
2558 ERR("excess columns in transform: %u > %u\n", num_cols, tv->num_cols);
2559 break;
2560 }
2561
2562 for (i = 0; i < num_cols; i++)
2563 {
2564 if( (tv->columns[i].type & MSITYPE_STRING) &&
2565 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2566 sz += bytes_per_strref;
2567 else
2568 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2569 }
2570 }
2571 else
2572 {
2573 /*
2574 * If the low bit is not set, mask is a bitmask.
2575 * Excepting for key fields, which are always present,
2576 * each bit indicates that a field is present in the transform record.
2577 *
2578 * mask == 0 is a special case ... only the keys will be present
2579 * and it means that this row should be deleted.
2580 */
2581 sz = 2;
2582 num_cols = tv->num_cols;
2583 for (i = 0; i < num_cols; i++)
2584 {
2585 if ((tv->columns[i].type & MSITYPE_KEY) || ((1 << i) & mask))
2586 {
2587 if ((tv->columns[i].type & MSITYPE_STRING) &&
2588 !MSITYPE_IS_BINARY(tv->columns[i].type))
2589 sz += bytes_per_strref;
2590 else
2591 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2592 }
2593 }
2594 }
2595
2596 /* check we didn't run of the end of the table */
2597 if (n + sz > rawsize)
2598 {
2599 ERR("borked.\n");
2600 dump_table( st, (USHORT *)rawdata, rawsize );
2601 break;
2602 }
2603
2604 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2605 if (rec)
2606 {
2607 WCHAR table[32];
2608 DWORD sz = 32;
2609 UINT number = MSI_NULL_INTEGER;
2610 UINT row = 0;
2611
2612 if (!strcmpW( name, szColumns ))
2613 {
2614 MSI_RecordGetStringW( rec, 1, table, &sz );
2615 number = MSI_RecordGetInteger( rec, 2 );
2616
2617 /*
2618 * Native msi seems writes nul into the Number (2nd) column of
2619 * the _Columns table when there are new columns
2620 */
2621 if ( number == MSI_NULL_INTEGER )
2622 {
2623 /* reset the column number on a new table */
2624 if (strcmpW( coltable, table ))
2625 {
2626 colcol = 0;
2627 lstrcpyW( coltable, table );
2628 }
2629
2630 /* fix nul column numbers */
2631 MSI_RecordSetInteger( rec, 2, ++colcol );
2632 }
2633 }
2634
2635 if (TRACE_ON(msidb)) dump_record( rec );
2636
2637 r = msi_table_find_row( tv, rec, &row, NULL );
2638 if (r == ERROR_SUCCESS)
2639 {
2640 if (!mask)
2641 {
2642 TRACE("deleting row [%d]:\n", row);
2643 r = TABLE_delete_row( &tv->view, row );
2644 if (r != ERROR_SUCCESS)
2645 WARN("failed to delete row %u\n", r);
2646 }
2647 else if (mask & 1)
2648 {
2649 TRACE("modifying full row [%d]:\n", row);
2650 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2651 if (r != ERROR_SUCCESS)
2652 WARN("failed to modify row %u\n", r);
2653 }
2654 else
2655 {
2656 TRACE("modifying masked row [%d]:\n", row);
2657 r = TABLE_set_row( &tv->view, row, rec, mask );
2658 if (r != ERROR_SUCCESS)
2659 WARN("failed to modify row %u\n", r);
2660 }
2661 }
2662 else
2663 {
2664 TRACE("inserting row\n");
2665 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2666 if (r != ERROR_SUCCESS)
2667 WARN("failed to insert row %u\n", r);
2668 }
2669
2670 if (!strcmpW( name, szColumns ))
2671 msi_update_table_columns( db, table );
2672
2673 msiobj_release( &rec->hdr );
2674 }
2675
2676 n += sz;
2677 }
2678
2679 err:
2680 /* no need to free the table, it's associated with the database */
2681 msi_free( rawdata );
2682 if( tv )
2683 tv->view.ops->delete( &tv->view );
2684
2685 return ERROR_SUCCESS;
2686 }
2687
2688 /*
2689 * msi_table_apply_transform
2690 *
2691 * Enumerate the table transforms in a transform storage and apply each one.
2692 */
2693 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2694 {
2695 struct list transforms;
2696 IEnumSTATSTG *stgenum = NULL;
2697 TRANSFORMDATA *transform;
2698 TRANSFORMDATA *tables = NULL, *columns = NULL;
2699 HRESULT r;
2700 STATSTG stat;
2701 string_table *strings;
2702 UINT ret = ERROR_FUNCTION_FAILED;
2703 UINT bytes_per_strref;
2704 BOOL property_update = FALSE;
2705
2706 TRACE("%p %p\n", db, stg );
2707
2708 strings = msi_load_string_table( stg, &bytes_per_strref );
2709 if( !strings )
2710 goto end;
2711
2712 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2713 if( FAILED( r ) )
2714 goto end;
2715
2716 list_init(&transforms);
2717
2718 while ( TRUE )
2719 {
2720 MSITABLEVIEW *tv = NULL;
2721 WCHAR name[0x40];
2722 ULONG count = 0;
2723
2724 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2725 if ( FAILED( r ) || !count )
2726 break;
2727
2728 decode_streamname( stat.pwcsName, name );
2729 CoTaskMemFree( stat.pwcsName );
2730 if ( name[0] != 0x4840 )
2731 continue;
2732
2733 if ( !strcmpW( name+1, szStringPool ) ||
2734 !strcmpW( name+1, szStringData ) )
2735 continue;
2736
2737 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2738 if ( !transform )
2739 break;
2740
2741 list_add_tail( &transforms, &transform->entry );
2742
2743 transform->name = strdupW( name + 1 );
2744
2745 if ( !strcmpW( transform->name, szTables ) )
2746 tables = transform;
2747 else if (!strcmpW( transform->name, szColumns ) )
2748 columns = transform;
2749 else if (!strcmpW( transform->name, szProperty ))
2750 property_update = TRUE;
2751
2752 TRACE("transform contains stream %s\n", debugstr_w(name));
2753
2754 /* load the table */
2755 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2756 if( r != ERROR_SUCCESS )
2757 continue;
2758
2759 r = tv->view.ops->execute( &tv->view, NULL );
2760 if( r != ERROR_SUCCESS )
2761 {
2762 tv->view.ops->delete( &tv->view );
2763 continue;
2764 }
2765
2766 tv->view.ops->delete( &tv->view );
2767 }
2768
2769 /*
2770 * Apply _Tables and _Columns transforms first so that
2771 * the table metadata is correct, and empty tables exist.
2772 */
2773 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2774 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2775 goto end;
2776
2777 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2778 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2779 goto end;
2780
2781 ret = ERROR_SUCCESS;
2782
2783 while ( !list_empty( &transforms ) )
2784 {
2785 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2786
2787 if ( strcmpW( transform->name, szColumns ) &&
2788 strcmpW( transform->name, szTables ) &&
2789 ret == ERROR_SUCCESS )
2790 {
2791 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2792 }
2793
2794 list_remove( &transform->entry );
2795 msi_free( transform->name );
2796 msi_free( transform );
2797 }
2798
2799 if ( ret == ERROR_SUCCESS )
2800 {
2801 append_storage_to_db( db, stg );
2802 if (property_update) msi_clone_properties( db );
2803 }
2804
2805 end:
2806 if ( stgenum )
2807 IEnumSTATSTG_Release( stgenum );
2808 if ( strings )
2809 msi_destroy_stringtable( strings );
2810
2811 return ret;
2812 }