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