opcservices: Implement IOpcPartEnumerator.
[wine.git] / dlls / msi / table.c
blobe046c5c9e27846ae00620c4fd4f9e6ed4ee712ad
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 if ((t->row_count = rawsize / row_size))
427 if (!(t->data = msi_alloc_zero( t->row_count * sizeof(USHORT *) ))) goto err;
428 if (!(t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL) ))) goto err;
431 /* transpose all the data */
432 TRACE("Transposing data from %d rows\n", t->row_count );
433 for (i = 0; i < t->row_count; i++)
435 UINT ofs = 0, ofs_mem = 0;
437 t->data[i] = msi_alloc( row_size_mem );
438 if( !t->data[i] )
439 goto err;
440 t->data_persistent[i] = TRUE;
442 for (j = 0; j < t->col_count; j++)
444 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
445 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
446 UINT k;
448 if ( n != 2 && n != 3 && n != 4 )
450 ERR("oops - unknown column width %d\n", n);
451 goto err;
453 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
455 for (k = 0; k < m; k++)
457 if (k < n)
458 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
459 else
460 t->data[i][ofs_mem + k] = 0;
463 else
465 for (k = 0; k < n; k++)
466 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
468 ofs_mem += m;
469 ofs += n;
473 msi_free( rawdata );
474 return ERROR_SUCCESS;
475 err:
476 msi_free( rawdata );
477 return ERROR_FUNCTION_FAILED;
480 void free_cached_tables( MSIDATABASE *db )
482 while( !list_empty( &db->tables ) )
484 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
486 list_remove( &t->entry );
487 free_table( t );
491 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
493 MSITABLE *t;
495 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
496 if( !strcmpW( name, t->name ) )
497 return t;
499 return NULL;
502 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
504 DWORD i;
506 for (i = 0; colinfo && i < count; i++)
508 assert( i + 1 == colinfo[i].number );
509 if (i) colinfo[i].offset = colinfo[i - 1].offset +
510 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
511 else colinfo[i].offset = 0;
513 TRACE("column %d is [%s] with type %08x ofs %d\n",
514 colinfo[i].number, debugstr_w(colinfo[i].colname),
515 colinfo[i].type, colinfo[i].offset);
519 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
521 const MSICOLUMNINFO *p;
522 DWORD i, n;
524 TRACE("%s\n", debugstr_w(name));
526 if (!strcmpW( name, szTables ))
528 p = _Tables_cols;
529 n = 1;
531 else if (!strcmpW( name, szColumns ))
533 p = _Columns_cols;
534 n = 4;
536 else return ERROR_FUNCTION_FAILED;
538 for (i = 0; i < n; i++)
540 if (colinfo && i < *sz) colinfo[i] = p[i];
541 if (colinfo && i >= *sz) break;
543 table_calc_column_offsets( db, colinfo, n );
544 *sz = n;
545 return ERROR_SUCCESS;
548 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
550 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
552 UINT r, column_count = 0;
553 MSICOLUMNINFO *columns;
555 /* get the number of columns in this table */
556 column_count = 0;
557 r = get_tablecolumns( db, name, NULL, &column_count );
558 if (r != ERROR_SUCCESS)
559 return r;
561 *pcount = column_count;
563 /* if there are no columns, there's no table */
564 if (!column_count)
565 return ERROR_INVALID_PARAMETER;
567 TRACE("table %s found\n", debugstr_w(name));
569 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
570 if (!columns)
571 return ERROR_FUNCTION_FAILED;
573 r = get_tablecolumns( db, name, columns, &column_count );
574 if (r != ERROR_SUCCESS)
576 msi_free( columns );
577 return ERROR_FUNCTION_FAILED;
579 *pcols = columns;
580 return r;
583 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
585 MSITABLE *table;
586 UINT r;
588 /* first, see if the table is cached */
589 table = find_cached_table( db, name );
590 if (table)
592 *table_ret = table;
593 return ERROR_SUCCESS;
596 /* nonexistent tables should be interpreted as empty tables */
597 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
598 if (!table)
599 return ERROR_FUNCTION_FAILED;
601 table->row_count = 0;
602 table->data = NULL;
603 table->data_persistent = NULL;
604 table->colinfo = NULL;
605 table->col_count = 0;
606 table->persistent = MSICONDITION_TRUE;
607 lstrcpyW( table->name, name );
609 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
610 table->persistent = MSICONDITION_NONE;
612 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
613 if (r != ERROR_SUCCESS)
615 free_table( table );
616 return r;
618 r = read_table_from_storage( db, table, db->storage );
619 if (r != ERROR_SUCCESS)
621 free_table( table );
622 return r;
624 list_add_head( &db->tables, &table->entry );
625 *table_ret = table;
626 return ERROR_SUCCESS;
629 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
631 UINT ret = 0, i;
633 for (i = 0; i < bytes; i++)
634 ret += data[row][col + i] << i * 8;
636 return ret;
639 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
641 UINT r, i, n = 0, table_id, count, maxcount = *sz;
642 MSITABLE *table = NULL;
644 TRACE("%s\n", debugstr_w(szTableName));
646 /* first check if there is a default table with that name */
647 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
648 if (r == ERROR_SUCCESS && *sz)
649 return r;
651 r = get_table( db, szColumns, &table );
652 if (r != ERROR_SUCCESS)
654 ERR("couldn't load _Columns table\n");
655 return ERROR_FUNCTION_FAILED;
658 /* convert table and column names to IDs from the string table */
659 r = msi_string2id( db->strings, szTableName, -1, &table_id );
660 if (r != ERROR_SUCCESS)
662 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
663 return r;
665 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
667 /* Note: _Columns table doesn't have non-persistent data */
669 /* if maxcount is non-zero, assume it's exactly right for this table */
670 if (colinfo) memset( colinfo, 0, maxcount * sizeof(*colinfo) );
671 count = table->row_count;
672 for (i = 0; i < count; i++)
674 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
675 if (colinfo)
677 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
678 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
680 /* check the column number is in range */
681 if (col < 1 || col > maxcount)
683 ERR("column %d out of range (maxcount: %d)\n", col, maxcount);
684 continue;
686 /* check if this column was already set */
687 if (colinfo[col - 1].number)
689 ERR("duplicate column %d\n", col);
690 continue;
692 colinfo[col - 1].tablename = msi_string_lookup( db->strings, table_id, NULL );
693 colinfo[col - 1].number = col;
694 colinfo[col - 1].colname = msi_string_lookup( db->strings, id, NULL );
695 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
696 sizeof(USHORT) ) - (1 << 15);
697 colinfo[col - 1].offset = 0;
698 colinfo[col - 1].ref_count = 0;
699 colinfo[col - 1].hash_table = NULL;
701 n++;
703 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
705 if (colinfo && n != maxcount)
707 ERR("missing column in table %s\n", debugstr_w(szTableName));
708 msi_free_colinfo( colinfo, maxcount );
709 return ERROR_FUNCTION_FAILED;
711 table_calc_column_offsets( db, colinfo, n );
712 *sz = n;
713 return ERROR_SUCCESS;
716 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
717 MSICONDITION persistent )
719 enum StringPersistence string_persistence = (persistent) ? StringPersistent : StringNonPersistent;
720 UINT r, nField;
721 MSIVIEW *tv = NULL;
722 MSIRECORD *rec = NULL;
723 column_info *col;
724 MSITABLE *table;
725 UINT i;
727 /* only add tables that don't exist already */
728 if( TABLE_Exists(db, name ) )
730 WARN("table %s exists\n", debugstr_w(name));
731 return ERROR_BAD_QUERY_SYNTAX;
734 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
735 if( !table )
736 return ERROR_FUNCTION_FAILED;
738 table->ref_count = 1;
739 table->row_count = 0;
740 table->data = NULL;
741 table->data_persistent = NULL;
742 table->colinfo = NULL;
743 table->col_count = 0;
744 table->persistent = persistent;
745 lstrcpyW( table->name, name );
747 for( col = col_info; col; col = col->next )
748 table->col_count++;
750 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
751 if (!table->colinfo)
753 free_table( table );
754 return ERROR_FUNCTION_FAILED;
757 for( i = 0, col = col_info; col; i++, col = col->next )
759 UINT table_id = msi_add_string( db->strings, col->table, -1, string_persistence );
760 UINT col_id = msi_add_string( db->strings, col->column, -1, string_persistence );
762 table->colinfo[ i ].tablename = msi_string_lookup( db->strings, table_id, NULL );
763 table->colinfo[ i ].number = i + 1;
764 table->colinfo[ i ].colname = msi_string_lookup( db->strings, col_id, NULL );
765 table->colinfo[ i ].type = col->type;
766 table->colinfo[ i ].offset = 0;
767 table->colinfo[ i ].ref_count = 0;
768 table->colinfo[ i ].hash_table = NULL;
769 table->colinfo[ i ].temporary = col->temporary;
771 table_calc_column_offsets( db, table->colinfo, table->col_count);
773 r = TABLE_CreateView( db, szTables, &tv );
774 TRACE("CreateView returned %x\n", r);
775 if( r )
777 free_table( table );
778 return r;
781 r = tv->ops->execute( tv, 0 );
782 TRACE("tv execute returned %x\n", r);
783 if( r )
784 goto err;
786 rec = MSI_CreateRecord( 1 );
787 if( !rec )
788 goto err;
790 r = MSI_RecordSetStringW( rec, 1, name );
791 if( r )
792 goto err;
794 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
795 TRACE("insert_row returned %x\n", r);
796 if( r )
797 goto err;
799 tv->ops->delete( tv );
800 tv = NULL;
802 msiobj_release( &rec->hdr );
803 rec = NULL;
805 if( persistent != MSICONDITION_FALSE )
807 /* add each column to the _Columns table */
808 r = TABLE_CreateView( db, szColumns, &tv );
809 if( r )
810 goto err;
812 r = tv->ops->execute( tv, 0 );
813 TRACE("tv execute returned %x\n", r);
814 if( r )
815 goto err;
817 rec = MSI_CreateRecord( 4 );
818 if( !rec )
819 goto err;
821 r = MSI_RecordSetStringW( rec, 1, name );
822 if( r )
823 goto err;
826 * need to set the table, column number, col name and type
827 * for each column we enter in the table
829 nField = 1;
830 for( col = col_info; col; col = col->next )
832 r = MSI_RecordSetInteger( rec, 2, nField );
833 if( r )
834 goto err;
836 r = MSI_RecordSetStringW( rec, 3, col->column );
837 if( r )
838 goto err;
840 r = MSI_RecordSetInteger( rec, 4, col->type );
841 if( r )
842 goto err;
844 r = tv->ops->insert_row( tv, rec, -1, FALSE );
845 if( r )
846 goto err;
848 nField++;
850 if( !col )
851 r = ERROR_SUCCESS;
854 err:
855 if (rec)
856 msiobj_release( &rec->hdr );
857 /* FIXME: remove values from the string table on error */
858 if( tv )
859 tv->ops->delete( tv );
861 if (r == ERROR_SUCCESS)
862 list_add_head( &db->tables, &table->entry );
863 else
864 free_table( table );
866 return r;
869 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
871 BYTE *rawdata = NULL;
872 UINT rawsize, i, j, row_size, row_count;
873 UINT r = ERROR_FUNCTION_FAILED;
875 /* Nothing to do for non-persistent tables */
876 if( t->persistent == MSICONDITION_FALSE )
877 return ERROR_SUCCESS;
879 TRACE("Saving %s\n", debugstr_w( t->name ) );
881 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
882 row_count = t->row_count;
883 for (i = 0; i < t->row_count; i++)
885 if (!t->data_persistent[i])
887 row_count = 1; /* yes, this is bizarre */
888 break;
891 rawsize = row_count * row_size;
892 rawdata = msi_alloc_zero( rawsize );
893 if( !rawdata )
895 r = ERROR_NOT_ENOUGH_MEMORY;
896 goto err;
899 rawsize = 0;
900 for (i = 0; i < row_count; i++)
902 UINT ofs = 0, ofs_mem = 0;
904 if (!t->data_persistent[i]) break;
906 for (j = 0; j < t->col_count; j++)
908 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
909 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
910 UINT k;
912 if (n != 2 && n != 3 && n != 4)
914 ERR("oops - unknown column width %d\n", n);
915 goto err;
917 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
919 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
920 if (id > 1 << bytes_per_strref * 8)
922 ERR("string id %u out of range\n", id);
923 goto err;
926 for (k = 0; k < n; k++)
928 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
930 ofs_mem += m;
931 ofs += n;
933 rawsize += row_size;
936 TRACE("writing %d bytes\n", rawsize);
937 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
939 err:
940 msi_free( rawdata );
941 return r;
944 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
946 MSITABLE *table;
947 UINT size, offset, old_count;
948 UINT n;
950 if (!(table = find_cached_table( db, name ))) return;
951 old_count = table->col_count;
952 msi_free_colinfo( table->colinfo, table->col_count );
953 msi_free( table->colinfo );
954 table->colinfo = NULL;
956 table_get_column_info( db, name, &table->colinfo, &table->col_count );
957 if (!table->col_count) return;
959 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
960 offset = table->colinfo[table->col_count - 1].offset;
962 for ( n = 0; n < table->row_count; n++ )
964 table->data[n] = msi_realloc( table->data[n], size );
965 if (old_count < table->col_count)
966 memset( &table->data[n][offset], 0, size - offset );
970 /* try to find the table name in the _Tables table */
971 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
973 UINT r, table_id, i;
974 MSITABLE *table;
976 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
977 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
978 return TRUE;
980 r = msi_string2id( db->strings, name, -1, &table_id );
981 if( r != ERROR_SUCCESS )
983 TRACE("Couldn't find id for %s\n", debugstr_w(name));
984 return FALSE;
987 r = get_table( db, szTables, &table );
988 if( r != ERROR_SUCCESS )
990 ERR("table %s not available\n", debugstr_w(szTables));
991 return FALSE;
994 for( i = 0; i < table->row_count; i++ )
996 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
997 return TRUE;
1000 return FALSE;
1003 /* below is the query interface to a table */
1005 typedef struct tagMSITABLEVIEW
1007 MSIVIEW view;
1008 MSIDATABASE *db;
1009 MSITABLE *table;
1010 MSICOLUMNINFO *columns;
1011 UINT num_cols;
1012 UINT row_size;
1013 WCHAR name[1];
1014 } MSITABLEVIEW;
1016 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1018 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1019 UINT offset, n;
1021 if( !tv->table )
1022 return ERROR_INVALID_PARAMETER;
1024 if( (col==0) || (col>tv->num_cols) )
1025 return ERROR_INVALID_PARAMETER;
1027 /* how many rows are there ? */
1028 if( row >= tv->table->row_count )
1029 return ERROR_NO_MORE_ITEMS;
1031 if( tv->columns[col-1].offset >= tv->row_size )
1033 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1034 ERR("%p %p\n", tv, tv->columns );
1035 return ERROR_FUNCTION_FAILED;
1038 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1039 if (n != 2 && n != 3 && n != 4)
1041 ERR("oops! what is %d bytes per column?\n", n );
1042 return ERROR_FUNCTION_FAILED;
1045 offset = tv->columns[col-1].offset;
1046 *val = read_table_int(tv->table->data, row, offset, n);
1048 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1050 return ERROR_SUCCESS;
1053 static UINT get_stream_name( const MSITABLEVIEW *tv, UINT row, WCHAR **pstname )
1055 LPWSTR p, stname = NULL;
1056 UINT i, r, type, ival;
1057 DWORD len;
1058 LPCWSTR sval;
1059 MSIVIEW *view = (MSIVIEW *) tv;
1061 TRACE("%p %d\n", tv, row);
1063 len = lstrlenW( tv->name ) + 1;
1064 stname = msi_alloc( len*sizeof(WCHAR) );
1065 if ( !stname )
1067 r = ERROR_OUTOFMEMORY;
1068 goto err;
1071 lstrcpyW( stname, tv->name );
1073 for ( i = 0; i < tv->num_cols; i++ )
1075 type = tv->columns[i].type;
1076 if ( type & MSITYPE_KEY )
1078 WCHAR number[0x20];
1080 r = TABLE_fetch_int( view, row, i+1, &ival );
1081 if ( r != ERROR_SUCCESS )
1082 goto err;
1084 if ( tv->columns[i].type & MSITYPE_STRING )
1086 sval = msi_string_lookup( tv->db->strings, ival, NULL );
1087 if ( !sval )
1089 r = ERROR_INVALID_PARAMETER;
1090 goto err;
1093 else
1095 static const WCHAR fmt[] = { '%','d',0 };
1096 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1098 switch( n )
1100 case 2:
1101 sprintfW( number, fmt, ival-0x8000 );
1102 break;
1103 case 4:
1104 sprintfW( number, fmt, ival^0x80000000 );
1105 break;
1106 default:
1107 ERR( "oops - unknown column width %d\n", n );
1108 r = ERROR_FUNCTION_FAILED;
1109 goto err;
1111 sval = number;
1114 len += lstrlenW( szDot ) + lstrlenW( sval );
1115 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1116 if ( !p )
1118 r = ERROR_OUTOFMEMORY;
1119 goto err;
1121 stname = p;
1123 lstrcatW( stname, szDot );
1124 lstrcatW( stname, sval );
1126 else
1127 continue;
1130 *pstname = stname;
1131 return ERROR_SUCCESS;
1133 err:
1134 msi_free( stname );
1135 *pstname = NULL;
1136 return r;
1140 * We need a special case for streams, as we need to reference column with
1141 * the name of the stream in the same table, and the table name
1142 * which may not be available at higher levels of the query
1144 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1146 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1147 UINT r;
1148 WCHAR *name;
1150 if( !view->ops->fetch_int )
1151 return ERROR_INVALID_PARAMETER;
1153 r = get_stream_name( tv, row, &name );
1154 if (r != ERROR_SUCCESS)
1156 ERR("fetching stream, error = %u\n", r);
1157 return r;
1160 r = msi_get_stream( tv->db, name, stm );
1161 if (r != ERROR_SUCCESS)
1162 ERR("fetching stream %s, error = %u\n", debugstr_w(name), r);
1164 msi_free( name );
1165 return r;
1168 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1170 UINT offset, n, i;
1172 if( !tv->table )
1173 return ERROR_INVALID_PARAMETER;
1175 if( (col==0) || (col>tv->num_cols) )
1176 return ERROR_INVALID_PARAMETER;
1178 if( row >= tv->table->row_count )
1179 return ERROR_INVALID_PARAMETER;
1181 if( tv->columns[col-1].offset >= tv->row_size )
1183 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1184 ERR("%p %p\n", tv, tv->columns );
1185 return ERROR_FUNCTION_FAILED;
1188 msi_free( tv->columns[col-1].hash_table );
1189 tv->columns[col-1].hash_table = NULL;
1191 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1192 if ( n != 2 && n != 3 && n != 4 )
1194 ERR("oops! what is %d bytes per column?\n", n );
1195 return ERROR_FUNCTION_FAILED;
1198 offset = tv->columns[col-1].offset;
1199 for ( i = 0; i < n; i++ )
1200 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1202 return ERROR_SUCCESS;
1205 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1207 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1209 if (!tv->table)
1210 return ERROR_INVALID_PARAMETER;
1212 return msi_view_get_row(tv->db, view, row, rec);
1215 static UINT add_stream( MSIDATABASE *db, const WCHAR *name, IStream *data )
1217 static const WCHAR insert[] = {
1218 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1219 '`','_','S','t','r','e','a','m','s','`',' ',
1220 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1221 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1222 static const WCHAR update[] = {
1223 'U','P','D','A','T','E',' ','`','_','S','t','r','e','a','m','s','`',' ',
1224 'S','E','T',' ','`','D','a','t','a','`',' ','=',' ','?',' ',
1225 'W','H','E','R','E',' ','`','N','a','m','e','`',' ','=',' ','?',0};
1226 MSIQUERY *query;
1227 MSIRECORD *rec;
1228 UINT r;
1230 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1232 if (!(rec = MSI_CreateRecord( 2 )))
1233 return ERROR_OUTOFMEMORY;
1235 r = MSI_RecordSetStringW( rec, 1, name );
1236 if (r != ERROR_SUCCESS)
1237 goto done;
1239 r = MSI_RecordSetIStream( rec, 2, data );
1240 if (r != ERROR_SUCCESS)
1241 goto done;
1243 r = MSI_DatabaseOpenViewW( db, insert, &query );
1244 if (r != ERROR_SUCCESS)
1245 goto done;
1247 r = MSI_ViewExecute( query, rec );
1248 msiobj_release( &query->hdr );
1249 if (r == ERROR_SUCCESS)
1250 goto done;
1252 msiobj_release( &rec->hdr );
1253 if (!(rec = MSI_CreateRecord( 2 )))
1254 return ERROR_OUTOFMEMORY;
1256 r = MSI_RecordSetIStream( rec, 1, data );
1257 if (r != ERROR_SUCCESS)
1258 goto done;
1260 r = MSI_RecordSetStringW( rec, 2, name );
1261 if (r != ERROR_SUCCESS)
1262 goto done;
1264 r = MSI_DatabaseOpenViewW( db, update, &query );
1265 if (r != ERROR_SUCCESS)
1266 goto done;
1268 r = MSI_ViewExecute( query, rec );
1269 msiobj_release( &query->hdr );
1271 done:
1272 msiobj_release( &rec->hdr );
1273 return r;
1276 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1278 MSICOLUMNINFO columninfo;
1279 UINT r;
1280 int ival;
1282 if (!iField || iField > tv->num_cols || MSI_RecordIsNull( rec, iField ))
1283 return ERROR_FUNCTION_FAILED;
1285 columninfo = tv->columns[ iField - 1 ];
1287 if ( MSITYPE_IS_BINARY(columninfo.type) )
1289 *pvalue = 1; /* refers to the first key column */
1291 else if ( columninfo.type & MSITYPE_STRING )
1293 int len;
1294 const WCHAR *sval = msi_record_get_string( rec, iField, &len );
1295 if (sval)
1297 r = msi_string2id( tv->db->strings, sval, len, pvalue );
1298 if (r != ERROR_SUCCESS)
1299 return ERROR_NOT_FOUND;
1301 else *pvalue = 0;
1303 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1305 ival = MSI_RecordGetInteger( rec, iField );
1306 if (ival == 0x80000000) *pvalue = 0x8000;
1307 else
1309 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1310 if (*pvalue & 0xffff0000)
1312 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1313 return ERROR_FUNCTION_FAILED;
1317 else
1319 ival = MSI_RecordGetInteger( rec, iField );
1320 *pvalue = ival ^ 0x80000000;
1323 return ERROR_SUCCESS;
1326 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1328 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1329 UINT i, val, r = ERROR_SUCCESS;
1331 if ( !tv->table )
1332 return ERROR_INVALID_PARAMETER;
1334 /* test if any of the mask bits are invalid */
1335 if ( mask >= (1<<tv->num_cols) )
1336 return ERROR_INVALID_PARAMETER;
1338 for ( i = 0; i < tv->num_cols; i++ )
1340 BOOL persistent;
1342 /* only update the fields specified in the mask */
1343 if ( !(mask&(1<<i)) )
1344 continue;
1346 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1347 (tv->table->data_persistent[row]);
1348 /* FIXME: should we allow updating keys? */
1350 val = 0;
1351 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1353 r = get_table_value_from_record (tv, rec, i + 1, &val);
1354 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1356 IStream *stm;
1357 LPWSTR stname;
1359 if ( r != ERROR_SUCCESS )
1360 return ERROR_FUNCTION_FAILED;
1362 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1363 if ( r != ERROR_SUCCESS )
1364 return r;
1366 r = get_stream_name( tv, row, &stname );
1367 if ( r != ERROR_SUCCESS )
1369 IStream_Release( stm );
1370 return r;
1373 r = add_stream( tv->db, stname, stm );
1374 IStream_Release( stm );
1375 msi_free ( stname );
1377 if ( r != ERROR_SUCCESS )
1378 return r;
1380 else if ( tv->columns[i].type & MSITYPE_STRING )
1382 UINT x;
1384 if ( r != ERROR_SUCCESS )
1386 int len;
1387 const WCHAR *sval = msi_record_get_string( rec, i + 1, &len );
1388 val = msi_add_string( tv->db->strings, sval, len,
1389 persistent ? StringPersistent : StringNonPersistent );
1391 else
1393 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1394 if (val == x)
1395 continue;
1398 else
1400 if ( r != ERROR_SUCCESS )
1401 return ERROR_FUNCTION_FAILED;
1405 r = TABLE_set_int( tv, row, i+1, val );
1406 if ( r != ERROR_SUCCESS )
1407 break;
1409 return r;
1412 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1414 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1415 BYTE **p, *row;
1416 BOOL *b;
1417 UINT sz;
1418 BYTE ***data_ptr;
1419 BOOL **data_persist_ptr;
1420 UINT *row_count;
1422 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1424 if( !tv->table )
1425 return ERROR_INVALID_PARAMETER;
1427 row = msi_alloc_zero( tv->row_size );
1428 if( !row )
1429 return ERROR_NOT_ENOUGH_MEMORY;
1431 row_count = &tv->table->row_count;
1432 data_ptr = &tv->table->data;
1433 data_persist_ptr = &tv->table->data_persistent;
1434 if (*num == -1)
1435 *num = tv->table->row_count;
1437 sz = (*row_count + 1) * sizeof (BYTE*);
1438 if( *data_ptr )
1439 p = msi_realloc( *data_ptr, sz );
1440 else
1441 p = msi_alloc( sz );
1442 if( !p )
1444 msi_free( row );
1445 return ERROR_NOT_ENOUGH_MEMORY;
1448 sz = (*row_count + 1) * sizeof (BOOL);
1449 if( *data_persist_ptr )
1450 b = msi_realloc( *data_persist_ptr, sz );
1451 else
1452 b = msi_alloc( sz );
1453 if( !b )
1455 msi_free( row );
1456 msi_free( p );
1457 return ERROR_NOT_ENOUGH_MEMORY;
1460 *data_ptr = p;
1461 (*data_ptr)[*row_count] = row;
1463 *data_persist_ptr = b;
1464 (*data_persist_ptr)[*row_count] = !temporary;
1466 (*row_count)++;
1468 return ERROR_SUCCESS;
1471 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1473 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1475 TRACE("%p %p\n", tv, record);
1477 TRACE("There are %d columns\n", tv->num_cols );
1479 return ERROR_SUCCESS;
1482 static UINT TABLE_close( struct tagMSIVIEW *view )
1484 TRACE("%p\n", view );
1486 return ERROR_SUCCESS;
1489 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1491 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1493 TRACE("%p %p %p\n", view, rows, cols );
1495 if( cols )
1496 *cols = tv->num_cols;
1497 if( rows )
1499 if( !tv->table )
1500 return ERROR_INVALID_PARAMETER;
1501 *rows = tv->table->row_count;
1504 return ERROR_SUCCESS;
1507 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1508 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1509 LPCWSTR *table_name )
1511 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1513 TRACE("%p %d %p %p\n", tv, n, name, type );
1515 if( ( n == 0 ) || ( n > tv->num_cols ) )
1516 return ERROR_INVALID_PARAMETER;
1518 if( name )
1520 *name = tv->columns[n-1].colname;
1521 if( !*name )
1522 return ERROR_FUNCTION_FAILED;
1525 if( table_name )
1527 *table_name = tv->columns[n-1].tablename;
1528 if( !*table_name )
1529 return ERROR_FUNCTION_FAILED;
1532 if( type )
1533 *type = tv->columns[n-1].type;
1535 if( temporary )
1536 *temporary = tv->columns[n-1].temporary;
1538 return ERROR_SUCCESS;
1541 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1543 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1545 UINT r, row, i;
1547 /* check there are no null values where they're not allowed */
1548 for( i = 0; i < tv->num_cols; i++ )
1550 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1551 continue;
1553 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1554 TRACE("skipping binary column\n");
1555 else if ( tv->columns[i].type & MSITYPE_STRING )
1557 int len;
1558 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
1560 if (!str || (!str[0] && !len))
1562 if (column) *column = i;
1563 return ERROR_INVALID_DATA;
1566 else
1568 UINT n;
1570 n = MSI_RecordGetInteger( rec, i+1 );
1571 if (n == MSI_NULL_INTEGER)
1573 if (column) *column = i;
1574 return ERROR_INVALID_DATA;
1579 /* check there are no duplicate keys */
1580 r = msi_table_find_row( tv, rec, &row, column );
1581 if (r == ERROR_SUCCESS)
1582 return ERROR_FUNCTION_FAILED;
1584 return ERROR_SUCCESS;
1587 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1589 UINT r, i, ivalue, x;
1591 for (i = 0; i < tv->num_cols; i++ )
1593 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1595 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1596 if (r != ERROR_SUCCESS)
1597 return 1;
1599 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1600 if (r != ERROR_SUCCESS)
1602 WARN("TABLE_fetch_int should not fail here %u\n", r);
1603 return -1;
1605 if (ivalue > x)
1607 return 1;
1609 else if (ivalue == x)
1611 if (i < tv->num_cols - 1) continue;
1612 return 0;
1614 else
1615 return -1;
1617 return 1;
1620 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1622 int idx, c, low = 0, high = tv->table->row_count - 1;
1624 TRACE("%p %p\n", tv, rec);
1626 while (low <= high)
1628 idx = (low + high) / 2;
1629 c = compare_record( tv, idx, rec );
1631 if (c < 0)
1632 high = idx - 1;
1633 else if (c > 0)
1634 low = idx + 1;
1635 else
1637 TRACE("found %u\n", idx);
1638 return idx;
1641 TRACE("found %u\n", high + 1);
1642 return high + 1;
1645 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1647 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1648 UINT i, r;
1650 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1652 /* check that the key is unique - can we find a matching row? */
1653 r = table_validate_new( tv, rec, NULL );
1654 if( r != ERROR_SUCCESS )
1655 return ERROR_FUNCTION_FAILED;
1657 if (row == -1)
1658 row = find_insert_index( tv, rec );
1660 r = table_create_new_row( view, &row, temporary );
1661 TRACE("insert_row returned %08x\n", r);
1662 if( r != ERROR_SUCCESS )
1663 return r;
1665 /* shift the rows to make room for the new row */
1666 for (i = tv->table->row_count - 1; i > row; i--)
1668 memmove(&(tv->table->data[i][0]),
1669 &(tv->table->data[i - 1][0]), tv->row_size);
1670 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1673 /* Re-set the persistence flag */
1674 tv->table->data_persistent[row] = !temporary;
1675 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1678 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1680 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1681 UINT r, num_rows, num_cols, i;
1683 TRACE("%p %d\n", tv, row);
1685 if ( !tv->table )
1686 return ERROR_INVALID_PARAMETER;
1688 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1689 if ( r != ERROR_SUCCESS )
1690 return r;
1692 if ( row >= num_rows )
1693 return ERROR_FUNCTION_FAILED;
1695 num_rows = tv->table->row_count;
1696 tv->table->row_count--;
1698 /* reset the hash tables */
1699 for (i = 0; i < tv->num_cols; i++)
1701 msi_free( tv->columns[i].hash_table );
1702 tv->columns[i].hash_table = NULL;
1705 for (i = row + 1; i < num_rows; i++)
1707 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1708 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1711 msi_free(tv->table->data[num_rows - 1]);
1713 return ERROR_SUCCESS;
1716 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1718 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1719 UINT r, new_row;
1721 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1722 * sets the fetched record apart from other records
1725 if (!tv->table)
1726 return ERROR_INVALID_PARAMETER;
1728 r = msi_table_find_row(tv, rec, &new_row, NULL);
1729 if (r != ERROR_SUCCESS)
1731 ERR("can't find row to modify\n");
1732 return ERROR_FUNCTION_FAILED;
1735 /* the row cannot be changed */
1736 if (row != new_row + 1)
1737 return ERROR_FUNCTION_FAILED;
1739 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1742 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1744 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1745 UINT r, row;
1747 if (!tv->table)
1748 return ERROR_INVALID_PARAMETER;
1750 r = msi_table_find_row(tv, rec, &row, NULL);
1751 if (r == ERROR_SUCCESS)
1752 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1753 else
1754 return TABLE_insert_row( view, rec, -1, FALSE );
1757 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1759 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1760 UINT row, r;
1762 r = msi_table_find_row(tv, rec, &row, NULL);
1763 if (r != ERROR_SUCCESS)
1764 return r;
1766 return TABLE_delete_row(view, row);
1769 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1771 MSIRECORD *curr;
1772 UINT r, i, count;
1774 r = TABLE_get_row(view, row - 1, &curr);
1775 if (r != ERROR_SUCCESS)
1776 return r;
1778 /* Close the original record */
1779 MSI_CloseRecord(&rec->hdr);
1781 count = MSI_RecordGetFieldCount(rec);
1782 for (i = 0; i < count; i++)
1783 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1785 msiobj_release(&curr->hdr);
1786 return ERROR_SUCCESS;
1789 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1790 MSIRECORD *rec, UINT row)
1792 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1793 UINT r, frow, column;
1795 TRACE("%p %d %p\n", view, eModifyMode, rec );
1797 switch (eModifyMode)
1799 case MSIMODIFY_DELETE:
1800 r = modify_delete_row( view, rec );
1801 break;
1802 case MSIMODIFY_VALIDATE_NEW:
1803 r = table_validate_new( tv, rec, &column );
1804 if (r != ERROR_SUCCESS)
1806 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1807 tv->view.error_column = tv->columns[column].colname;
1808 r = ERROR_INVALID_DATA;
1810 break;
1812 case MSIMODIFY_INSERT:
1813 r = table_validate_new( tv, rec, NULL );
1814 if (r != ERROR_SUCCESS)
1815 break;
1816 r = TABLE_insert_row( view, rec, -1, FALSE );
1817 break;
1819 case MSIMODIFY_INSERT_TEMPORARY:
1820 r = table_validate_new( tv, rec, NULL );
1821 if (r != ERROR_SUCCESS)
1822 break;
1823 r = TABLE_insert_row( view, rec, -1, TRUE );
1824 break;
1826 case MSIMODIFY_REFRESH:
1827 r = msi_refresh_record( view, rec, row );
1828 break;
1830 case MSIMODIFY_UPDATE:
1831 r = msi_table_update( view, rec, row );
1832 break;
1834 case MSIMODIFY_ASSIGN:
1835 r = msi_table_assign( view, rec );
1836 break;
1838 case MSIMODIFY_MERGE:
1839 /* check row that matches this record */
1840 r = msi_table_find_row( tv, rec, &frow, &column );
1841 if (r != ERROR_SUCCESS)
1843 r = table_validate_new( tv, rec, NULL );
1844 if (r == ERROR_SUCCESS)
1845 r = TABLE_insert_row( view, rec, -1, FALSE );
1847 break;
1849 case MSIMODIFY_REPLACE:
1850 case MSIMODIFY_VALIDATE:
1851 case MSIMODIFY_VALIDATE_FIELD:
1852 case MSIMODIFY_VALIDATE_DELETE:
1853 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1854 r = ERROR_CALL_NOT_IMPLEMENTED;
1855 break;
1857 default:
1858 r = ERROR_INVALID_DATA;
1861 return r;
1864 static UINT TABLE_delete( struct tagMSIVIEW *view )
1866 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1868 TRACE("%p\n", view );
1870 tv->table = NULL;
1871 tv->columns = NULL;
1873 msi_free( tv );
1875 return ERROR_SUCCESS;
1878 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1879 UINT val, UINT *row, MSIITERHANDLE *handle )
1881 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1882 const MSICOLUMNHASHENTRY *entry;
1884 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1886 if( !tv->table )
1887 return ERROR_INVALID_PARAMETER;
1889 if( (col==0) || (col > tv->num_cols) )
1890 return ERROR_INVALID_PARAMETER;
1892 if( !tv->columns[col-1].hash_table )
1894 UINT i;
1895 UINT num_rows = tv->table->row_count;
1896 MSICOLUMNHASHENTRY **hash_table;
1897 MSICOLUMNHASHENTRY *new_entry;
1899 if( tv->columns[col-1].offset >= tv->row_size )
1901 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1902 ERR("%p %p\n", tv, tv->columns );
1903 return ERROR_FUNCTION_FAILED;
1906 /* allocate contiguous memory for the table and its entries so we
1907 * don't have to do an expensive cleanup */
1908 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1909 num_rows * sizeof(MSICOLUMNHASHENTRY));
1910 if (!hash_table)
1911 return ERROR_OUTOFMEMORY;
1913 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1914 tv->columns[col-1].hash_table = hash_table;
1916 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1918 for (i = 0; i < num_rows; i++, new_entry++)
1920 UINT row_value;
1922 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1923 continue;
1925 new_entry->next = NULL;
1926 new_entry->value = row_value;
1927 new_entry->row = i;
1928 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1930 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1931 while (prev_entry->next)
1932 prev_entry = prev_entry->next;
1933 prev_entry->next = new_entry;
1935 else
1936 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1940 if( !*handle )
1941 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1942 else
1943 entry = (*handle)->next;
1945 while (entry && entry->value != val)
1946 entry = entry->next;
1948 *handle = entry;
1949 if (!entry)
1950 return ERROR_NO_MORE_ITEMS;
1952 *row = entry->row;
1954 return ERROR_SUCCESS;
1957 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1959 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1960 UINT i;
1962 TRACE("%p %d\n", view, tv->table->ref_count);
1964 for (i = 0; i < tv->table->col_count; i++)
1966 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1967 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1970 return InterlockedIncrement(&tv->table->ref_count);
1973 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1975 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1976 MSIRECORD *rec = NULL;
1977 MSIVIEW *columns = NULL;
1978 UINT row, r;
1980 rec = MSI_CreateRecord(2);
1981 if (!rec)
1982 return ERROR_OUTOFMEMORY;
1984 MSI_RecordSetStringW(rec, 1, table);
1985 MSI_RecordSetInteger(rec, 2, number);
1987 r = TABLE_CreateView(tv->db, szColumns, &columns);
1988 if (r != ERROR_SUCCESS)
1990 msiobj_release(&rec->hdr);
1991 return r;
1994 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1995 if (r != ERROR_SUCCESS)
1996 goto done;
1998 r = TABLE_delete_row(columns, row);
1999 if (r != ERROR_SUCCESS)
2000 goto done;
2002 msi_update_table_columns(tv->db, table);
2004 done:
2005 msiobj_release(&rec->hdr);
2006 columns->ops->delete(columns);
2007 return r;
2010 static UINT TABLE_release(struct tagMSIVIEW *view)
2012 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2013 INT ref = tv->table->ref_count;
2014 UINT i, r;
2016 TRACE("%p %d\n", view, ref);
2018 for (i = 0; i < tv->table->col_count; i++)
2020 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2022 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2023 if (ref == 0)
2025 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2026 tv->table->colinfo[i].number);
2027 if (r != ERROR_SUCCESS)
2028 break;
2033 ref = InterlockedDecrement(&tv->table->ref_count);
2034 if (ref == 0)
2036 if (!tv->table->row_count)
2038 list_remove(&tv->table->entry);
2039 free_table(tv->table);
2040 TABLE_delete(view);
2044 return ref;
2047 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2048 LPCWSTR column, UINT type, BOOL hold)
2050 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2051 MSITABLE *msitable;
2052 MSIRECORD *rec;
2053 UINT r, i;
2055 rec = MSI_CreateRecord(4);
2056 if (!rec)
2057 return ERROR_OUTOFMEMORY;
2059 MSI_RecordSetStringW(rec, 1, table);
2060 MSI_RecordSetInteger(rec, 2, number);
2061 MSI_RecordSetStringW(rec, 3, column);
2062 MSI_RecordSetInteger(rec, 4, type);
2064 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2065 if (r != ERROR_SUCCESS)
2066 goto done;
2068 msi_update_table_columns(tv->db, table);
2070 if (!hold)
2071 goto done;
2073 msitable = find_cached_table(tv->db, table);
2074 for (i = 0; i < msitable->col_count; i++)
2076 if (!strcmpW( msitable->colinfo[i].colname, column ))
2078 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2079 break;
2083 done:
2084 msiobj_release(&rec->hdr);
2085 return r;
2088 static UINT TABLE_drop(struct tagMSIVIEW *view)
2090 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2091 MSIVIEW *tables = NULL;
2092 MSIRECORD *rec = NULL;
2093 UINT r, row;
2094 INT i;
2096 TRACE("dropping table %s\n", debugstr_w(tv->name));
2098 for (i = tv->table->col_count - 1; i >= 0; i--)
2100 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2101 tv->table->colinfo[i].number);
2102 if (r != ERROR_SUCCESS)
2103 return r;
2106 rec = MSI_CreateRecord(1);
2107 if (!rec)
2108 return ERROR_OUTOFMEMORY;
2110 MSI_RecordSetStringW(rec, 1, tv->name);
2112 r = TABLE_CreateView(tv->db, szTables, &tables);
2113 if (r != ERROR_SUCCESS)
2115 msiobj_release(&rec->hdr);
2116 return r;
2119 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2120 if (r != ERROR_SUCCESS)
2121 goto done;
2123 r = TABLE_delete_row(tables, row);
2124 if (r != ERROR_SUCCESS)
2125 goto done;
2127 list_remove(&tv->table->entry);
2128 free_table(tv->table);
2130 done:
2131 msiobj_release(&rec->hdr);
2132 tables->ops->delete(tables);
2134 return r;
2137 static const MSIVIEWOPS table_ops =
2139 TABLE_fetch_int,
2140 TABLE_fetch_stream,
2141 TABLE_get_row,
2142 TABLE_set_row,
2143 TABLE_insert_row,
2144 TABLE_delete_row,
2145 TABLE_execute,
2146 TABLE_close,
2147 TABLE_get_dimensions,
2148 TABLE_get_column_info,
2149 TABLE_modify,
2150 TABLE_delete,
2151 TABLE_find_matching_rows,
2152 TABLE_add_ref,
2153 TABLE_release,
2154 TABLE_add_column,
2155 TABLE_remove_column,
2156 NULL,
2157 TABLE_drop,
2160 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2162 MSITABLEVIEW *tv ;
2163 UINT r, sz;
2165 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2167 if ( !strcmpW( name, szStreams ) )
2168 return STREAMS_CreateView( db, view );
2169 else if ( !strcmpW( name, szStorages ) )
2170 return STORAGES_CreateView( db, view );
2172 sz = FIELD_OFFSET( MSITABLEVIEW, name[lstrlenW( name ) + 1] );
2173 tv = msi_alloc_zero( sz );
2174 if( !tv )
2175 return ERROR_FUNCTION_FAILED;
2177 r = get_table( db, name, &tv->table );
2178 if( r != ERROR_SUCCESS )
2180 msi_free( tv );
2181 WARN("table not found\n");
2182 return r;
2185 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2187 /* fill the structure */
2188 tv->view.ops = &table_ops;
2189 tv->db = db;
2190 tv->columns = tv->table->colinfo;
2191 tv->num_cols = tv->table->col_count;
2192 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2194 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2196 *view = (MSIVIEW*) tv;
2197 lstrcpyW( tv->name, name );
2199 return ERROR_SUCCESS;
2202 UINT MSI_CommitTables( MSIDATABASE *db )
2204 UINT r, bytes_per_strref;
2205 HRESULT hr;
2206 MSITABLE *table = NULL;
2208 TRACE("%p\n",db);
2210 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2211 if( r != ERROR_SUCCESS )
2213 WARN("failed to save string table r=%08x\n",r);
2214 return r;
2217 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2219 r = save_table( db, table, bytes_per_strref );
2220 if( r != ERROR_SUCCESS )
2222 WARN("failed to save table %s (r=%08x)\n",
2223 debugstr_w(table->name), r);
2224 return r;
2228 hr = IStorage_Commit( db->storage, 0 );
2229 if (FAILED( hr ))
2231 WARN("failed to commit changes 0x%08x\n", hr);
2232 r = ERROR_FUNCTION_FAILED;
2234 return r;
2237 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2239 MSITABLE *t;
2240 UINT r;
2242 TRACE("%p %s\n", db, debugstr_w(table));
2244 if (!table)
2245 return MSICONDITION_ERROR;
2247 r = get_table( db, table, &t );
2248 if (r != ERROR_SUCCESS)
2249 return MSICONDITION_NONE;
2251 return t->persistent;
2254 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2256 UINT ret = 0, i;
2258 for (i = 0; i < bytes; i++)
2259 ret += (data[col + i] << i * 8);
2261 return ret;
2264 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2266 LPWSTR stname = NULL, sval, p;
2267 DWORD len;
2268 UINT i, r;
2270 TRACE("%p %p\n", tv, rec);
2272 len = lstrlenW( tv->name ) + 1;
2273 stname = msi_alloc( len*sizeof(WCHAR) );
2274 if ( !stname )
2276 r = ERROR_OUTOFMEMORY;
2277 goto err;
2280 lstrcpyW( stname, tv->name );
2282 for ( i = 0; i < tv->num_cols; i++ )
2284 if ( tv->columns[i].type & MSITYPE_KEY )
2286 sval = msi_dup_record_field( rec, i + 1 );
2287 if ( !sval )
2289 r = ERROR_OUTOFMEMORY;
2290 goto err;
2293 len += lstrlenW( szDot ) + lstrlenW ( sval );
2294 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2295 if ( !p )
2297 r = ERROR_OUTOFMEMORY;
2298 msi_free(sval);
2299 goto err;
2301 stname = p;
2303 lstrcatW( stname, szDot );
2304 lstrcatW( stname, sval );
2306 msi_free( sval );
2308 else
2309 continue;
2312 *pstname = encode_streamname( FALSE, stname );
2313 msi_free( stname );
2315 return ERROR_SUCCESS;
2317 err:
2318 msi_free ( stname );
2319 *pstname = NULL;
2320 return r;
2323 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2324 IStorage *stg, const BYTE *rawdata, UINT bytes_per_strref )
2326 UINT i, val, ofs = 0;
2327 USHORT mask;
2328 MSICOLUMNINFO *columns = tv->columns;
2329 MSIRECORD *rec;
2331 mask = rawdata[0] | (rawdata[1] << 8);
2332 rawdata += 2;
2334 rec = MSI_CreateRecord( tv->num_cols );
2335 if( !rec )
2336 return rec;
2338 TRACE("row ->\n");
2339 for( i=0; i<tv->num_cols; i++ )
2341 if ( (mask&1) && (i>=(mask>>8)) )
2342 break;
2343 /* all keys must be present */
2344 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2345 continue;
2347 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2349 LPWSTR encname;
2350 IStream *stm = NULL;
2351 UINT r;
2353 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2355 r = msi_record_encoded_stream_name( tv, rec, &encname );
2356 if ( r != ERROR_SUCCESS )
2358 msiobj_release( &rec->hdr );
2359 return NULL;
2361 r = IStorage_OpenStream( stg, encname, NULL, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2362 if ( r != ERROR_SUCCESS )
2364 msiobj_release( &rec->hdr );
2365 msi_free( encname );
2366 return NULL;
2369 MSI_RecordSetStream( rec, i+1, stm );
2370 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2371 msi_free( encname );
2373 else if( columns[i].type & MSITYPE_STRING )
2375 int len;
2376 const WCHAR *sval;
2378 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2379 sval = msi_string_lookup( st, val, &len );
2380 msi_record_set_string( rec, i+1, sval, len );
2381 TRACE(" field %d [%s]\n", i+1, debugstr_wn(sval, len));
2382 ofs += bytes_per_strref;
2384 else
2386 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2387 switch( n )
2389 case 2:
2390 val = read_raw_int(rawdata, ofs, n);
2391 if (val)
2392 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2393 TRACE(" field %d [0x%04x]\n", i+1, val );
2394 break;
2395 case 4:
2396 val = read_raw_int(rawdata, ofs, n);
2397 if (val)
2398 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2399 TRACE(" field %d [0x%08x]\n", i+1, val );
2400 break;
2401 default:
2402 ERR("oops - unknown column width %d\n", n);
2403 break;
2405 ofs += n;
2408 return rec;
2411 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2413 UINT i;
2414 for (i = 0; i < rawsize / 2; i++)
2416 int len;
2417 const WCHAR *sval = msi_string_lookup( st, rawdata[i], &len );
2418 MESSAGE(" %04x %s\n", rawdata[i], debugstr_wn(sval, len) );
2422 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2424 UINT i, r, *data;
2426 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2427 for( i=0; i<tv->num_cols; i++ )
2429 data[i] = 0;
2431 if ( ~tv->columns[i].type & MSITYPE_KEY )
2432 continue;
2434 /* turn the transform column value into a row value */
2435 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2436 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2438 int len;
2439 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
2440 if (str)
2442 r = msi_string2id( tv->db->strings, str, len, &data[i] );
2444 /* if there's no matching string in the string table,
2445 these keys can't match any record, so fail now. */
2446 if (r != ERROR_SUCCESS)
2448 msi_free( data );
2449 return NULL;
2452 else data[i] = 0;
2454 else
2456 data[i] = MSI_RecordGetInteger( rec, i+1 );
2458 if (data[i] == MSI_NULL_INTEGER)
2459 data[i] = 0;
2460 else if ((tv->columns[i].type&0xff) == 2)
2461 data[i] += 0x8000;
2462 else
2463 data[i] += 0x80000000;
2466 return data;
2469 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2471 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2473 for( i=0; i<tv->num_cols; i++ )
2475 if ( ~tv->columns[i].type & MSITYPE_KEY )
2476 continue;
2478 /* turn the transform column value into a row value */
2479 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2480 if ( r != ERROR_SUCCESS )
2482 ERR("TABLE_fetch_int shouldn't fail here\n");
2483 break;
2486 /* if this key matches, move to the next column */
2487 if ( x != data[i] )
2489 ret = ERROR_FUNCTION_FAILED;
2490 break;
2492 if (column) *column = i;
2493 ret = ERROR_SUCCESS;
2495 return ret;
2498 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2500 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2502 data = msi_record_to_row( tv, rec );
2503 if( !data )
2504 return r;
2505 for( i = 0; i < tv->table->row_count; i++ )
2507 r = msi_row_matches( tv, i, data, column );
2508 if( r == ERROR_SUCCESS )
2510 *row = i;
2511 break;
2514 msi_free( data );
2515 return r;
2518 typedef struct
2520 struct list entry;
2521 LPWSTR name;
2522 } TRANSFORMDATA;
2524 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2525 string_table *st, TRANSFORMDATA *transform,
2526 UINT bytes_per_strref )
2528 BYTE *rawdata = NULL;
2529 MSITABLEVIEW *tv = NULL;
2530 UINT r, n, sz, i, mask, num_cols, colcol = 0, rawsize = 0;
2531 MSIRECORD *rec = NULL;
2532 WCHAR coltable[32];
2533 const WCHAR *name;
2535 if (!transform)
2536 return ERROR_SUCCESS;
2538 name = transform->name;
2540 coltable[0] = 0;
2541 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2543 /* read the transform data */
2544 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2545 if ( !rawdata )
2547 TRACE("table %s empty\n", debugstr_w(name) );
2548 return ERROR_INVALID_TABLE;
2551 /* create a table view */
2552 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2553 if( r != ERROR_SUCCESS )
2554 goto err;
2556 r = tv->view.ops->execute( &tv->view, NULL );
2557 if( r != ERROR_SUCCESS )
2558 goto err;
2560 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2561 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2563 /* interpret the data */
2564 for (n = 0; n < rawsize;)
2566 mask = rawdata[n] | (rawdata[n + 1] << 8);
2567 if (mask & 1)
2570 * if the low bit is set, columns are continuous and
2571 * the number of columns is specified in the high byte
2573 sz = 2;
2574 num_cols = mask >> 8;
2575 if (num_cols > tv->num_cols)
2577 ERR("excess columns in transform: %u > %u\n", num_cols, tv->num_cols);
2578 break;
2581 for (i = 0; i < num_cols; i++)
2583 if( (tv->columns[i].type & MSITYPE_STRING) &&
2584 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2585 sz += bytes_per_strref;
2586 else
2587 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2590 else
2593 * If the low bit is not set, mask is a bitmask.
2594 * Excepting for key fields, which are always present,
2595 * each bit indicates that a field is present in the transform record.
2597 * mask == 0 is a special case ... only the keys will be present
2598 * and it means that this row should be deleted.
2600 sz = 2;
2601 num_cols = tv->num_cols;
2602 for (i = 0; i < num_cols; i++)
2604 if ((tv->columns[i].type & MSITYPE_KEY) || ((1 << i) & mask))
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 );
2615 /* check we didn't run of the end of the table */
2616 if (n + sz > rawsize)
2618 ERR("borked.\n");
2619 dump_table( st, (USHORT *)rawdata, rawsize );
2620 break;
2623 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2624 if (rec)
2626 WCHAR table[32];
2627 DWORD sz = 32;
2628 UINT number = MSI_NULL_INTEGER;
2629 UINT row = 0;
2631 if (!strcmpW( name, szColumns ))
2633 MSI_RecordGetStringW( rec, 1, table, &sz );
2634 number = MSI_RecordGetInteger( rec, 2 );
2637 * Native msi seems writes nul into the Number (2nd) column of
2638 * the _Columns table when there are new columns
2640 if ( number == MSI_NULL_INTEGER )
2642 /* reset the column number on a new table */
2643 if (strcmpW( coltable, table ))
2645 colcol = 0;
2646 lstrcpyW( coltable, table );
2649 /* fix nul column numbers */
2650 MSI_RecordSetInteger( rec, 2, ++colcol );
2654 if (TRACE_ON(msidb)) dump_record( rec );
2656 r = msi_table_find_row( tv, rec, &row, NULL );
2657 if (r == ERROR_SUCCESS)
2659 if (!mask)
2661 TRACE("deleting row [%d]:\n", row);
2662 r = TABLE_delete_row( &tv->view, row );
2663 if (r != ERROR_SUCCESS)
2664 WARN("failed to delete row %u\n", r);
2666 else if (mask & 1)
2668 TRACE("modifying full row [%d]:\n", row);
2669 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2670 if (r != ERROR_SUCCESS)
2671 WARN("failed to modify row %u\n", r);
2673 else
2675 TRACE("modifying masked row [%d]:\n", row);
2676 r = TABLE_set_row( &tv->view, row, rec, mask );
2677 if (r != ERROR_SUCCESS)
2678 WARN("failed to modify row %u\n", r);
2681 else
2683 TRACE("inserting row\n");
2684 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2685 if (r != ERROR_SUCCESS)
2686 WARN("failed to insert row %u\n", r);
2689 if (!strcmpW( name, szColumns ))
2690 msi_update_table_columns( db, table );
2692 msiobj_release( &rec->hdr );
2695 n += sz;
2698 err:
2699 /* no need to free the table, it's associated with the database */
2700 msi_free( rawdata );
2701 if( tv )
2702 tv->view.ops->delete( &tv->view );
2704 return ERROR_SUCCESS;
2708 * msi_table_apply_transform
2710 * Enumerate the table transforms in a transform storage and apply each one.
2712 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2714 struct list transforms;
2715 IEnumSTATSTG *stgenum = NULL;
2716 TRANSFORMDATA *transform;
2717 TRANSFORMDATA *tables = NULL, *columns = NULL;
2718 HRESULT hr;
2719 STATSTG stat;
2720 string_table *strings;
2721 UINT ret = ERROR_FUNCTION_FAILED;
2722 UINT bytes_per_strref;
2723 BOOL property_update = FALSE;
2725 TRACE("%p %p\n", db, stg );
2727 strings = msi_load_string_table( stg, &bytes_per_strref );
2728 if( !strings )
2729 goto end;
2731 hr = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2732 if (FAILED( hr ))
2733 goto end;
2735 list_init(&transforms);
2737 while ( TRUE )
2739 MSITABLEVIEW *tv = NULL;
2740 WCHAR name[0x40];
2741 ULONG count = 0;
2743 hr = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2744 if (FAILED( hr ) || !count)
2745 break;
2747 decode_streamname( stat.pwcsName, name );
2748 CoTaskMemFree( stat.pwcsName );
2749 if ( name[0] != 0x4840 )
2750 continue;
2752 if ( !strcmpW( name+1, szStringPool ) ||
2753 !strcmpW( name+1, szStringData ) )
2754 continue;
2756 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2757 if ( !transform )
2758 break;
2760 list_add_tail( &transforms, &transform->entry );
2762 transform->name = strdupW( name + 1 );
2764 if ( !strcmpW( transform->name, szTables ) )
2765 tables = transform;
2766 else if (!strcmpW( transform->name, szColumns ) )
2767 columns = transform;
2768 else if (!strcmpW( transform->name, szProperty ))
2769 property_update = TRUE;
2771 TRACE("transform contains stream %s\n", debugstr_w(name));
2773 /* load the table */
2774 if (TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv ) != ERROR_SUCCESS)
2775 continue;
2777 if (tv->view.ops->execute( &tv->view, NULL ) != ERROR_SUCCESS)
2779 tv->view.ops->delete( &tv->view );
2780 continue;
2783 tv->view.ops->delete( &tv->view );
2787 * Apply _Tables and _Columns transforms first so that
2788 * the table metadata is correct, and empty tables exist.
2790 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2791 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2792 goto end;
2794 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2795 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2796 goto end;
2798 ret = ERROR_SUCCESS;
2800 while ( !list_empty( &transforms ) )
2802 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2804 if ( strcmpW( transform->name, szColumns ) &&
2805 strcmpW( transform->name, szTables ) &&
2806 ret == ERROR_SUCCESS )
2808 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2811 list_remove( &transform->entry );
2812 msi_free( transform->name );
2813 msi_free( transform );
2816 if ( ret == ERROR_SUCCESS )
2818 append_storage_to_db( db, stg );
2819 if (property_update) msi_clone_properties( db );
2822 end:
2823 if ( stgenum )
2824 IEnumSTATSTG_Release( stgenum );
2825 if ( strings )
2826 msi_destroy_stringtable( strings );
2828 return ret;