[MSI]
[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!\n");
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 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\n", col);
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_addstringW( db->strings, col->table, -1, 1, string_persistence );
745 UINT col_id = msi_addstringW( db->strings, col->column, -1, 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 table = find_cached_table( db, name );
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 LPWSTR encname, full_name = NULL;
1134
1135 if( !view->ops->fetch_int )
1136 return ERROR_INVALID_PARAMETER;
1137
1138 r = msi_stream_name( tv, row, &full_name );
1139 if ( r != ERROR_SUCCESS )
1140 {
1141 ERR("fetching stream, error = %d\n", r);
1142 return r;
1143 }
1144
1145 encname = encode_streamname( FALSE, full_name );
1146 r = msi_get_raw_stream( tv->db, encname, stm );
1147 if( r )
1148 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1149
1150 msi_free( full_name );
1151 msi_free( encname );
1152 return r;
1153 }
1154
1155 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1156 {
1157 UINT offset, n, i;
1158
1159 if( !tv->table )
1160 return ERROR_INVALID_PARAMETER;
1161
1162 if( (col==0) || (col>tv->num_cols) )
1163 return ERROR_INVALID_PARAMETER;
1164
1165 if( row >= tv->table->row_count )
1166 return ERROR_INVALID_PARAMETER;
1167
1168 if( tv->columns[col-1].offset >= tv->row_size )
1169 {
1170 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1171 ERR("%p %p\n", tv, tv->columns );
1172 return ERROR_FUNCTION_FAILED;
1173 }
1174
1175 msi_free( tv->columns[col-1].hash_table );
1176 tv->columns[col-1].hash_table = NULL;
1177
1178 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1179 if ( n != 2 && n != 3 && n != 4 )
1180 {
1181 ERR("oops! what is %d bytes per column?\n", n );
1182 return ERROR_FUNCTION_FAILED;
1183 }
1184
1185 offset = tv->columns[col-1].offset;
1186 for ( i = 0; i < n; i++ )
1187 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1188
1189 return ERROR_SUCCESS;
1190 }
1191
1192 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1193 {
1194 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1195
1196 if (!tv->table)
1197 return ERROR_INVALID_PARAMETER;
1198
1199 return msi_view_get_row(tv->db, view, row, rec);
1200 }
1201
1202 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1203 {
1204 static const WCHAR insert[] = {
1205 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1206 '`','_','S','t','r','e','a','m','s','`',' ',
1207 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1208 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1209 MSIQUERY *query = NULL;
1210 MSIRECORD *rec;
1211 UINT r;
1212
1213 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1214
1215 rec = MSI_CreateRecord( 2 );
1216 if ( !rec )
1217 return ERROR_OUTOFMEMORY;
1218
1219 r = MSI_RecordSetStringW( rec, 1, name );
1220 if ( r != ERROR_SUCCESS )
1221 goto err;
1222
1223 r = MSI_RecordSetIStream( rec, 2, data );
1224 if ( r != ERROR_SUCCESS )
1225 goto err;
1226
1227 r = MSI_DatabaseOpenViewW( db, insert, &query );
1228 if ( r != ERROR_SUCCESS )
1229 goto err;
1230
1231 r = MSI_ViewExecute( query, rec );
1232
1233 err:
1234 msiobj_release( &query->hdr );
1235 msiobj_release( &rec->hdr );
1236 return r;
1237 }
1238
1239 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1240 {
1241 MSICOLUMNINFO columninfo;
1242 UINT r;
1243 int ival;
1244
1245 if ( (iField <= 0) ||
1246 (iField > tv->num_cols) ||
1247 MSI_RecordIsNull( rec, iField ) )
1248 return ERROR_FUNCTION_FAILED;
1249
1250 columninfo = tv->columns[ iField - 1 ];
1251
1252 if ( MSITYPE_IS_BINARY(columninfo.type) )
1253 {
1254 *pvalue = 1; /* refers to the first key column */
1255 }
1256 else if ( columninfo.type & MSITYPE_STRING )
1257 {
1258 int len;
1259 const WCHAR *sval = msi_record_get_string( rec, iField, &len );
1260 if (sval)
1261 {
1262 r = msi_string2id( tv->db->strings, sval, len, pvalue );
1263 if (r != ERROR_SUCCESS)
1264 return ERROR_NOT_FOUND;
1265 }
1266 else *pvalue = 0;
1267 }
1268 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1269 {
1270 ival = MSI_RecordGetInteger( rec, iField );
1271 if (ival == 0x80000000) *pvalue = 0x8000;
1272 else
1273 {
1274 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1275 if (*pvalue & 0xffff0000)
1276 {
1277 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1278 return ERROR_FUNCTION_FAILED;
1279 }
1280 }
1281 }
1282 else
1283 {
1284 ival = MSI_RecordGetInteger( rec, iField );
1285 *pvalue = ival ^ 0x80000000;
1286 }
1287
1288 return ERROR_SUCCESS;
1289 }
1290
1291 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1292 {
1293 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1294 UINT i, val, r = ERROR_SUCCESS;
1295
1296 if ( !tv->table )
1297 return ERROR_INVALID_PARAMETER;
1298
1299 /* test if any of the mask bits are invalid */
1300 if ( mask >= (1<<tv->num_cols) )
1301 return ERROR_INVALID_PARAMETER;
1302
1303 for ( i = 0; i < tv->num_cols; i++ )
1304 {
1305 BOOL persistent;
1306
1307 /* only update the fields specified in the mask */
1308 if ( !(mask&(1<<i)) )
1309 continue;
1310
1311 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1312 (tv->table->data_persistent[row]);
1313 /* FIXME: should we allow updating keys? */
1314
1315 val = 0;
1316 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1317 {
1318 r = get_table_value_from_record (tv, rec, i + 1, &val);
1319 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1320 {
1321 IStream *stm;
1322 LPWSTR stname;
1323
1324 if ( r != ERROR_SUCCESS )
1325 return ERROR_FUNCTION_FAILED;
1326
1327 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1328 if ( r != ERROR_SUCCESS )
1329 return r;
1330
1331 r = msi_stream_name( tv, row, &stname );
1332 if ( r != ERROR_SUCCESS )
1333 {
1334 IStream_Release( stm );
1335 return r;
1336 }
1337
1338 r = msi_addstreamW( tv->db, stname, stm );
1339 IStream_Release( stm );
1340 msi_free ( stname );
1341
1342 if ( r != ERROR_SUCCESS )
1343 return r;
1344 }
1345 else if ( tv->columns[i].type & MSITYPE_STRING )
1346 {
1347 UINT x;
1348
1349 if ( r != ERROR_SUCCESS )
1350 {
1351 int len;
1352 const WCHAR *sval = msi_record_get_string( rec, i + 1, &len );
1353 val = msi_addstringW( tv->db->strings, sval, len, 1,
1354 persistent ? StringPersistent : StringNonPersistent );
1355 }
1356 else
1357 {
1358 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1359 if (val == x)
1360 continue;
1361 }
1362 }
1363 else
1364 {
1365 if ( r != ERROR_SUCCESS )
1366 return ERROR_FUNCTION_FAILED;
1367 }
1368 }
1369
1370 r = TABLE_set_int( tv, row, i+1, val );
1371 if ( r != ERROR_SUCCESS )
1372 break;
1373 }
1374 return r;
1375 }
1376
1377 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1378 {
1379 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1380 BYTE **p, *row;
1381 BOOL *b;
1382 UINT sz;
1383 BYTE ***data_ptr;
1384 BOOL **data_persist_ptr;
1385 UINT *row_count;
1386
1387 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1388
1389 if( !tv->table )
1390 return ERROR_INVALID_PARAMETER;
1391
1392 row = msi_alloc_zero( tv->row_size );
1393 if( !row )
1394 return ERROR_NOT_ENOUGH_MEMORY;
1395
1396 row_count = &tv->table->row_count;
1397 data_ptr = &tv->table->data;
1398 data_persist_ptr = &tv->table->data_persistent;
1399 if (*num == -1)
1400 *num = tv->table->row_count;
1401
1402 sz = (*row_count + 1) * sizeof (BYTE*);
1403 if( *data_ptr )
1404 p = msi_realloc( *data_ptr, sz );
1405 else
1406 p = msi_alloc( sz );
1407 if( !p )
1408 {
1409 msi_free( row );
1410 return ERROR_NOT_ENOUGH_MEMORY;
1411 }
1412
1413 sz = (*row_count + 1) * sizeof (BOOL);
1414 if( *data_persist_ptr )
1415 b = msi_realloc( *data_persist_ptr, sz );
1416 else
1417 b = msi_alloc( sz );
1418 if( !b )
1419 {
1420 msi_free( row );
1421 msi_free( p );
1422 return ERROR_NOT_ENOUGH_MEMORY;
1423 }
1424
1425 *data_ptr = p;
1426 (*data_ptr)[*row_count] = row;
1427
1428 *data_persist_ptr = b;
1429 (*data_persist_ptr)[*row_count] = !temporary;
1430
1431 (*row_count)++;
1432
1433 return ERROR_SUCCESS;
1434 }
1435
1436 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1437 {
1438 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1439
1440 TRACE("%p %p\n", tv, record);
1441
1442 TRACE("There are %d columns\n", tv->num_cols );
1443
1444 return ERROR_SUCCESS;
1445 }
1446
1447 static UINT TABLE_close( struct tagMSIVIEW *view )
1448 {
1449 TRACE("%p\n", view );
1450
1451 return ERROR_SUCCESS;
1452 }
1453
1454 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1455 {
1456 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1457
1458 TRACE("%p %p %p\n", view, rows, cols );
1459
1460 if( cols )
1461 *cols = tv->num_cols;
1462 if( rows )
1463 {
1464 if( !tv->table )
1465 return ERROR_INVALID_PARAMETER;
1466 *rows = tv->table->row_count;
1467 }
1468
1469 return ERROR_SUCCESS;
1470 }
1471
1472 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1473 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1474 LPCWSTR *table_name )
1475 {
1476 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1477
1478 TRACE("%p %d %p %p\n", tv, n, name, type );
1479
1480 if( ( n == 0 ) || ( n > tv->num_cols ) )
1481 return ERROR_INVALID_PARAMETER;
1482
1483 if( name )
1484 {
1485 *name = tv->columns[n-1].colname;
1486 if( !*name )
1487 return ERROR_FUNCTION_FAILED;
1488 }
1489
1490 if( table_name )
1491 {
1492 *table_name = tv->columns[n-1].tablename;
1493 if( !*table_name )
1494 return ERROR_FUNCTION_FAILED;
1495 }
1496
1497 if( type )
1498 *type = tv->columns[n-1].type;
1499
1500 if( temporary )
1501 *temporary = tv->columns[n-1].temporary;
1502
1503 return ERROR_SUCCESS;
1504 }
1505
1506 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1507
1508 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1509 {
1510 UINT r, row, i;
1511
1512 /* check there are no null values where they're not allowed */
1513 for( i = 0; i < tv->num_cols; i++ )
1514 {
1515 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1516 continue;
1517
1518 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1519 TRACE("skipping binary column\n");
1520 else if ( tv->columns[i].type & MSITYPE_STRING )
1521 {
1522 int len;
1523 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
1524
1525 if (!str || (!str[0] && !len))
1526 {
1527 if (column) *column = i;
1528 return ERROR_INVALID_DATA;
1529 }
1530 }
1531 else
1532 {
1533 UINT n;
1534
1535 n = MSI_RecordGetInteger( rec, i+1 );
1536 if (n == MSI_NULL_INTEGER)
1537 {
1538 if (column) *column = i;
1539 return ERROR_INVALID_DATA;
1540 }
1541 }
1542 }
1543
1544 /* check there are no duplicate keys */
1545 r = msi_table_find_row( tv, rec, &row, column );
1546 if (r == ERROR_SUCCESS)
1547 return ERROR_FUNCTION_FAILED;
1548
1549 return ERROR_SUCCESS;
1550 }
1551
1552 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1553 {
1554 UINT r, i, ivalue, x;
1555
1556 for (i = 0; i < tv->num_cols; i++ )
1557 {
1558 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1559
1560 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1561 if (r != ERROR_SUCCESS)
1562 return 1;
1563
1564 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1565 if (r != ERROR_SUCCESS)
1566 {
1567 WARN("TABLE_fetch_int should not fail here %u\n", r);
1568 return -1;
1569 }
1570 if (ivalue > x)
1571 {
1572 return 1;
1573 }
1574 else if (ivalue == x)
1575 {
1576 if (i < tv->num_cols - 1) continue;
1577 return 0;
1578 }
1579 else
1580 return -1;
1581 }
1582 return 1;
1583 }
1584
1585 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1586 {
1587 int idx, c, low = 0, high = tv->table->row_count - 1;
1588
1589 TRACE("%p %p\n", tv, rec);
1590
1591 while (low <= high)
1592 {
1593 idx = (low + high) / 2;
1594 c = compare_record( tv, idx, rec );
1595
1596 if (c < 0)
1597 high = idx - 1;
1598 else if (c > 0)
1599 low = idx + 1;
1600 else
1601 {
1602 TRACE("found %u\n", idx);
1603 return idx;
1604 }
1605 }
1606 TRACE("found %u\n", high + 1);
1607 return high + 1;
1608 }
1609
1610 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1611 {
1612 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1613 UINT i, r;
1614
1615 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1616
1617 /* check that the key is unique - can we find a matching row? */
1618 r = table_validate_new( tv, rec, NULL );
1619 if( r != ERROR_SUCCESS )
1620 return ERROR_FUNCTION_FAILED;
1621
1622 if (row == -1)
1623 row = find_insert_index( tv, rec );
1624
1625 r = table_create_new_row( view, &row, temporary );
1626 TRACE("insert_row returned %08x\n", r);
1627 if( r != ERROR_SUCCESS )
1628 return r;
1629
1630 /* shift the rows to make room for the new row */
1631 for (i = tv->table->row_count - 1; i > row; i--)
1632 {
1633 memmove(&(tv->table->data[i][0]),
1634 &(tv->table->data[i - 1][0]), tv->row_size);
1635 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1636 }
1637
1638 /* Re-set the persistence flag */
1639 tv->table->data_persistent[row] = !temporary;
1640 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1641 }
1642
1643 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1644 {
1645 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1646 UINT r, num_rows, num_cols, i;
1647
1648 TRACE("%p %d\n", tv, row);
1649
1650 if ( !tv->table )
1651 return ERROR_INVALID_PARAMETER;
1652
1653 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1654 if ( r != ERROR_SUCCESS )
1655 return r;
1656
1657 if ( row >= num_rows )
1658 return ERROR_FUNCTION_FAILED;
1659
1660 num_rows = tv->table->row_count;
1661 tv->table->row_count--;
1662
1663 /* reset the hash tables */
1664 for (i = 0; i < tv->num_cols; i++)
1665 {
1666 msi_free( tv->columns[i].hash_table );
1667 tv->columns[i].hash_table = NULL;
1668 }
1669
1670 for (i = row + 1; i < num_rows; i++)
1671 {
1672 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1673 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1674 }
1675
1676 msi_free(tv->table->data[num_rows - 1]);
1677
1678 return ERROR_SUCCESS;
1679 }
1680
1681 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1682 {
1683 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1684 UINT r, new_row;
1685
1686 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1687 * sets the fetched record apart from other records
1688 */
1689
1690 if (!tv->table)
1691 return ERROR_INVALID_PARAMETER;
1692
1693 r = msi_table_find_row(tv, rec, &new_row, NULL);
1694 if (r != ERROR_SUCCESS)
1695 {
1696 ERR("can't find row to modify\n");
1697 return ERROR_FUNCTION_FAILED;
1698 }
1699
1700 /* the row cannot be changed */
1701 if (row != new_row + 1)
1702 return ERROR_FUNCTION_FAILED;
1703
1704 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1705 }
1706
1707 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1708 {
1709 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1710 UINT r, row;
1711
1712 if (!tv->table)
1713 return ERROR_INVALID_PARAMETER;
1714
1715 r = msi_table_find_row(tv, rec, &row, NULL);
1716 if (r == ERROR_SUCCESS)
1717 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1718 else
1719 return TABLE_insert_row( view, rec, -1, FALSE );
1720 }
1721
1722 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1723 {
1724 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1725 UINT row, r;
1726
1727 r = msi_table_find_row(tv, rec, &row, NULL);
1728 if (r != ERROR_SUCCESS)
1729 return r;
1730
1731 return TABLE_delete_row(view, row);
1732 }
1733
1734 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1735 {
1736 MSIRECORD *curr;
1737 UINT r, i, count;
1738
1739 r = TABLE_get_row(view, row - 1, &curr);
1740 if (r != ERROR_SUCCESS)
1741 return r;
1742
1743 /* Close the original record */
1744 MSI_CloseRecord(&rec->hdr);
1745
1746 count = MSI_RecordGetFieldCount(rec);
1747 for (i = 0; i < count; i++)
1748 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1749
1750 msiobj_release(&curr->hdr);
1751 return ERROR_SUCCESS;
1752 }
1753
1754 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1755 MSIRECORD *rec, UINT row)
1756 {
1757 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1758 UINT r, frow, column;
1759
1760 TRACE("%p %d %p\n", view, eModifyMode, rec );
1761
1762 switch (eModifyMode)
1763 {
1764 case MSIMODIFY_DELETE:
1765 r = modify_delete_row( view, rec );
1766 break;
1767 case MSIMODIFY_VALIDATE_NEW:
1768 r = table_validate_new( tv, rec, &column );
1769 if (r != ERROR_SUCCESS)
1770 {
1771 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1772 tv->view.error_column = tv->columns[column].colname;
1773 r = ERROR_INVALID_DATA;
1774 }
1775 break;
1776
1777 case MSIMODIFY_INSERT:
1778 r = table_validate_new( tv, rec, NULL );
1779 if (r != ERROR_SUCCESS)
1780 break;
1781 r = TABLE_insert_row( view, rec, -1, FALSE );
1782 break;
1783
1784 case MSIMODIFY_INSERT_TEMPORARY:
1785 r = table_validate_new( tv, rec, NULL );
1786 if (r != ERROR_SUCCESS)
1787 break;
1788 r = TABLE_insert_row( view, rec, -1, TRUE );
1789 break;
1790
1791 case MSIMODIFY_REFRESH:
1792 r = msi_refresh_record( view, rec, row );
1793 break;
1794
1795 case MSIMODIFY_UPDATE:
1796 r = msi_table_update( view, rec, row );
1797 break;
1798
1799 case MSIMODIFY_ASSIGN:
1800 r = msi_table_assign( view, rec );
1801 break;
1802
1803 case MSIMODIFY_MERGE:
1804 /* check row that matches this record */
1805 r = msi_table_find_row( tv, rec, &frow, &column );
1806 if (r != ERROR_SUCCESS)
1807 {
1808 r = table_validate_new( tv, rec, NULL );
1809 if (r == ERROR_SUCCESS)
1810 r = TABLE_insert_row( view, rec, -1, FALSE );
1811 }
1812 break;
1813
1814 case MSIMODIFY_REPLACE:
1815 case MSIMODIFY_VALIDATE:
1816 case MSIMODIFY_VALIDATE_FIELD:
1817 case MSIMODIFY_VALIDATE_DELETE:
1818 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1819 r = ERROR_CALL_NOT_IMPLEMENTED;
1820 break;
1821
1822 default:
1823 r = ERROR_INVALID_DATA;
1824 }
1825
1826 return r;
1827 }
1828
1829 static UINT TABLE_delete( struct tagMSIVIEW *view )
1830 {
1831 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1832
1833 TRACE("%p\n", view );
1834
1835 tv->table = NULL;
1836 tv->columns = NULL;
1837
1838 msi_free( tv );
1839
1840 return ERROR_SUCCESS;
1841 }
1842
1843 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1844 UINT val, UINT *row, MSIITERHANDLE *handle )
1845 {
1846 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1847 const MSICOLUMNHASHENTRY *entry;
1848
1849 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1850
1851 if( !tv->table )
1852 return ERROR_INVALID_PARAMETER;
1853
1854 if( (col==0) || (col > tv->num_cols) )
1855 return ERROR_INVALID_PARAMETER;
1856
1857 if( !tv->columns[col-1].hash_table )
1858 {
1859 UINT i;
1860 UINT num_rows = tv->table->row_count;
1861 MSICOLUMNHASHENTRY **hash_table;
1862 MSICOLUMNHASHENTRY *new_entry;
1863
1864 if( tv->columns[col-1].offset >= tv->row_size )
1865 {
1866 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1867 ERR("%p %p\n", tv, tv->columns );
1868 return ERROR_FUNCTION_FAILED;
1869 }
1870
1871 /* allocate contiguous memory for the table and its entries so we
1872 * don't have to do an expensive cleanup */
1873 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1874 num_rows * sizeof(MSICOLUMNHASHENTRY));
1875 if (!hash_table)
1876 return ERROR_OUTOFMEMORY;
1877
1878 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1879 tv->columns[col-1].hash_table = hash_table;
1880
1881 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1882
1883 for (i = 0; i < num_rows; i++, new_entry++)
1884 {
1885 UINT row_value;
1886
1887 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1888 continue;
1889
1890 new_entry->next = NULL;
1891 new_entry->value = row_value;
1892 new_entry->row = i;
1893 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1894 {
1895 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1896 while (prev_entry->next)
1897 prev_entry = prev_entry->next;
1898 prev_entry->next = new_entry;
1899 }
1900 else
1901 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1902 }
1903 }
1904
1905 if( !*handle )
1906 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1907 else
1908 entry = (*handle)->next;
1909
1910 while (entry && entry->value != val)
1911 entry = entry->next;
1912
1913 *handle = entry;
1914 if (!entry)
1915 return ERROR_NO_MORE_ITEMS;
1916
1917 *row = entry->row;
1918
1919 return ERROR_SUCCESS;
1920 }
1921
1922 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1923 {
1924 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1925 UINT i;
1926
1927 TRACE("%p %d\n", view, tv->table->ref_count);
1928
1929 for (i = 0; i < tv->table->col_count; i++)
1930 {
1931 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1932 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1933 }
1934
1935 return InterlockedIncrement(&tv->table->ref_count);
1936 }
1937
1938 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1939 {
1940 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1941 MSIRECORD *rec = NULL;
1942 MSIVIEW *columns = NULL;
1943 UINT row, r;
1944
1945 rec = MSI_CreateRecord(2);
1946 if (!rec)
1947 return ERROR_OUTOFMEMORY;
1948
1949 MSI_RecordSetStringW(rec, 1, table);
1950 MSI_RecordSetInteger(rec, 2, number);
1951
1952 r = TABLE_CreateView(tv->db, szColumns, &columns);
1953 if (r != ERROR_SUCCESS)
1954 {
1955 msiobj_release(&rec->hdr);
1956 return r;
1957 }
1958
1959 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1960 if (r != ERROR_SUCCESS)
1961 goto done;
1962
1963 r = TABLE_delete_row(columns, row);
1964 if (r != ERROR_SUCCESS)
1965 goto done;
1966
1967 msi_update_table_columns(tv->db, table);
1968
1969 done:
1970 msiobj_release(&rec->hdr);
1971 columns->ops->delete(columns);
1972 return r;
1973 }
1974
1975 static UINT TABLE_release(struct tagMSIVIEW *view)
1976 {
1977 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1978 INT ref = tv->table->ref_count;
1979 UINT i, r;
1980
1981 TRACE("%p %d\n", view, ref);
1982
1983 for (i = 0; i < tv->table->col_count; i++)
1984 {
1985 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1986 {
1987 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1988 if (ref == 0)
1989 {
1990 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1991 tv->table->colinfo[i].number);
1992 if (r != ERROR_SUCCESS)
1993 break;
1994 }
1995 }
1996 }
1997
1998 ref = InterlockedDecrement(&tv->table->ref_count);
1999 if (ref == 0)
2000 {
2001 if (!tv->table->row_count)
2002 {
2003 list_remove(&tv->table->entry);
2004 free_table(tv->table);
2005 TABLE_delete(view);
2006 }
2007 }
2008
2009 return ref;
2010 }
2011
2012 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2013 LPCWSTR column, UINT type, BOOL hold)
2014 {
2015 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2016 MSITABLE *msitable;
2017 MSIRECORD *rec;
2018 UINT r, i;
2019
2020 rec = MSI_CreateRecord(4);
2021 if (!rec)
2022 return ERROR_OUTOFMEMORY;
2023
2024 MSI_RecordSetStringW(rec, 1, table);
2025 MSI_RecordSetInteger(rec, 2, number);
2026 MSI_RecordSetStringW(rec, 3, column);
2027 MSI_RecordSetInteger(rec, 4, type);
2028
2029 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2030 if (r != ERROR_SUCCESS)
2031 goto done;
2032
2033 msi_update_table_columns(tv->db, table);
2034
2035 if (!hold)
2036 goto done;
2037
2038 msitable = find_cached_table(tv->db, table);
2039 for (i = 0; i < msitable->col_count; i++)
2040 {
2041 if (!strcmpW( msitable->colinfo[i].colname, column ))
2042 {
2043 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2044 break;
2045 }
2046 }
2047
2048 done:
2049 msiobj_release(&rec->hdr);
2050 return r;
2051 }
2052
2053 static UINT TABLE_drop(struct tagMSIVIEW *view)
2054 {
2055 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2056 MSIVIEW *tables = NULL;
2057 MSIRECORD *rec = NULL;
2058 UINT r, row;
2059 INT i;
2060
2061 TRACE("dropping table %s\n", debugstr_w(tv->name));
2062
2063 for (i = tv->table->col_count - 1; i >= 0; i--)
2064 {
2065 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2066 tv->table->colinfo[i].number);
2067 if (r != ERROR_SUCCESS)
2068 return r;
2069 }
2070
2071 rec = MSI_CreateRecord(1);
2072 if (!rec)
2073 return ERROR_OUTOFMEMORY;
2074
2075 MSI_RecordSetStringW(rec, 1, tv->name);
2076
2077 r = TABLE_CreateView(tv->db, szTables, &tables);
2078 if (r != ERROR_SUCCESS)
2079 {
2080 msiobj_release(&rec->hdr);
2081 return r;
2082 }
2083
2084 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2085 if (r != ERROR_SUCCESS)
2086 goto done;
2087
2088 r = TABLE_delete_row(tables, row);
2089 if (r != ERROR_SUCCESS)
2090 goto done;
2091
2092 list_remove(&tv->table->entry);
2093 free_table(tv->table);
2094
2095 done:
2096 msiobj_release(&rec->hdr);
2097 tables->ops->delete(tables);
2098
2099 return r;
2100 }
2101
2102 static const MSIVIEWOPS table_ops =
2103 {
2104 TABLE_fetch_int,
2105 TABLE_fetch_stream,
2106 TABLE_get_row,
2107 TABLE_set_row,
2108 TABLE_insert_row,
2109 TABLE_delete_row,
2110 TABLE_execute,
2111 TABLE_close,
2112 TABLE_get_dimensions,
2113 TABLE_get_column_info,
2114 TABLE_modify,
2115 TABLE_delete,
2116 TABLE_find_matching_rows,
2117 TABLE_add_ref,
2118 TABLE_release,
2119 TABLE_add_column,
2120 TABLE_remove_column,
2121 NULL,
2122 TABLE_drop,
2123 };
2124
2125 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2126 {
2127 MSITABLEVIEW *tv ;
2128 UINT r, sz;
2129
2130 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2131
2132 if ( !strcmpW( name, szStreams ) )
2133 return STREAMS_CreateView( db, view );
2134 else if ( !strcmpW( name, szStorages ) )
2135 return STORAGES_CreateView( db, view );
2136
2137 sz = FIELD_OFFSET( MSITABLEVIEW, name[lstrlenW( name ) + 1] );
2138 tv = msi_alloc_zero( sz );
2139 if( !tv )
2140 return ERROR_FUNCTION_FAILED;
2141
2142 r = get_table( db, name, &tv->table );
2143 if( r != ERROR_SUCCESS )
2144 {
2145 msi_free( tv );
2146 WARN("table not found\n");
2147 return r;
2148 }
2149
2150 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2151
2152 /* fill the structure */
2153 tv->view.ops = &table_ops;
2154 tv->db = db;
2155 tv->columns = tv->table->colinfo;
2156 tv->num_cols = tv->table->col_count;
2157 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2158
2159 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2160
2161 *view = (MSIVIEW*) tv;
2162 lstrcpyW( tv->name, name );
2163
2164 return ERROR_SUCCESS;
2165 }
2166
2167 UINT MSI_CommitTables( MSIDATABASE *db )
2168 {
2169 UINT r, bytes_per_strref;
2170 HRESULT hr;
2171 MSITABLE *table = NULL;
2172
2173 TRACE("%p\n",db);
2174
2175 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2176 if( r != ERROR_SUCCESS )
2177 {
2178 WARN("failed to save string table r=%08x\n",r);
2179 return r;
2180 }
2181
2182 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2183 {
2184 r = save_table( db, table, bytes_per_strref );
2185 if( r != ERROR_SUCCESS )
2186 {
2187 WARN("failed to save table %s (r=%08x)\n",
2188 debugstr_w(table->name), r);
2189 return r;
2190 }
2191 }
2192
2193 hr = IStorage_Commit( db->storage, 0 );
2194 if (FAILED( hr ))
2195 {
2196 WARN("failed to commit changes 0x%08x\n", hr);
2197 r = ERROR_FUNCTION_FAILED;
2198 }
2199 return r;
2200 }
2201
2202 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2203 {
2204 MSITABLE *t;
2205 UINT r;
2206
2207 TRACE("%p %s\n", db, debugstr_w(table));
2208
2209 if (!table)
2210 return MSICONDITION_ERROR;
2211
2212 r = get_table( db, table, &t );
2213 if (r != ERROR_SUCCESS)
2214 return MSICONDITION_NONE;
2215
2216 return t->persistent;
2217 }
2218
2219 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2220 {
2221 UINT ret = 0, i;
2222
2223 for (i = 0; i < bytes; i++)
2224 ret += (data[col + i] << i * 8);
2225
2226 return ret;
2227 }
2228
2229 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2230 {
2231 LPWSTR stname = NULL, sval, p;
2232 DWORD len;
2233 UINT i, r;
2234
2235 TRACE("%p %p\n", tv, rec);
2236
2237 len = lstrlenW( tv->name ) + 1;
2238 stname = msi_alloc( len*sizeof(WCHAR) );
2239 if ( !stname )
2240 {
2241 r = ERROR_OUTOFMEMORY;
2242 goto err;
2243 }
2244
2245 lstrcpyW( stname, tv->name );
2246
2247 for ( i = 0; i < tv->num_cols; i++ )
2248 {
2249 if ( tv->columns[i].type & MSITYPE_KEY )
2250 {
2251 sval = msi_dup_record_field( rec, i + 1 );
2252 if ( !sval )
2253 {
2254 r = ERROR_OUTOFMEMORY;
2255 goto err;
2256 }
2257
2258 len += lstrlenW( szDot ) + lstrlenW ( sval );
2259 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2260 if ( !p )
2261 {
2262 r = ERROR_OUTOFMEMORY;
2263 msi_free(sval);
2264 goto err;
2265 }
2266 stname = p;
2267
2268 lstrcatW( stname, szDot );
2269 lstrcatW( stname, sval );
2270
2271 msi_free( sval );
2272 }
2273 else
2274 continue;
2275 }
2276
2277 *pstname = encode_streamname( FALSE, stname );
2278 msi_free( stname );
2279
2280 return ERROR_SUCCESS;
2281
2282 err:
2283 msi_free ( stname );
2284 *pstname = NULL;
2285 return r;
2286 }
2287
2288 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2289 IStorage *stg,
2290 const BYTE *rawdata, UINT bytes_per_strref )
2291 {
2292 UINT i, val, ofs = 0;
2293 USHORT mask;
2294 MSICOLUMNINFO *columns = tv->columns;
2295 MSIRECORD *rec;
2296
2297 mask = rawdata[0] | (rawdata[1] << 8);
2298 rawdata += 2;
2299
2300 rec = MSI_CreateRecord( tv->num_cols );
2301 if( !rec )
2302 return rec;
2303
2304 TRACE("row ->\n");
2305 for( i=0; i<tv->num_cols; i++ )
2306 {
2307 if ( (mask&1) && (i>=(mask>>8)) )
2308 break;
2309 /* all keys must be present */
2310 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2311 continue;
2312
2313 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2314 {
2315 LPWSTR encname;
2316 IStream *stm = NULL;
2317 UINT r;
2318
2319 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2320
2321 r = msi_record_encoded_stream_name( tv, rec, &encname );
2322 if ( r != ERROR_SUCCESS )
2323 return NULL;
2324
2325 r = IStorage_OpenStream( stg, encname, NULL,
2326 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2327 if ( r != ERROR_SUCCESS )
2328 {
2329 msi_free( encname );
2330 return NULL;
2331 }
2332
2333 MSI_RecordSetStream( rec, i+1, stm );
2334 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2335 msi_free( encname );
2336 }
2337 else if( columns[i].type & MSITYPE_STRING )
2338 {
2339 int len;
2340 const WCHAR *sval;
2341
2342 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2343 sval = msi_string_lookup( st, val, &len );
2344 msi_record_set_string( rec, i+1, sval, len );
2345 TRACE(" field %d [%s]\n", i+1, debugstr_wn(sval, len));
2346 ofs += bytes_per_strref;
2347 }
2348 else
2349 {
2350 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2351 switch( n )
2352 {
2353 case 2:
2354 val = read_raw_int(rawdata, ofs, n);
2355 if (val)
2356 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2357 TRACE(" field %d [0x%04x]\n", i+1, val );
2358 break;
2359 case 4:
2360 val = read_raw_int(rawdata, ofs, n);
2361 if (val)
2362 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2363 TRACE(" field %d [0x%08x]\n", i+1, val );
2364 break;
2365 default:
2366 ERR("oops - unknown column width %d\n", n);
2367 break;
2368 }
2369 ofs += n;
2370 }
2371 }
2372 return rec;
2373 }
2374
2375 static void dump_record( MSIRECORD *rec )
2376 {
2377 UINT i, n;
2378
2379 n = MSI_RecordGetFieldCount( rec );
2380 for( i=1; i<=n; i++ )
2381 {
2382 int len;
2383 const WCHAR *sval;
2384
2385 if( MSI_RecordIsNull( rec, i ) )
2386 TRACE("row -> []\n");
2387 else if( (sval = msi_record_get_string( rec, i, &len )) )
2388 TRACE("row -> [%s]\n", debugstr_wn(sval, len));
2389 else
2390 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2391 }
2392 }
2393
2394 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2395 {
2396 UINT i;
2397 for (i = 0; i < rawsize / 2; i++)
2398 {
2399 int len;
2400 const WCHAR *sval = msi_string_lookup( st, rawdata[i], &len );
2401 MESSAGE(" %04x %s\n", rawdata[i], debugstr_wn(sval, len) );
2402 }
2403 }
2404
2405 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2406 {
2407 UINT i, r, *data;
2408
2409 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2410 for( i=0; i<tv->num_cols; i++ )
2411 {
2412 data[i] = 0;
2413
2414 if ( ~tv->columns[i].type & MSITYPE_KEY )
2415 continue;
2416
2417 /* turn the transform column value into a row value */
2418 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2419 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2420 {
2421 int len;
2422 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
2423 if (str)
2424 {
2425 r = msi_string2id( tv->db->strings, str, len, &data[i] );
2426
2427 /* if there's no matching string in the string table,
2428 these keys can't match any record, so fail now. */
2429 if (r != ERROR_SUCCESS)
2430 {
2431 msi_free( data );
2432 return NULL;
2433 }
2434 }
2435 else data[i] = 0;
2436 }
2437 else
2438 {
2439 data[i] = MSI_RecordGetInteger( rec, i+1 );
2440
2441 if (data[i] == MSI_NULL_INTEGER)
2442 data[i] = 0;
2443 else if ((tv->columns[i].type&0xff) == 2)
2444 data[i] += 0x8000;
2445 else
2446 data[i] += 0x80000000;
2447 }
2448 }
2449 return data;
2450 }
2451
2452 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2453 {
2454 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2455
2456 for( i=0; i<tv->num_cols; i++ )
2457 {
2458 if ( ~tv->columns[i].type & MSITYPE_KEY )
2459 continue;
2460
2461 /* turn the transform column value into a row value */
2462 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2463 if ( r != ERROR_SUCCESS )
2464 {
2465 ERR("TABLE_fetch_int shouldn't fail here\n");
2466 break;
2467 }
2468
2469 /* if this key matches, move to the next column */
2470 if ( x != data[i] )
2471 {
2472 ret = ERROR_FUNCTION_FAILED;
2473 break;
2474 }
2475 if (column) *column = i;
2476 ret = ERROR_SUCCESS;
2477 }
2478 return ret;
2479 }
2480
2481 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2482 {
2483 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2484
2485 data = msi_record_to_row( tv, rec );
2486 if( !data )
2487 return r;
2488 for( i = 0; i < tv->table->row_count; i++ )
2489 {
2490 r = msi_row_matches( tv, i, data, column );
2491 if( r == ERROR_SUCCESS )
2492 {
2493 *row = i;
2494 break;
2495 }
2496 }
2497 msi_free( data );
2498 return r;
2499 }
2500
2501 typedef struct
2502 {
2503 struct list entry;
2504 LPWSTR name;
2505 } TRANSFORMDATA;
2506
2507 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2508 string_table *st, TRANSFORMDATA *transform,
2509 UINT bytes_per_strref )
2510 {
2511 BYTE *rawdata = NULL;
2512 MSITABLEVIEW *tv = NULL;
2513 UINT r, n, sz, i, mask, num_cols, colcol = 0, rawsize = 0;
2514 MSIRECORD *rec = NULL;
2515 WCHAR coltable[32];
2516 const WCHAR *name;
2517
2518 if (!transform)
2519 return ERROR_SUCCESS;
2520
2521 name = transform->name;
2522
2523 coltable[0] = 0;
2524 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2525
2526 /* read the transform data */
2527 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2528 if ( !rawdata )
2529 {
2530 TRACE("table %s empty\n", debugstr_w(name) );
2531 return ERROR_INVALID_TABLE;
2532 }
2533
2534 /* create a table view */
2535 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2536 if( r != ERROR_SUCCESS )
2537 goto err;
2538
2539 r = tv->view.ops->execute( &tv->view, NULL );
2540 if( r != ERROR_SUCCESS )
2541 goto err;
2542
2543 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2544 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2545
2546 /* interpret the data */
2547 for (n = 0; n < rawsize;)
2548 {
2549 mask = rawdata[n] | (rawdata[n + 1] << 8);
2550 if (mask & 1)
2551 {
2552 /*
2553 * if the low bit is set, columns are continuous and
2554 * the number of columns is specified in the high byte
2555 */
2556 sz = 2;
2557 num_cols = mask >> 8;
2558 for (i = 0; i < num_cols; i++)
2559 {
2560 if( (tv->columns[i].type & MSITYPE_STRING) &&
2561 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2562 sz += bytes_per_strref;
2563 else
2564 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2565 }
2566 }
2567 else
2568 {
2569 /*
2570 * If the low bit is not set, mask is a bitmask.
2571 * Excepting for key fields, which are always present,
2572 * each bit indicates that a field is present in the transform record.
2573 *
2574 * mask == 0 is a special case ... only the keys will be present
2575 * and it means that this row should be deleted.
2576 */
2577 sz = 2;
2578 num_cols = tv->num_cols;
2579 for (i = 0; i < num_cols; i++)
2580 {
2581 if ((tv->columns[i].type & MSITYPE_KEY) || ((1 << i) & mask))
2582 {
2583 if ((tv->columns[i].type & MSITYPE_STRING) &&
2584 !MSITYPE_IS_BINARY(tv->columns[i].type))
2585 sz += bytes_per_strref;
2586 else
2587 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2588 }
2589 }
2590 }
2591
2592 /* check we didn't run of the end of the table */
2593 if (n + sz > rawsize)
2594 {
2595 ERR("borked.\n");
2596 dump_table( st, (USHORT *)rawdata, rawsize );
2597 break;
2598 }
2599
2600 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2601 if (rec)
2602 {
2603 WCHAR table[32];
2604 DWORD sz = 32;
2605 UINT number = MSI_NULL_INTEGER;
2606 UINT row = 0;
2607
2608 if (!strcmpW( name, szColumns ))
2609 {
2610 MSI_RecordGetStringW( rec, 1, table, &sz );
2611 number = MSI_RecordGetInteger( rec, 2 );
2612
2613 /*
2614 * Native msi seems writes nul into the Number (2nd) column of
2615 * the _Columns table, only when the columns are from a new table
2616 */
2617 if ( number == MSI_NULL_INTEGER )
2618 {
2619 /* reset the column number on a new table */
2620 if (strcmpW( coltable, table ))
2621 {
2622 colcol = 0;
2623 lstrcpyW( coltable, table );
2624 }
2625
2626 /* fix nul column numbers */
2627 MSI_RecordSetInteger( rec, 2, ++colcol );
2628 }
2629 }
2630
2631 if (TRACE_ON(msidb)) dump_record( rec );
2632
2633 r = msi_table_find_row( tv, rec, &row, NULL );
2634 if (r == ERROR_SUCCESS)
2635 {
2636 if (!mask)
2637 {
2638 TRACE("deleting row [%d]:\n", row);
2639 r = TABLE_delete_row( &tv->view, row );
2640 if (r != ERROR_SUCCESS)
2641 WARN("failed to delete row %u\n", r);
2642 }
2643 else if (mask & 1)
2644 {
2645 TRACE("modifying full row [%d]:\n", row);
2646 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2647 if (r != ERROR_SUCCESS)
2648 WARN("failed to modify row %u\n", r);
2649 }
2650 else
2651 {
2652 TRACE("modifying masked row [%d]:\n", row);
2653 r = TABLE_set_row( &tv->view, row, rec, mask );
2654 if (r != ERROR_SUCCESS)
2655 WARN("failed to modify row %u\n", r);
2656 }
2657 }
2658 else
2659 {
2660 TRACE("inserting row\n");
2661 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2662 if (r != ERROR_SUCCESS)
2663 WARN("failed to insert row %u\n", r);
2664 }
2665
2666 if (number != MSI_NULL_INTEGER && !strcmpW( name, szColumns ))
2667 msi_update_table_columns( db, table );
2668
2669 msiobj_release( &rec->hdr );
2670 }
2671
2672 n += sz;
2673 }
2674
2675 err:
2676 /* no need to free the table, it's associated with the database */
2677 msi_free( rawdata );
2678 if( tv )
2679 tv->view.ops->delete( &tv->view );
2680
2681 return ERROR_SUCCESS;
2682 }
2683
2684 /*
2685 * msi_table_apply_transform
2686 *
2687 * Enumerate the table transforms in a transform storage and apply each one.
2688 */
2689 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2690 {
2691 struct list transforms;
2692 IEnumSTATSTG *stgenum = NULL;
2693 TRANSFORMDATA *transform;
2694 TRANSFORMDATA *tables = NULL, *columns = NULL;
2695 HRESULT r;
2696 STATSTG stat;
2697 string_table *strings;
2698 UINT ret = ERROR_FUNCTION_FAILED;
2699 UINT bytes_per_strref;
2700
2701 TRACE("%p %p\n", db, stg );
2702
2703 strings = msi_load_string_table( stg, &bytes_per_strref );
2704 if( !strings )
2705 goto end;
2706
2707 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2708 if( FAILED( r ) )
2709 goto end;
2710
2711 list_init(&transforms);
2712
2713 while ( TRUE )
2714 {
2715 MSITABLEVIEW *tv = NULL;
2716 WCHAR name[0x40];
2717 ULONG count = 0;
2718
2719 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2720 if ( FAILED( r ) || !count )
2721 break;
2722
2723 decode_streamname( stat.pwcsName, name );
2724 CoTaskMemFree( stat.pwcsName );
2725 if ( name[0] != 0x4840 )
2726 continue;
2727
2728 if ( !strcmpW( name+1, szStringPool ) ||
2729 !strcmpW( name+1, szStringData ) )
2730 continue;
2731
2732 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2733 if ( !transform )
2734 break;
2735
2736 list_add_tail( &transforms, &transform->entry );
2737
2738 transform->name = strdupW( name + 1 );
2739
2740 if ( !strcmpW( transform->name, szTables ) )
2741 tables = transform;
2742 else if (!strcmpW( transform->name, szColumns ) )
2743 columns = transform;
2744
2745 TRACE("transform contains stream %s\n", debugstr_w(name));
2746
2747 /* load the table */
2748 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2749 if( r != ERROR_SUCCESS )
2750 continue;
2751
2752 r = tv->view.ops->execute( &tv->view, NULL );
2753 if( r != ERROR_SUCCESS )
2754 {
2755 tv->view.ops->delete( &tv->view );
2756 continue;
2757 }
2758
2759 tv->view.ops->delete( &tv->view );
2760 }
2761
2762 /*
2763 * Apply _Tables and _Columns transforms first so that
2764 * the table metadata is correct, and empty tables exist.
2765 */
2766 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2767 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2768 goto end;
2769
2770 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2771 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2772 goto end;
2773
2774 ret = ERROR_SUCCESS;
2775
2776 while ( !list_empty( &transforms ) )
2777 {
2778 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2779
2780 if ( strcmpW( transform->name, szColumns ) &&
2781 strcmpW( transform->name, szTables ) &&
2782 ret == ERROR_SUCCESS )
2783 {
2784 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2785 }
2786
2787 list_remove( &transform->entry );
2788 msi_free( transform->name );
2789 msi_free( transform );
2790 }
2791
2792 if ( ret == ERROR_SUCCESS )
2793 append_storage_to_db( db, stg );
2794
2795 end:
2796 if ( stgenum )
2797 IEnumSTATSTG_Release( stgenum );
2798 if ( strings )
2799 msi_destroy_stringtable( strings );
2800
2801 return ret;
2802 }