d3d8/tests: Make the window client rect match the d3d swapchain size.
[wine.git] / dlls / msi / table.c
blob2b36091eab8fb089631b15a7aea0ec48d278788f
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002-2005 Mike McCormack for CodeWeavers
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.
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.
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
21 #include <stdarg.h>
22 #include <assert.h>
24 #define COBJMACROS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winerror.h"
29 #include "msi.h"
30 #include "msiquery.h"
31 #include "objbase.h"
32 #include "objidl.h"
33 #include "winnls.h"
34 #include "msipriv.h"
35 #include "query.h"
37 #include "wine/debug.h"
38 #include "wine/unicode.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
42 #define MSITABLE_HASH_TABLE_SIZE 37
44 typedef struct tagMSICOLUMNHASHENTRY
46 struct tagMSICOLUMNHASHENTRY *next;
47 UINT value;
48 UINT row;
49 } MSICOLUMNHASHENTRY;
51 typedef struct tagMSICOLUMNINFO
53 LPCWSTR tablename;
54 UINT number;
55 LPCWSTR colname;
56 UINT type;
57 UINT offset;
58 INT ref_count;
59 BOOL temporary;
60 MSICOLUMNHASHENTRY **hash_table;
61 } MSICOLUMNINFO;
63 struct tagMSITABLE
65 BYTE **data;
66 BOOL *data_persistent;
67 UINT row_count;
68 struct list entry;
69 MSICOLUMNINFO *colinfo;
70 UINT col_count;
71 MSICONDITION persistent;
72 INT ref_count;
73 WCHAR name[1];
76 /* information for default tables */
77 static const WCHAR szTables[] = {'_','T','a','b','l','e','s',0};
78 static const WCHAR szTable[] = {'T','a','b','l','e',0};
79 static const WCHAR szColumns[] = {'_','C','o','l','u','m','n','s',0};
80 static const WCHAR szNumber[] = {'N','u','m','b','e','r',0};
81 static const WCHAR szType[] = {'T','y','p','e',0};
83 static const MSICOLUMNINFO _Columns_cols[4] = {
84 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
85 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
86 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
87 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
90 static const MSICOLUMNINFO _Tables_cols[1] = {
91 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
94 #define MAX_STREAM_NAME 0x1f
96 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
98 if( MSITYPE_IS_BINARY(col->type) )
99 return 2;
101 if( col->type & MSITYPE_STRING )
102 return bytes_per_strref;
104 if( (col->type & 0xff) <= 2)
105 return 2;
107 if( (col->type & 0xff) != 4 )
108 ERR("Invalid column size %u\n", col->type & 0xff);
110 return 4;
113 static int utf2mime(int x)
115 if( (x>='0') && (x<='9') )
116 return x-'0';
117 if( (x>='A') && (x<='Z') )
118 return x-'A'+10;
119 if( (x>='a') && (x<='z') )
120 return x-'a'+10+26;
121 if( x=='.' )
122 return 10+26+26;
123 if( x=='_' )
124 return 10+26+26+1;
125 return -1;
128 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
130 DWORD count = MAX_STREAM_NAME;
131 DWORD ch, next;
132 LPWSTR out, p;
134 if( !bTable )
135 count = lstrlenW( in )+2;
136 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
137 p = out;
139 if( bTable )
141 *p++ = 0x4840;
142 count --;
144 while( count -- )
146 ch = *in++;
147 if( !ch )
149 *p = ch;
150 return out;
152 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
154 ch = utf2mime(ch) + 0x4800;
155 next = *in;
156 if( next && (next<0x80) )
158 next = utf2mime(next);
159 if( next != -1 )
161 next += 0x3ffffc0;
162 ch += (next<<6);
163 in++;
167 *p++ = ch;
169 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
170 msi_free( out );
171 return NULL;
174 static int mime2utf(int x)
176 if( x<10 )
177 return x + '0';
178 if( x<(10+26))
179 return x - 10 + 'A';
180 if( x<(10+26+26))
181 return x - 10 - 26 + 'a';
182 if( x == (10+26+26) )
183 return '.';
184 return '_';
187 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
189 WCHAR ch;
190 DWORD count = 0;
192 while ( (ch = *in++) )
194 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
196 if( ch >= 0x4800 )
197 ch = mime2utf(ch-0x4800);
198 else
200 ch -= 0x3800;
201 *out++ = mime2utf(ch&0x3f);
202 count++;
203 ch = mime2utf((ch>>6)&0x3f);
206 *out++ = ch;
207 count++;
209 *out = 0;
210 return count;
213 void enum_stream_names( IStorage *stg )
215 IEnumSTATSTG *stgenum = NULL;
216 HRESULT r;
217 STATSTG stat;
218 ULONG n, count;
219 WCHAR name[0x40];
221 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
222 if( FAILED( r ) )
223 return;
225 n = 0;
226 while( 1 )
228 count = 0;
229 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
230 if( FAILED( r ) || !count )
231 break;
232 decode_streamname( stat.pwcsName, name );
233 TRACE("stream %2d -> %s %s\n", n,
234 debugstr_w(stat.pwcsName), debugstr_w(name) );
235 CoTaskMemFree( stat.pwcsName );
236 n++;
239 IEnumSTATSTG_Release( stgenum );
242 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
243 BYTE **pdata, UINT *psz )
245 HRESULT r;
246 UINT ret = ERROR_FUNCTION_FAILED;
247 VOID *data;
248 ULONG sz, count;
249 IStream *stm = NULL;
250 STATSTG stat;
251 LPWSTR encname;
253 encname = encode_streamname(table, stname);
255 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
257 r = IStorage_OpenStream(stg, encname, NULL,
258 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
259 msi_free( encname );
260 if( FAILED( r ) )
262 WARN("open stream failed r = %08x - empty table?\n", r);
263 return ret;
266 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
267 if( FAILED( r ) )
269 WARN("open stream failed r = %08x!\n", r);
270 goto end;
273 if( stat.cbSize.QuadPart >> 32 )
275 WARN("Too big!\n");
276 goto end;
279 sz = stat.cbSize.QuadPart;
280 data = msi_alloc( sz );
281 if( !data )
283 WARN("couldn't allocate memory r=%08x!\n", r);
284 ret = ERROR_NOT_ENOUGH_MEMORY;
285 goto end;
288 r = IStream_Read(stm, data, sz, &count );
289 if( FAILED( r ) || ( count != sz ) )
291 msi_free( data );
292 WARN("read stream failed r = %08x!\n", r);
293 goto end;
296 *pdata = data;
297 *psz = sz;
298 ret = ERROR_SUCCESS;
300 end:
301 IStream_Release( stm );
303 return ret;
306 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
307 LPCVOID data, UINT sz, BOOL bTable )
309 HRESULT r;
310 UINT ret = ERROR_FUNCTION_FAILED;
311 ULONG count;
312 IStream *stm = NULL;
313 ULARGE_INTEGER size;
314 LARGE_INTEGER pos;
315 LPWSTR encname;
317 encname = encode_streamname(bTable, stname );
318 r = IStorage_OpenStream( stg, encname, NULL,
319 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
320 if( FAILED(r) )
322 r = IStorage_CreateStream( stg, encname,
323 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
325 msi_free( encname );
326 if( FAILED( r ) )
328 WARN("open stream failed r = %08x\n", r);
329 return ret;
332 size.QuadPart = sz;
333 r = IStream_SetSize( stm, size );
334 if( FAILED( r ) )
336 WARN("Failed to SetSize\n");
337 goto end;
340 pos.QuadPart = 0;
341 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
342 if( FAILED( r ) )
344 WARN("Failed to Seek\n");
345 goto end;
348 if (sz)
350 r = IStream_Write(stm, data, sz, &count );
351 if( FAILED( r ) || ( count != sz ) )
353 WARN("Failed to Write\n");
354 goto end;
358 ret = ERROR_SUCCESS;
360 end:
361 IStream_Release( stm );
363 return ret;
366 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
368 UINT i;
369 for (i = 0; i < count; i++) msi_free( colinfo[i].hash_table );
372 static void free_table( MSITABLE *table )
374 UINT i;
375 for( i=0; i<table->row_count; i++ )
376 msi_free( table->data[i] );
377 msi_free( table->data );
378 msi_free( table->data_persistent );
379 msi_free_colinfo( table->colinfo, table->col_count );
380 msi_free( table->colinfo );
381 msi_free( table );
384 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
386 const MSICOLUMNINFO *last_col;
388 if (!count)
389 return 0;
391 if (bytes_per_strref != LONG_STR_BYTES)
393 UINT i, size = 0;
394 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
395 return size;
397 last_col = &cols[count - 1];
398 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
401 /* add this table to the list of cached tables in the database */
402 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
404 BYTE *rawdata = NULL;
405 UINT rawsize = 0, i, j, row_size, row_size_mem;
407 TRACE("%s\n",debugstr_w(t->name));
409 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
410 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
412 /* if we can't read the table, just assume that it's empty */
413 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
414 if( !rawdata )
415 return ERROR_SUCCESS;
417 TRACE("Read %d bytes\n", rawsize );
419 if( rawsize % row_size )
421 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
422 goto err;
425 t->row_count = rawsize / row_size;
426 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
427 if( !t->data )
428 goto err;
429 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
430 if ( !t->data_persistent )
431 goto err;
433 /* transpose all the data */
434 TRACE("Transposing data from %d rows\n", t->row_count );
435 for (i = 0; i < t->row_count; i++)
437 UINT ofs = 0, ofs_mem = 0;
439 t->data[i] = msi_alloc( row_size_mem );
440 if( !t->data[i] )
441 goto err;
442 t->data_persistent[i] = TRUE;
444 for (j = 0; j < t->col_count; j++)
446 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
447 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
448 UINT k;
450 if ( n != 2 && n != 3 && n != 4 )
452 ERR("oops - unknown column width %d\n", n);
453 goto err;
455 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
457 for (k = 0; k < m; k++)
459 if (k < n)
460 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
461 else
462 t->data[i][ofs_mem + k] = 0;
465 else
467 for (k = 0; k < n; k++)
468 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
470 ofs_mem += m;
471 ofs += n;
475 msi_free( rawdata );
476 return ERROR_SUCCESS;
477 err:
478 msi_free( rawdata );
479 return ERROR_FUNCTION_FAILED;
482 void free_cached_tables( MSIDATABASE *db )
484 while( !list_empty( &db->tables ) )
486 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
488 list_remove( &t->entry );
489 free_table( t );
493 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
495 MSITABLE *t;
497 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
498 if( !strcmpW( name, t->name ) )
499 return t;
501 return NULL;
504 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
506 DWORD i;
508 for (i = 0; colinfo && i < count; i++)
510 assert( i + 1 == colinfo[i].number );
511 if (i) colinfo[i].offset = colinfo[i - 1].offset +
512 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
513 else colinfo[i].offset = 0;
515 TRACE("column %d is [%s] with type %08x ofs %d\n",
516 colinfo[i].number, debugstr_w(colinfo[i].colname),
517 colinfo[i].type, colinfo[i].offset);
521 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
523 const MSICOLUMNINFO *p;
524 DWORD i, n;
526 TRACE("%s\n", debugstr_w(name));
528 if (!strcmpW( name, szTables ))
530 p = _Tables_cols;
531 n = 1;
533 else if (!strcmpW( name, szColumns ))
535 p = _Columns_cols;
536 n = 4;
538 else return ERROR_FUNCTION_FAILED;
540 for (i = 0; i < n; i++)
542 if (colinfo && i < *sz) colinfo[i] = p[i];
543 if (colinfo && i >= *sz) break;
545 table_calc_column_offsets( db, colinfo, n );
546 *sz = n;
547 return ERROR_SUCCESS;
550 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
552 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
554 UINT r, column_count = 0;
555 MSICOLUMNINFO *columns;
557 /* get the number of columns in this table */
558 column_count = 0;
559 r = get_tablecolumns( db, name, NULL, &column_count );
560 if (r != ERROR_SUCCESS)
561 return r;
563 *pcount = column_count;
565 /* if there are no columns, there's no table */
566 if (!column_count)
567 return ERROR_INVALID_PARAMETER;
569 TRACE("table %s found\n", debugstr_w(name));
571 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
572 if (!columns)
573 return ERROR_FUNCTION_FAILED;
575 r = get_tablecolumns( db, name, columns, &column_count );
576 if (r != ERROR_SUCCESS)
578 msi_free( columns );
579 return ERROR_FUNCTION_FAILED;
581 *pcols = columns;
582 return r;
585 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
587 MSITABLE *table;
588 UINT r;
590 /* first, see if the table is cached */
591 table = find_cached_table( db, name );
592 if (table)
594 *table_ret = table;
595 return ERROR_SUCCESS;
598 /* nonexistent tables should be interpreted as empty tables */
599 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
600 if (!table)
601 return ERROR_FUNCTION_FAILED;
603 table->row_count = 0;
604 table->data = NULL;
605 table->data_persistent = NULL;
606 table->colinfo = NULL;
607 table->col_count = 0;
608 table->persistent = MSICONDITION_TRUE;
609 lstrcpyW( table->name, name );
611 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
612 table->persistent = MSICONDITION_NONE;
614 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
615 if (r != ERROR_SUCCESS)
617 free_table( table );
618 return r;
620 r = read_table_from_storage( db, table, db->storage );
621 if (r != ERROR_SUCCESS)
623 free_table( table );
624 return r;
626 list_add_head( &db->tables, &table->entry );
627 *table_ret = table;
628 return ERROR_SUCCESS;
631 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
633 UINT ret = 0, i;
635 for (i = 0; i < bytes; i++)
636 ret += data[row][col + i] << i * 8;
638 return ret;
641 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
643 UINT r, i, n = 0, table_id, count, maxcount = *sz;
644 MSITABLE *table = NULL;
646 TRACE("%s\n", debugstr_w(szTableName));
648 /* first check if there is a default table with that name */
649 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
650 if (r == ERROR_SUCCESS && *sz)
651 return r;
653 r = get_table( db, szColumns, &table );
654 if (r != ERROR_SUCCESS)
656 ERR("couldn't load _Columns table\n");
657 return ERROR_FUNCTION_FAILED;
660 /* convert table and column names to IDs from the string table */
661 r = msi_string2id( db->strings, szTableName, -1, &table_id );
662 if (r != ERROR_SUCCESS)
664 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
665 return r;
667 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
669 /* Note: _Columns table doesn't have non-persistent data */
671 /* if maxcount is non-zero, assume it's exactly right for this table */
672 if (colinfo) memset( colinfo, 0, maxcount * sizeof(*colinfo) );
673 count = table->row_count;
674 for (i = 0; i < count; i++)
676 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
677 if (colinfo)
679 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
680 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
682 /* check the column number is in range */
683 if (col < 1 || col > maxcount)
685 ERR("column %d out of range (maxcount: %d)\n", col, maxcount);
686 continue;
688 /* check if this column was already set */
689 if (colinfo[col - 1].number)
691 ERR("duplicate column %d\n", col);
692 continue;
694 colinfo[col - 1].tablename = msi_string_lookup( db->strings, table_id, NULL );
695 colinfo[col - 1].number = col;
696 colinfo[col - 1].colname = msi_string_lookup( db->strings, id, NULL );
697 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
698 sizeof(USHORT) ) - (1 << 15);
699 colinfo[col - 1].offset = 0;
700 colinfo[col - 1].ref_count = 0;
701 colinfo[col - 1].hash_table = NULL;
703 n++;
705 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
707 if (colinfo && n != maxcount)
709 ERR("missing column in table %s\n", debugstr_w(szTableName));
710 msi_free_colinfo( colinfo, maxcount );
711 return ERROR_FUNCTION_FAILED;
713 table_calc_column_offsets( db, colinfo, n );
714 *sz = n;
715 return ERROR_SUCCESS;
718 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
719 MSICONDITION persistent )
721 enum StringPersistence string_persistence = (persistent) ? StringPersistent : StringNonPersistent;
722 UINT r, nField;
723 MSIVIEW *tv = NULL;
724 MSIRECORD *rec = NULL;
725 column_info *col;
726 MSITABLE *table;
727 UINT i;
729 /* only add tables that don't exist already */
730 if( TABLE_Exists(db, name ) )
732 WARN("table %s exists\n", debugstr_w(name));
733 return ERROR_BAD_QUERY_SYNTAX;
736 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
737 if( !table )
738 return ERROR_FUNCTION_FAILED;
740 table->ref_count = 1;
741 table->row_count = 0;
742 table->data = NULL;
743 table->data_persistent = NULL;
744 table->colinfo = NULL;
745 table->col_count = 0;
746 table->persistent = persistent;
747 lstrcpyW( table->name, name );
749 for( col = col_info; col; col = col->next )
750 table->col_count++;
752 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
753 if (!table->colinfo)
755 free_table( table );
756 return ERROR_FUNCTION_FAILED;
759 for( i = 0, col = col_info; col; i++, col = col->next )
761 UINT table_id = msi_add_string( db->strings, col->table, -1, string_persistence );
762 UINT col_id = msi_add_string( db->strings, col->column, -1, string_persistence );
764 table->colinfo[ i ].tablename = msi_string_lookup( db->strings, table_id, NULL );
765 table->colinfo[ i ].number = i + 1;
766 table->colinfo[ i ].colname = msi_string_lookup( db->strings, col_id, NULL );
767 table->colinfo[ i ].type = col->type;
768 table->colinfo[ i ].offset = 0;
769 table->colinfo[ i ].ref_count = 0;
770 table->colinfo[ i ].hash_table = NULL;
771 table->colinfo[ i ].temporary = col->temporary;
773 table_calc_column_offsets( db, table->colinfo, table->col_count);
775 r = TABLE_CreateView( db, szTables, &tv );
776 TRACE("CreateView returned %x\n", r);
777 if( r )
779 free_table( table );
780 return r;
783 r = tv->ops->execute( tv, 0 );
784 TRACE("tv execute returned %x\n", r);
785 if( r )
786 goto err;
788 rec = MSI_CreateRecord( 1 );
789 if( !rec )
790 goto err;
792 r = MSI_RecordSetStringW( rec, 1, name );
793 if( r )
794 goto err;
796 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
797 TRACE("insert_row returned %x\n", r);
798 if( r )
799 goto err;
801 tv->ops->delete( tv );
802 tv = NULL;
804 msiobj_release( &rec->hdr );
805 rec = NULL;
807 if( persistent != MSICONDITION_FALSE )
809 /* add each column to the _Columns table */
810 r = TABLE_CreateView( db, szColumns, &tv );
811 if( r )
812 goto err;
814 r = tv->ops->execute( tv, 0 );
815 TRACE("tv execute returned %x\n", r);
816 if( r )
817 goto err;
819 rec = MSI_CreateRecord( 4 );
820 if( !rec )
821 goto err;
823 r = MSI_RecordSetStringW( rec, 1, name );
824 if( r )
825 goto err;
828 * need to set the table, column number, col name and type
829 * for each column we enter in the table
831 nField = 1;
832 for( col = col_info; col; col = col->next )
834 r = MSI_RecordSetInteger( rec, 2, nField );
835 if( r )
836 goto err;
838 r = MSI_RecordSetStringW( rec, 3, col->column );
839 if( r )
840 goto err;
842 r = MSI_RecordSetInteger( rec, 4, col->type );
843 if( r )
844 goto err;
846 r = tv->ops->insert_row( tv, rec, -1, FALSE );
847 if( r )
848 goto err;
850 nField++;
852 if( !col )
853 r = ERROR_SUCCESS;
856 err:
857 if (rec)
858 msiobj_release( &rec->hdr );
859 /* FIXME: remove values from the string table on error */
860 if( tv )
861 tv->ops->delete( tv );
863 if (r == ERROR_SUCCESS)
864 list_add_head( &db->tables, &table->entry );
865 else
866 free_table( table );
868 return r;
871 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
873 BYTE *rawdata = NULL;
874 UINT rawsize, i, j, row_size, row_count;
875 UINT r = ERROR_FUNCTION_FAILED;
877 /* Nothing to do for non-persistent tables */
878 if( t->persistent == MSICONDITION_FALSE )
879 return ERROR_SUCCESS;
881 TRACE("Saving %s\n", debugstr_w( t->name ) );
883 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
884 row_count = t->row_count;
885 for (i = 0; i < t->row_count; i++)
887 if (!t->data_persistent[i])
889 row_count = 1; /* yes, this is bizarre */
890 break;
893 rawsize = row_count * row_size;
894 rawdata = msi_alloc_zero( rawsize );
895 if( !rawdata )
897 r = ERROR_NOT_ENOUGH_MEMORY;
898 goto err;
901 rawsize = 0;
902 for (i = 0; i < row_count; i++)
904 UINT ofs = 0, ofs_mem = 0;
906 if (!t->data_persistent[i]) break;
908 for (j = 0; j < t->col_count; j++)
910 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
911 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
912 UINT k;
914 if (n != 2 && n != 3 && n != 4)
916 ERR("oops - unknown column width %d\n", n);
917 goto err;
919 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
921 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
922 if (id > 1 << bytes_per_strref * 8)
924 ERR("string id %u out of range\n", id);
925 goto err;
928 for (k = 0; k < n; k++)
930 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
932 ofs_mem += m;
933 ofs += n;
935 rawsize += row_size;
938 TRACE("writing %d bytes\n", rawsize);
939 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
941 err:
942 msi_free( rawdata );
943 return r;
946 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
948 MSITABLE *table;
949 UINT size, offset, old_count;
950 UINT n;
952 if (!(table = find_cached_table( db, name ))) return;
953 old_count = table->col_count;
954 msi_free_colinfo( table->colinfo, table->col_count );
955 msi_free( table->colinfo );
956 table->colinfo = NULL;
958 table_get_column_info( db, name, &table->colinfo, &table->col_count );
959 if (!table->col_count) return;
961 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
962 offset = table->colinfo[table->col_count - 1].offset;
964 for ( n = 0; n < table->row_count; n++ )
966 table->data[n] = msi_realloc( table->data[n], size );
967 if (old_count < table->col_count)
968 memset( &table->data[n][offset], 0, size - offset );
972 /* try to find the table name in the _Tables table */
973 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
975 UINT r, table_id, i;
976 MSITABLE *table;
978 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
979 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
980 return TRUE;
982 r = msi_string2id( db->strings, name, -1, &table_id );
983 if( r != ERROR_SUCCESS )
985 TRACE("Couldn't find id for %s\n", debugstr_w(name));
986 return FALSE;
989 r = get_table( db, szTables, &table );
990 if( r != ERROR_SUCCESS )
992 ERR("table %s not available\n", debugstr_w(szTables));
993 return FALSE;
996 for( i = 0; i < table->row_count; i++ )
998 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
999 return TRUE;
1002 return FALSE;
1005 /* below is the query interface to a table */
1007 typedef struct tagMSITABLEVIEW
1009 MSIVIEW view;
1010 MSIDATABASE *db;
1011 MSITABLE *table;
1012 MSICOLUMNINFO *columns;
1013 UINT num_cols;
1014 UINT row_size;
1015 WCHAR name[1];
1016 } MSITABLEVIEW;
1018 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1020 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1021 UINT offset, n;
1023 if( !tv->table )
1024 return ERROR_INVALID_PARAMETER;
1026 if( (col==0) || (col>tv->num_cols) )
1027 return ERROR_INVALID_PARAMETER;
1029 /* how many rows are there ? */
1030 if( row >= tv->table->row_count )
1031 return ERROR_NO_MORE_ITEMS;
1033 if( tv->columns[col-1].offset >= tv->row_size )
1035 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1036 ERR("%p %p\n", tv, tv->columns );
1037 return ERROR_FUNCTION_FAILED;
1040 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1041 if (n != 2 && n != 3 && n != 4)
1043 ERR("oops! what is %d bytes per column?\n", n );
1044 return ERROR_FUNCTION_FAILED;
1047 offset = tv->columns[col-1].offset;
1048 *val = read_table_int(tv->table->data, row, offset, n);
1050 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1052 return ERROR_SUCCESS;
1055 static UINT get_stream_name( const MSITABLEVIEW *tv, UINT row, WCHAR **pstname )
1057 LPWSTR p, stname = NULL;
1058 UINT i, r, type, ival;
1059 DWORD len;
1060 LPCWSTR sval;
1061 MSIVIEW *view = (MSIVIEW *) tv;
1063 TRACE("%p %d\n", tv, row);
1065 len = lstrlenW( tv->name ) + 1;
1066 stname = msi_alloc( len*sizeof(WCHAR) );
1067 if ( !stname )
1069 r = ERROR_OUTOFMEMORY;
1070 goto err;
1073 lstrcpyW( stname, tv->name );
1075 for ( i = 0; i < tv->num_cols; i++ )
1077 type = tv->columns[i].type;
1078 if ( type & MSITYPE_KEY )
1080 WCHAR number[0x20];
1082 r = TABLE_fetch_int( view, row, i+1, &ival );
1083 if ( r != ERROR_SUCCESS )
1084 goto err;
1086 if ( tv->columns[i].type & MSITYPE_STRING )
1088 sval = msi_string_lookup( tv->db->strings, ival, NULL );
1089 if ( !sval )
1091 r = ERROR_INVALID_PARAMETER;
1092 goto err;
1095 else
1097 static const WCHAR fmt[] = { '%','d',0 };
1098 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1100 switch( n )
1102 case 2:
1103 sprintfW( number, fmt, ival-0x8000 );
1104 break;
1105 case 4:
1106 sprintfW( number, fmt, ival^0x80000000 );
1107 break;
1108 default:
1109 ERR( "oops - unknown column width %d\n", n );
1110 r = ERROR_FUNCTION_FAILED;
1111 goto err;
1113 sval = number;
1116 len += lstrlenW( szDot ) + lstrlenW( sval );
1117 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1118 if ( !p )
1120 r = ERROR_OUTOFMEMORY;
1121 goto err;
1123 stname = p;
1125 lstrcatW( stname, szDot );
1126 lstrcatW( stname, sval );
1128 else
1129 continue;
1132 *pstname = stname;
1133 return ERROR_SUCCESS;
1135 err:
1136 msi_free( stname );
1137 *pstname = NULL;
1138 return r;
1142 * We need a special case for streams, as we need to reference column with
1143 * the name of the stream in the same table, and the table name
1144 * which may not be available at higher levels of the query
1146 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1148 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1149 UINT r;
1150 WCHAR *name;
1152 if( !view->ops->fetch_int )
1153 return ERROR_INVALID_PARAMETER;
1155 r = get_stream_name( tv, row, &name );
1156 if (r != ERROR_SUCCESS)
1158 ERR("fetching stream, error = %u\n", r);
1159 return r;
1162 r = msi_get_stream( tv->db, name, stm );
1163 if (r != ERROR_SUCCESS)
1164 ERR("fetching stream %s, error = %u\n", debugstr_w(name), r);
1166 msi_free( name );
1167 return r;
1170 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1172 UINT offset, n, i;
1174 if( !tv->table )
1175 return ERROR_INVALID_PARAMETER;
1177 if( (col==0) || (col>tv->num_cols) )
1178 return ERROR_INVALID_PARAMETER;
1180 if( row >= tv->table->row_count )
1181 return ERROR_INVALID_PARAMETER;
1183 if( tv->columns[col-1].offset >= tv->row_size )
1185 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1186 ERR("%p %p\n", tv, tv->columns );
1187 return ERROR_FUNCTION_FAILED;
1190 msi_free( tv->columns[col-1].hash_table );
1191 tv->columns[col-1].hash_table = NULL;
1193 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1194 if ( n != 2 && n != 3 && n != 4 )
1196 ERR("oops! what is %d bytes per column?\n", n );
1197 return ERROR_FUNCTION_FAILED;
1200 offset = tv->columns[col-1].offset;
1201 for ( i = 0; i < n; i++ )
1202 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1204 return ERROR_SUCCESS;
1207 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1209 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1211 if (!tv->table)
1212 return ERROR_INVALID_PARAMETER;
1214 return msi_view_get_row(tv->db, view, row, rec);
1217 static UINT add_stream( MSIDATABASE *db, const WCHAR *name, IStream *data )
1219 static const WCHAR insert[] = {
1220 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1221 '`','_','S','t','r','e','a','m','s','`',' ',
1222 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1223 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1224 static const WCHAR update[] = {
1225 'U','P','D','A','T','E',' ','`','_','S','t','r','e','a','m','s','`',' ',
1226 'S','E','T',' ','`','D','a','t','a','`',' ','=',' ','?',' ',
1227 'W','H','E','R','E',' ','`','N','a','m','e','`',' ','=',' ','?',0};
1228 MSIQUERY *query;
1229 MSIRECORD *rec;
1230 UINT r;
1232 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1234 if (!(rec = MSI_CreateRecord( 2 )))
1235 return ERROR_OUTOFMEMORY;
1237 r = MSI_RecordSetStringW( rec, 1, name );
1238 if (r != ERROR_SUCCESS)
1239 goto done;
1241 r = MSI_RecordSetIStream( rec, 2, data );
1242 if (r != ERROR_SUCCESS)
1243 goto done;
1245 r = MSI_DatabaseOpenViewW( db, insert, &query );
1246 if (r != ERROR_SUCCESS)
1247 goto done;
1249 r = MSI_ViewExecute( query, rec );
1250 msiobj_release( &query->hdr );
1251 if (r == ERROR_SUCCESS)
1252 goto done;
1254 msiobj_release( &rec->hdr );
1255 if (!(rec = MSI_CreateRecord( 2 )))
1256 return ERROR_OUTOFMEMORY;
1258 r = MSI_RecordSetIStream( rec, 1, data );
1259 if (r != ERROR_SUCCESS)
1260 goto done;
1262 r = MSI_RecordSetStringW( rec, 2, name );
1263 if (r != ERROR_SUCCESS)
1264 goto done;
1266 r = MSI_DatabaseOpenViewW( db, update, &query );
1267 if (r != ERROR_SUCCESS)
1268 goto done;
1270 r = MSI_ViewExecute( query, rec );
1271 msiobj_release( &query->hdr );
1273 done:
1274 msiobj_release( &rec->hdr );
1275 return r;
1278 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1280 MSICOLUMNINFO columninfo;
1281 UINT r;
1282 int ival;
1284 if ( (iField <= 0) ||
1285 (iField > tv->num_cols) ||
1286 MSI_RecordIsNull( rec, iField ) )
1287 return ERROR_FUNCTION_FAILED;
1289 columninfo = tv->columns[ iField - 1 ];
1291 if ( MSITYPE_IS_BINARY(columninfo.type) )
1293 *pvalue = 1; /* refers to the first key column */
1295 else if ( columninfo.type & MSITYPE_STRING )
1297 int len;
1298 const WCHAR *sval = msi_record_get_string( rec, iField, &len );
1299 if (sval)
1301 r = msi_string2id( tv->db->strings, sval, len, pvalue );
1302 if (r != ERROR_SUCCESS)
1303 return ERROR_NOT_FOUND;
1305 else *pvalue = 0;
1307 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1309 ival = MSI_RecordGetInteger( rec, iField );
1310 if (ival == 0x80000000) *pvalue = 0x8000;
1311 else
1313 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1314 if (*pvalue & 0xffff0000)
1316 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1317 return ERROR_FUNCTION_FAILED;
1321 else
1323 ival = MSI_RecordGetInteger( rec, iField );
1324 *pvalue = ival ^ 0x80000000;
1327 return ERROR_SUCCESS;
1330 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1332 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1333 UINT i, val, r = ERROR_SUCCESS;
1335 if ( !tv->table )
1336 return ERROR_INVALID_PARAMETER;
1338 /* test if any of the mask bits are invalid */
1339 if ( mask >= (1<<tv->num_cols) )
1340 return ERROR_INVALID_PARAMETER;
1342 for ( i = 0; i < tv->num_cols; i++ )
1344 BOOL persistent;
1346 /* only update the fields specified in the mask */
1347 if ( !(mask&(1<<i)) )
1348 continue;
1350 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1351 (tv->table->data_persistent[row]);
1352 /* FIXME: should we allow updating keys? */
1354 val = 0;
1355 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1357 r = get_table_value_from_record (tv, rec, i + 1, &val);
1358 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1360 IStream *stm;
1361 LPWSTR stname;
1363 if ( r != ERROR_SUCCESS )
1364 return ERROR_FUNCTION_FAILED;
1366 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1367 if ( r != ERROR_SUCCESS )
1368 return r;
1370 r = get_stream_name( tv, row, &stname );
1371 if ( r != ERROR_SUCCESS )
1373 IStream_Release( stm );
1374 return r;
1377 r = add_stream( tv->db, stname, stm );
1378 IStream_Release( stm );
1379 msi_free ( stname );
1381 if ( r != ERROR_SUCCESS )
1382 return r;
1384 else if ( tv->columns[i].type & MSITYPE_STRING )
1386 UINT x;
1388 if ( r != ERROR_SUCCESS )
1390 int len;
1391 const WCHAR *sval = msi_record_get_string( rec, i + 1, &len );
1392 val = msi_add_string( tv->db->strings, sval, len,
1393 persistent ? StringPersistent : StringNonPersistent );
1395 else
1397 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1398 if (val == x)
1399 continue;
1402 else
1404 if ( r != ERROR_SUCCESS )
1405 return ERROR_FUNCTION_FAILED;
1409 r = TABLE_set_int( tv, row, i+1, val );
1410 if ( r != ERROR_SUCCESS )
1411 break;
1413 return r;
1416 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1418 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1419 BYTE **p, *row;
1420 BOOL *b;
1421 UINT sz;
1422 BYTE ***data_ptr;
1423 BOOL **data_persist_ptr;
1424 UINT *row_count;
1426 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1428 if( !tv->table )
1429 return ERROR_INVALID_PARAMETER;
1431 row = msi_alloc_zero( tv->row_size );
1432 if( !row )
1433 return ERROR_NOT_ENOUGH_MEMORY;
1435 row_count = &tv->table->row_count;
1436 data_ptr = &tv->table->data;
1437 data_persist_ptr = &tv->table->data_persistent;
1438 if (*num == -1)
1439 *num = tv->table->row_count;
1441 sz = (*row_count + 1) * sizeof (BYTE*);
1442 if( *data_ptr )
1443 p = msi_realloc( *data_ptr, sz );
1444 else
1445 p = msi_alloc( sz );
1446 if( !p )
1448 msi_free( row );
1449 return ERROR_NOT_ENOUGH_MEMORY;
1452 sz = (*row_count + 1) * sizeof (BOOL);
1453 if( *data_persist_ptr )
1454 b = msi_realloc( *data_persist_ptr, sz );
1455 else
1456 b = msi_alloc( sz );
1457 if( !b )
1459 msi_free( row );
1460 msi_free( p );
1461 return ERROR_NOT_ENOUGH_MEMORY;
1464 *data_ptr = p;
1465 (*data_ptr)[*row_count] = row;
1467 *data_persist_ptr = b;
1468 (*data_persist_ptr)[*row_count] = !temporary;
1470 (*row_count)++;
1472 return ERROR_SUCCESS;
1475 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1477 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1479 TRACE("%p %p\n", tv, record);
1481 TRACE("There are %d columns\n", tv->num_cols );
1483 return ERROR_SUCCESS;
1486 static UINT TABLE_close( struct tagMSIVIEW *view )
1488 TRACE("%p\n", view );
1490 return ERROR_SUCCESS;
1493 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1495 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1497 TRACE("%p %p %p\n", view, rows, cols );
1499 if( cols )
1500 *cols = tv->num_cols;
1501 if( rows )
1503 if( !tv->table )
1504 return ERROR_INVALID_PARAMETER;
1505 *rows = tv->table->row_count;
1508 return ERROR_SUCCESS;
1511 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1512 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1513 LPCWSTR *table_name )
1515 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1517 TRACE("%p %d %p %p\n", tv, n, name, type );
1519 if( ( n == 0 ) || ( n > tv->num_cols ) )
1520 return ERROR_INVALID_PARAMETER;
1522 if( name )
1524 *name = tv->columns[n-1].colname;
1525 if( !*name )
1526 return ERROR_FUNCTION_FAILED;
1529 if( table_name )
1531 *table_name = tv->columns[n-1].tablename;
1532 if( !*table_name )
1533 return ERROR_FUNCTION_FAILED;
1536 if( type )
1537 *type = tv->columns[n-1].type;
1539 if( temporary )
1540 *temporary = tv->columns[n-1].temporary;
1542 return ERROR_SUCCESS;
1545 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1547 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1549 UINT r, row, i;
1551 /* check there are no null values where they're not allowed */
1552 for( i = 0; i < tv->num_cols; i++ )
1554 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1555 continue;
1557 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1558 TRACE("skipping binary column\n");
1559 else if ( tv->columns[i].type & MSITYPE_STRING )
1561 int len;
1562 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
1564 if (!str || (!str[0] && !len))
1566 if (column) *column = i;
1567 return ERROR_INVALID_DATA;
1570 else
1572 UINT n;
1574 n = MSI_RecordGetInteger( rec, i+1 );
1575 if (n == MSI_NULL_INTEGER)
1577 if (column) *column = i;
1578 return ERROR_INVALID_DATA;
1583 /* check there are no duplicate keys */
1584 r = msi_table_find_row( tv, rec, &row, column );
1585 if (r == ERROR_SUCCESS)
1586 return ERROR_FUNCTION_FAILED;
1588 return ERROR_SUCCESS;
1591 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1593 UINT r, i, ivalue, x;
1595 for (i = 0; i < tv->num_cols; i++ )
1597 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1599 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1600 if (r != ERROR_SUCCESS)
1601 return 1;
1603 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1604 if (r != ERROR_SUCCESS)
1606 WARN("TABLE_fetch_int should not fail here %u\n", r);
1607 return -1;
1609 if (ivalue > x)
1611 return 1;
1613 else if (ivalue == x)
1615 if (i < tv->num_cols - 1) continue;
1616 return 0;
1618 else
1619 return -1;
1621 return 1;
1624 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1626 int idx, c, low = 0, high = tv->table->row_count - 1;
1628 TRACE("%p %p\n", tv, rec);
1630 while (low <= high)
1632 idx = (low + high) / 2;
1633 c = compare_record( tv, idx, rec );
1635 if (c < 0)
1636 high = idx - 1;
1637 else if (c > 0)
1638 low = idx + 1;
1639 else
1641 TRACE("found %u\n", idx);
1642 return idx;
1645 TRACE("found %u\n", high + 1);
1646 return high + 1;
1649 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1651 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1652 UINT i, r;
1654 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1656 /* check that the key is unique - can we find a matching row? */
1657 r = table_validate_new( tv, rec, NULL );
1658 if( r != ERROR_SUCCESS )
1659 return ERROR_FUNCTION_FAILED;
1661 if (row == -1)
1662 row = find_insert_index( tv, rec );
1664 r = table_create_new_row( view, &row, temporary );
1665 TRACE("insert_row returned %08x\n", r);
1666 if( r != ERROR_SUCCESS )
1667 return r;
1669 /* shift the rows to make room for the new row */
1670 for (i = tv->table->row_count - 1; i > row; i--)
1672 memmove(&(tv->table->data[i][0]),
1673 &(tv->table->data[i - 1][0]), tv->row_size);
1674 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1677 /* Re-set the persistence flag */
1678 tv->table->data_persistent[row] = !temporary;
1679 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1682 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1684 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1685 UINT r, num_rows, num_cols, i;
1687 TRACE("%p %d\n", tv, row);
1689 if ( !tv->table )
1690 return ERROR_INVALID_PARAMETER;
1692 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1693 if ( r != ERROR_SUCCESS )
1694 return r;
1696 if ( row >= num_rows )
1697 return ERROR_FUNCTION_FAILED;
1699 num_rows = tv->table->row_count;
1700 tv->table->row_count--;
1702 /* reset the hash tables */
1703 for (i = 0; i < tv->num_cols; i++)
1705 msi_free( tv->columns[i].hash_table );
1706 tv->columns[i].hash_table = NULL;
1709 for (i = row + 1; i < num_rows; i++)
1711 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1712 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1715 msi_free(tv->table->data[num_rows - 1]);
1717 return ERROR_SUCCESS;
1720 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1722 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1723 UINT r, new_row;
1725 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1726 * sets the fetched record apart from other records
1729 if (!tv->table)
1730 return ERROR_INVALID_PARAMETER;
1732 r = msi_table_find_row(tv, rec, &new_row, NULL);
1733 if (r != ERROR_SUCCESS)
1735 ERR("can't find row to modify\n");
1736 return ERROR_FUNCTION_FAILED;
1739 /* the row cannot be changed */
1740 if (row != new_row + 1)
1741 return ERROR_FUNCTION_FAILED;
1743 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1746 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1748 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1749 UINT r, row;
1751 if (!tv->table)
1752 return ERROR_INVALID_PARAMETER;
1754 r = msi_table_find_row(tv, rec, &row, NULL);
1755 if (r == ERROR_SUCCESS)
1756 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1757 else
1758 return TABLE_insert_row( view, rec, -1, FALSE );
1761 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1763 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1764 UINT row, r;
1766 r = msi_table_find_row(tv, rec, &row, NULL);
1767 if (r != ERROR_SUCCESS)
1768 return r;
1770 return TABLE_delete_row(view, row);
1773 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1775 MSIRECORD *curr;
1776 UINT r, i, count;
1778 r = TABLE_get_row(view, row - 1, &curr);
1779 if (r != ERROR_SUCCESS)
1780 return r;
1782 /* Close the original record */
1783 MSI_CloseRecord(&rec->hdr);
1785 count = MSI_RecordGetFieldCount(rec);
1786 for (i = 0; i < count; i++)
1787 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1789 msiobj_release(&curr->hdr);
1790 return ERROR_SUCCESS;
1793 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1794 MSIRECORD *rec, UINT row)
1796 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1797 UINT r, frow, column;
1799 TRACE("%p %d %p\n", view, eModifyMode, rec );
1801 switch (eModifyMode)
1803 case MSIMODIFY_DELETE:
1804 r = modify_delete_row( view, rec );
1805 break;
1806 case MSIMODIFY_VALIDATE_NEW:
1807 r = table_validate_new( tv, rec, &column );
1808 if (r != ERROR_SUCCESS)
1810 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1811 tv->view.error_column = tv->columns[column].colname;
1812 r = ERROR_INVALID_DATA;
1814 break;
1816 case MSIMODIFY_INSERT:
1817 r = table_validate_new( tv, rec, NULL );
1818 if (r != ERROR_SUCCESS)
1819 break;
1820 r = TABLE_insert_row( view, rec, -1, FALSE );
1821 break;
1823 case MSIMODIFY_INSERT_TEMPORARY:
1824 r = table_validate_new( tv, rec, NULL );
1825 if (r != ERROR_SUCCESS)
1826 break;
1827 r = TABLE_insert_row( view, rec, -1, TRUE );
1828 break;
1830 case MSIMODIFY_REFRESH:
1831 r = msi_refresh_record( view, rec, row );
1832 break;
1834 case MSIMODIFY_UPDATE:
1835 r = msi_table_update( view, rec, row );
1836 break;
1838 case MSIMODIFY_ASSIGN:
1839 r = msi_table_assign( view, rec );
1840 break;
1842 case MSIMODIFY_MERGE:
1843 /* check row that matches this record */
1844 r = msi_table_find_row( tv, rec, &frow, &column );
1845 if (r != ERROR_SUCCESS)
1847 r = table_validate_new( tv, rec, NULL );
1848 if (r == ERROR_SUCCESS)
1849 r = TABLE_insert_row( view, rec, -1, FALSE );
1851 break;
1853 case MSIMODIFY_REPLACE:
1854 case MSIMODIFY_VALIDATE:
1855 case MSIMODIFY_VALIDATE_FIELD:
1856 case MSIMODIFY_VALIDATE_DELETE:
1857 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1858 r = ERROR_CALL_NOT_IMPLEMENTED;
1859 break;
1861 default:
1862 r = ERROR_INVALID_DATA;
1865 return r;
1868 static UINT TABLE_delete( struct tagMSIVIEW *view )
1870 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1872 TRACE("%p\n", view );
1874 tv->table = NULL;
1875 tv->columns = NULL;
1877 msi_free( tv );
1879 return ERROR_SUCCESS;
1882 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1883 UINT val, UINT *row, MSIITERHANDLE *handle )
1885 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1886 const MSICOLUMNHASHENTRY *entry;
1888 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1890 if( !tv->table )
1891 return ERROR_INVALID_PARAMETER;
1893 if( (col==0) || (col > tv->num_cols) )
1894 return ERROR_INVALID_PARAMETER;
1896 if( !tv->columns[col-1].hash_table )
1898 UINT i;
1899 UINT num_rows = tv->table->row_count;
1900 MSICOLUMNHASHENTRY **hash_table;
1901 MSICOLUMNHASHENTRY *new_entry;
1903 if( tv->columns[col-1].offset >= tv->row_size )
1905 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1906 ERR("%p %p\n", tv, tv->columns );
1907 return ERROR_FUNCTION_FAILED;
1910 /* allocate contiguous memory for the table and its entries so we
1911 * don't have to do an expensive cleanup */
1912 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1913 num_rows * sizeof(MSICOLUMNHASHENTRY));
1914 if (!hash_table)
1915 return ERROR_OUTOFMEMORY;
1917 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1918 tv->columns[col-1].hash_table = hash_table;
1920 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1922 for (i = 0; i < num_rows; i++, new_entry++)
1924 UINT row_value;
1926 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1927 continue;
1929 new_entry->next = NULL;
1930 new_entry->value = row_value;
1931 new_entry->row = i;
1932 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1934 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1935 while (prev_entry->next)
1936 prev_entry = prev_entry->next;
1937 prev_entry->next = new_entry;
1939 else
1940 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1944 if( !*handle )
1945 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1946 else
1947 entry = (*handle)->next;
1949 while (entry && entry->value != val)
1950 entry = entry->next;
1952 *handle = entry;
1953 if (!entry)
1954 return ERROR_NO_MORE_ITEMS;
1956 *row = entry->row;
1958 return ERROR_SUCCESS;
1961 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1963 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1964 UINT i;
1966 TRACE("%p %d\n", view, tv->table->ref_count);
1968 for (i = 0; i < tv->table->col_count; i++)
1970 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1971 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1974 return InterlockedIncrement(&tv->table->ref_count);
1977 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1979 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1980 MSIRECORD *rec = NULL;
1981 MSIVIEW *columns = NULL;
1982 UINT row, r;
1984 rec = MSI_CreateRecord(2);
1985 if (!rec)
1986 return ERROR_OUTOFMEMORY;
1988 MSI_RecordSetStringW(rec, 1, table);
1989 MSI_RecordSetInteger(rec, 2, number);
1991 r = TABLE_CreateView(tv->db, szColumns, &columns);
1992 if (r != ERROR_SUCCESS)
1994 msiobj_release(&rec->hdr);
1995 return r;
1998 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1999 if (r != ERROR_SUCCESS)
2000 goto done;
2002 r = TABLE_delete_row(columns, row);
2003 if (r != ERROR_SUCCESS)
2004 goto done;
2006 msi_update_table_columns(tv->db, table);
2008 done:
2009 msiobj_release(&rec->hdr);
2010 columns->ops->delete(columns);
2011 return r;
2014 static UINT TABLE_release(struct tagMSIVIEW *view)
2016 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2017 INT ref = tv->table->ref_count;
2018 UINT i, r;
2020 TRACE("%p %d\n", view, ref);
2022 for (i = 0; i < tv->table->col_count; i++)
2024 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2026 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2027 if (ref == 0)
2029 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2030 tv->table->colinfo[i].number);
2031 if (r != ERROR_SUCCESS)
2032 break;
2037 ref = InterlockedDecrement(&tv->table->ref_count);
2038 if (ref == 0)
2040 if (!tv->table->row_count)
2042 list_remove(&tv->table->entry);
2043 free_table(tv->table);
2044 TABLE_delete(view);
2048 return ref;
2051 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2052 LPCWSTR column, UINT type, BOOL hold)
2054 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2055 MSITABLE *msitable;
2056 MSIRECORD *rec;
2057 UINT r, i;
2059 rec = MSI_CreateRecord(4);
2060 if (!rec)
2061 return ERROR_OUTOFMEMORY;
2063 MSI_RecordSetStringW(rec, 1, table);
2064 MSI_RecordSetInteger(rec, 2, number);
2065 MSI_RecordSetStringW(rec, 3, column);
2066 MSI_RecordSetInteger(rec, 4, type);
2068 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2069 if (r != ERROR_SUCCESS)
2070 goto done;
2072 msi_update_table_columns(tv->db, table);
2074 if (!hold)
2075 goto done;
2077 msitable = find_cached_table(tv->db, table);
2078 for (i = 0; i < msitable->col_count; i++)
2080 if (!strcmpW( msitable->colinfo[i].colname, column ))
2082 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2083 break;
2087 done:
2088 msiobj_release(&rec->hdr);
2089 return r;
2092 static UINT TABLE_drop(struct tagMSIVIEW *view)
2094 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2095 MSIVIEW *tables = NULL;
2096 MSIRECORD *rec = NULL;
2097 UINT r, row;
2098 INT i;
2100 TRACE("dropping table %s\n", debugstr_w(tv->name));
2102 for (i = tv->table->col_count - 1; i >= 0; i--)
2104 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2105 tv->table->colinfo[i].number);
2106 if (r != ERROR_SUCCESS)
2107 return r;
2110 rec = MSI_CreateRecord(1);
2111 if (!rec)
2112 return ERROR_OUTOFMEMORY;
2114 MSI_RecordSetStringW(rec, 1, tv->name);
2116 r = TABLE_CreateView(tv->db, szTables, &tables);
2117 if (r != ERROR_SUCCESS)
2119 msiobj_release(&rec->hdr);
2120 return r;
2123 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2124 if (r != ERROR_SUCCESS)
2125 goto done;
2127 r = TABLE_delete_row(tables, row);
2128 if (r != ERROR_SUCCESS)
2129 goto done;
2131 list_remove(&tv->table->entry);
2132 free_table(tv->table);
2134 done:
2135 msiobj_release(&rec->hdr);
2136 tables->ops->delete(tables);
2138 return r;
2141 static const MSIVIEWOPS table_ops =
2143 TABLE_fetch_int,
2144 TABLE_fetch_stream,
2145 TABLE_get_row,
2146 TABLE_set_row,
2147 TABLE_insert_row,
2148 TABLE_delete_row,
2149 TABLE_execute,
2150 TABLE_close,
2151 TABLE_get_dimensions,
2152 TABLE_get_column_info,
2153 TABLE_modify,
2154 TABLE_delete,
2155 TABLE_find_matching_rows,
2156 TABLE_add_ref,
2157 TABLE_release,
2158 TABLE_add_column,
2159 TABLE_remove_column,
2160 NULL,
2161 TABLE_drop,
2164 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2166 MSITABLEVIEW *tv ;
2167 UINT r, sz;
2169 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2171 if ( !strcmpW( name, szStreams ) )
2172 return STREAMS_CreateView( db, view );
2173 else if ( !strcmpW( name, szStorages ) )
2174 return STORAGES_CreateView( db, view );
2176 sz = FIELD_OFFSET( MSITABLEVIEW, name[lstrlenW( name ) + 1] );
2177 tv = msi_alloc_zero( sz );
2178 if( !tv )
2179 return ERROR_FUNCTION_FAILED;
2181 r = get_table( db, name, &tv->table );
2182 if( r != ERROR_SUCCESS )
2184 msi_free( tv );
2185 WARN("table not found\n");
2186 return r;
2189 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2191 /* fill the structure */
2192 tv->view.ops = &table_ops;
2193 tv->db = db;
2194 tv->columns = tv->table->colinfo;
2195 tv->num_cols = tv->table->col_count;
2196 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2198 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2200 *view = (MSIVIEW*) tv;
2201 lstrcpyW( tv->name, name );
2203 return ERROR_SUCCESS;
2206 UINT MSI_CommitTables( MSIDATABASE *db )
2208 UINT r, bytes_per_strref;
2209 HRESULT hr;
2210 MSITABLE *table = NULL;
2212 TRACE("%p\n",db);
2214 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2215 if( r != ERROR_SUCCESS )
2217 WARN("failed to save string table r=%08x\n",r);
2218 return r;
2221 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2223 r = save_table( db, table, bytes_per_strref );
2224 if( r != ERROR_SUCCESS )
2226 WARN("failed to save table %s (r=%08x)\n",
2227 debugstr_w(table->name), r);
2228 return r;
2232 hr = IStorage_Commit( db->storage, 0 );
2233 if (FAILED( hr ))
2235 WARN("failed to commit changes 0x%08x\n", hr);
2236 r = ERROR_FUNCTION_FAILED;
2238 return r;
2241 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2243 MSITABLE *t;
2244 UINT r;
2246 TRACE("%p %s\n", db, debugstr_w(table));
2248 if (!table)
2249 return MSICONDITION_ERROR;
2251 r = get_table( db, table, &t );
2252 if (r != ERROR_SUCCESS)
2253 return MSICONDITION_NONE;
2255 return t->persistent;
2258 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2260 UINT ret = 0, i;
2262 for (i = 0; i < bytes; i++)
2263 ret += (data[col + i] << i * 8);
2265 return ret;
2268 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2270 LPWSTR stname = NULL, sval, p;
2271 DWORD len;
2272 UINT i, r;
2274 TRACE("%p %p\n", tv, rec);
2276 len = lstrlenW( tv->name ) + 1;
2277 stname = msi_alloc( len*sizeof(WCHAR) );
2278 if ( !stname )
2280 r = ERROR_OUTOFMEMORY;
2281 goto err;
2284 lstrcpyW( stname, tv->name );
2286 for ( i = 0; i < tv->num_cols; i++ )
2288 if ( tv->columns[i].type & MSITYPE_KEY )
2290 sval = msi_dup_record_field( rec, i + 1 );
2291 if ( !sval )
2293 r = ERROR_OUTOFMEMORY;
2294 goto err;
2297 len += lstrlenW( szDot ) + lstrlenW ( sval );
2298 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2299 if ( !p )
2301 r = ERROR_OUTOFMEMORY;
2302 msi_free(sval);
2303 goto err;
2305 stname = p;
2307 lstrcatW( stname, szDot );
2308 lstrcatW( stname, sval );
2310 msi_free( sval );
2312 else
2313 continue;
2316 *pstname = encode_streamname( FALSE, stname );
2317 msi_free( stname );
2319 return ERROR_SUCCESS;
2321 err:
2322 msi_free ( stname );
2323 *pstname = NULL;
2324 return r;
2327 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2328 IStorage *stg, const BYTE *rawdata, UINT bytes_per_strref )
2330 UINT i, val, ofs = 0;
2331 USHORT mask;
2332 MSICOLUMNINFO *columns = tv->columns;
2333 MSIRECORD *rec;
2335 mask = rawdata[0] | (rawdata[1] << 8);
2336 rawdata += 2;
2338 rec = MSI_CreateRecord( tv->num_cols );
2339 if( !rec )
2340 return rec;
2342 TRACE("row ->\n");
2343 for( i=0; i<tv->num_cols; i++ )
2345 if ( (mask&1) && (i>=(mask>>8)) )
2346 break;
2347 /* all keys must be present */
2348 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2349 continue;
2351 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2353 LPWSTR encname;
2354 IStream *stm = NULL;
2355 UINT r;
2357 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2359 r = msi_record_encoded_stream_name( tv, rec, &encname );
2360 if ( r != ERROR_SUCCESS )
2362 msiobj_release( &rec->hdr );
2363 return NULL;
2365 r = IStorage_OpenStream( stg, encname, NULL, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2366 if ( r != ERROR_SUCCESS )
2368 msiobj_release( &rec->hdr );
2369 msi_free( encname );
2370 return NULL;
2373 MSI_RecordSetStream( rec, i+1, stm );
2374 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2375 msi_free( encname );
2377 else if( columns[i].type & MSITYPE_STRING )
2379 int len;
2380 const WCHAR *sval;
2382 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2383 sval = msi_string_lookup( st, val, &len );
2384 msi_record_set_string( rec, i+1, sval, len );
2385 TRACE(" field %d [%s]\n", i+1, debugstr_wn(sval, len));
2386 ofs += bytes_per_strref;
2388 else
2390 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2391 switch( n )
2393 case 2:
2394 val = read_raw_int(rawdata, ofs, n);
2395 if (val)
2396 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2397 TRACE(" field %d [0x%04x]\n", i+1, val );
2398 break;
2399 case 4:
2400 val = read_raw_int(rawdata, ofs, n);
2401 if (val)
2402 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2403 TRACE(" field %d [0x%08x]\n", i+1, val );
2404 break;
2405 default:
2406 ERR("oops - unknown column width %d\n", n);
2407 break;
2409 ofs += n;
2412 return rec;
2415 static void dump_record( MSIRECORD *rec )
2417 UINT i, n;
2419 n = MSI_RecordGetFieldCount( rec );
2420 for( i=1; i<=n; i++ )
2422 int len;
2423 const WCHAR *sval;
2425 if( MSI_RecordIsNull( rec, i ) )
2426 TRACE("row -> []\n");
2427 else if( (sval = msi_record_get_string( rec, i, &len )) )
2428 TRACE("row -> [%s]\n", debugstr_wn(sval, len));
2429 else
2430 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2434 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2436 UINT i;
2437 for (i = 0; i < rawsize / 2; i++)
2439 int len;
2440 const WCHAR *sval = msi_string_lookup( st, rawdata[i], &len );
2441 MESSAGE(" %04x %s\n", rawdata[i], debugstr_wn(sval, len) );
2445 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2447 UINT i, r, *data;
2449 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2450 for( i=0; i<tv->num_cols; i++ )
2452 data[i] = 0;
2454 if ( ~tv->columns[i].type & MSITYPE_KEY )
2455 continue;
2457 /* turn the transform column value into a row value */
2458 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2459 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2461 int len;
2462 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
2463 if (str)
2465 r = msi_string2id( tv->db->strings, str, len, &data[i] );
2467 /* if there's no matching string in the string table,
2468 these keys can't match any record, so fail now. */
2469 if (r != ERROR_SUCCESS)
2471 msi_free( data );
2472 return NULL;
2475 else data[i] = 0;
2477 else
2479 data[i] = MSI_RecordGetInteger( rec, i+1 );
2481 if (data[i] == MSI_NULL_INTEGER)
2482 data[i] = 0;
2483 else if ((tv->columns[i].type&0xff) == 2)
2484 data[i] += 0x8000;
2485 else
2486 data[i] += 0x80000000;
2489 return data;
2492 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2494 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2496 for( i=0; i<tv->num_cols; i++ )
2498 if ( ~tv->columns[i].type & MSITYPE_KEY )
2499 continue;
2501 /* turn the transform column value into a row value */
2502 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2503 if ( r != ERROR_SUCCESS )
2505 ERR("TABLE_fetch_int shouldn't fail here\n");
2506 break;
2509 /* if this key matches, move to the next column */
2510 if ( x != data[i] )
2512 ret = ERROR_FUNCTION_FAILED;
2513 break;
2515 if (column) *column = i;
2516 ret = ERROR_SUCCESS;
2518 return ret;
2521 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2523 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2525 data = msi_record_to_row( tv, rec );
2526 if( !data )
2527 return r;
2528 for( i = 0; i < tv->table->row_count; i++ )
2530 r = msi_row_matches( tv, i, data, column );
2531 if( r == ERROR_SUCCESS )
2533 *row = i;
2534 break;
2537 msi_free( data );
2538 return r;
2541 typedef struct
2543 struct list entry;
2544 LPWSTR name;
2545 } TRANSFORMDATA;
2547 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2548 string_table *st, TRANSFORMDATA *transform,
2549 UINT bytes_per_strref )
2551 BYTE *rawdata = NULL;
2552 MSITABLEVIEW *tv = NULL;
2553 UINT r, n, sz, i, mask, num_cols, colcol = 0, rawsize = 0;
2554 MSIRECORD *rec = NULL;
2555 WCHAR coltable[32];
2556 const WCHAR *name;
2558 if (!transform)
2559 return ERROR_SUCCESS;
2561 name = transform->name;
2563 coltable[0] = 0;
2564 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2566 /* read the transform data */
2567 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2568 if ( !rawdata )
2570 TRACE("table %s empty\n", debugstr_w(name) );
2571 return ERROR_INVALID_TABLE;
2574 /* create a table view */
2575 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2576 if( r != ERROR_SUCCESS )
2577 goto err;
2579 r = tv->view.ops->execute( &tv->view, NULL );
2580 if( r != ERROR_SUCCESS )
2581 goto err;
2583 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2584 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2586 /* interpret the data */
2587 for (n = 0; n < rawsize;)
2589 mask = rawdata[n] | (rawdata[n + 1] << 8);
2590 if (mask & 1)
2593 * if the low bit is set, columns are continuous and
2594 * the number of columns is specified in the high byte
2596 sz = 2;
2597 num_cols = mask >> 8;
2598 if (num_cols > tv->num_cols)
2600 ERR("excess columns in transform: %u > %u\n", num_cols, tv->num_cols);
2601 break;
2604 for (i = 0; i < num_cols; i++)
2606 if( (tv->columns[i].type & MSITYPE_STRING) &&
2607 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2608 sz += bytes_per_strref;
2609 else
2610 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2613 else
2616 * If the low bit is not set, mask is a bitmask.
2617 * Excepting for key fields, which are always present,
2618 * each bit indicates that a field is present in the transform record.
2620 * mask == 0 is a special case ... only the keys will be present
2621 * and it means that this row should be deleted.
2623 sz = 2;
2624 num_cols = tv->num_cols;
2625 for (i = 0; i < num_cols; i++)
2627 if ((tv->columns[i].type & MSITYPE_KEY) || ((1 << i) & mask))
2629 if ((tv->columns[i].type & MSITYPE_STRING) &&
2630 !MSITYPE_IS_BINARY(tv->columns[i].type))
2631 sz += bytes_per_strref;
2632 else
2633 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2638 /* check we didn't run of the end of the table */
2639 if (n + sz > rawsize)
2641 ERR("borked.\n");
2642 dump_table( st, (USHORT *)rawdata, rawsize );
2643 break;
2646 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2647 if (rec)
2649 WCHAR table[32];
2650 DWORD sz = 32;
2651 UINT number = MSI_NULL_INTEGER;
2652 UINT row = 0;
2654 if (!strcmpW( name, szColumns ))
2656 MSI_RecordGetStringW( rec, 1, table, &sz );
2657 number = MSI_RecordGetInteger( rec, 2 );
2660 * Native msi seems writes nul into the Number (2nd) column of
2661 * the _Columns table when there are new columns
2663 if ( number == MSI_NULL_INTEGER )
2665 /* reset the column number on a new table */
2666 if (strcmpW( coltable, table ))
2668 colcol = 0;
2669 lstrcpyW( coltable, table );
2672 /* fix nul column numbers */
2673 MSI_RecordSetInteger( rec, 2, ++colcol );
2677 if (TRACE_ON(msidb)) dump_record( rec );
2679 r = msi_table_find_row( tv, rec, &row, NULL );
2680 if (r == ERROR_SUCCESS)
2682 if (!mask)
2684 TRACE("deleting row [%d]:\n", row);
2685 r = TABLE_delete_row( &tv->view, row );
2686 if (r != ERROR_SUCCESS)
2687 WARN("failed to delete row %u\n", r);
2689 else if (mask & 1)
2691 TRACE("modifying full row [%d]:\n", row);
2692 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2693 if (r != ERROR_SUCCESS)
2694 WARN("failed to modify row %u\n", r);
2696 else
2698 TRACE("modifying masked row [%d]:\n", row);
2699 r = TABLE_set_row( &tv->view, row, rec, mask );
2700 if (r != ERROR_SUCCESS)
2701 WARN("failed to modify row %u\n", r);
2704 else
2706 TRACE("inserting row\n");
2707 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2708 if (r != ERROR_SUCCESS)
2709 WARN("failed to insert row %u\n", r);
2712 if (!strcmpW( name, szColumns ))
2713 msi_update_table_columns( db, table );
2715 msiobj_release( &rec->hdr );
2718 n += sz;
2721 err:
2722 /* no need to free the table, it's associated with the database */
2723 msi_free( rawdata );
2724 if( tv )
2725 tv->view.ops->delete( &tv->view );
2727 return ERROR_SUCCESS;
2731 * msi_table_apply_transform
2733 * Enumerate the table transforms in a transform storage and apply each one.
2735 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2737 struct list transforms;
2738 IEnumSTATSTG *stgenum = NULL;
2739 TRANSFORMDATA *transform;
2740 TRANSFORMDATA *tables = NULL, *columns = NULL;
2741 HRESULT hr;
2742 STATSTG stat;
2743 string_table *strings;
2744 UINT ret = ERROR_FUNCTION_FAILED;
2745 UINT bytes_per_strref;
2746 BOOL property_update = FALSE;
2748 TRACE("%p %p\n", db, stg );
2750 strings = msi_load_string_table( stg, &bytes_per_strref );
2751 if( !strings )
2752 goto end;
2754 hr = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2755 if (FAILED( hr ))
2756 goto end;
2758 list_init(&transforms);
2760 while ( TRUE )
2762 MSITABLEVIEW *tv = NULL;
2763 WCHAR name[0x40];
2764 ULONG count = 0;
2766 hr = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2767 if (FAILED( hr ) || !count)
2768 break;
2770 decode_streamname( stat.pwcsName, name );
2771 CoTaskMemFree( stat.pwcsName );
2772 if ( name[0] != 0x4840 )
2773 continue;
2775 if ( !strcmpW( name+1, szStringPool ) ||
2776 !strcmpW( name+1, szStringData ) )
2777 continue;
2779 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2780 if ( !transform )
2781 break;
2783 list_add_tail( &transforms, &transform->entry );
2785 transform->name = strdupW( name + 1 );
2787 if ( !strcmpW( transform->name, szTables ) )
2788 tables = transform;
2789 else if (!strcmpW( transform->name, szColumns ) )
2790 columns = transform;
2791 else if (!strcmpW( transform->name, szProperty ))
2792 property_update = TRUE;
2794 TRACE("transform contains stream %s\n", debugstr_w(name));
2796 /* load the table */
2797 if (TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv ) != ERROR_SUCCESS)
2798 continue;
2800 if (tv->view.ops->execute( &tv->view, NULL ) != ERROR_SUCCESS)
2802 tv->view.ops->delete( &tv->view );
2803 continue;
2806 tv->view.ops->delete( &tv->view );
2810 * Apply _Tables and _Columns transforms first so that
2811 * the table metadata is correct, and empty tables exist.
2813 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2814 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2815 goto end;
2817 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2818 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2819 goto end;
2821 ret = ERROR_SUCCESS;
2823 while ( !list_empty( &transforms ) )
2825 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2827 if ( strcmpW( transform->name, szColumns ) &&
2828 strcmpW( transform->name, szTables ) &&
2829 ret == ERROR_SUCCESS )
2831 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2834 list_remove( &transform->entry );
2835 msi_free( transform->name );
2836 msi_free( transform );
2839 if ( ret == ERROR_SUCCESS )
2841 append_storage_to_db( db, stg );
2842 if (property_update) msi_clone_properties( db );
2845 end:
2846 if ( stgenum )
2847 IEnumSTATSTG_Release( stgenum );
2848 if ( strings )
2849 msi_destroy_stringtable( strings );
2851 return ret;