quartz: Fix IAMDirectSound interface definition.
[wine/multimedia.git] / dlls / msi / table.c
blobcc40515e66438beac57c89ee79823f7785a84949
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
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "winnls.h"
36 #include "msipriv.h"
37 #include "query.h"
39 #include "wine/debug.h"
40 #include "wine/unicode.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
44 #define MSITABLE_HASH_TABLE_SIZE 37
45 #define LONG_STR_BYTES 3
47 typedef struct tagMSICOLUMNHASHENTRY
49 struct tagMSICOLUMNHASHENTRY *next;
50 UINT value;
51 UINT row;
52 } MSICOLUMNHASHENTRY;
54 typedef struct tagMSICOLUMNINFO
56 LPWSTR tablename;
57 UINT number;
58 LPWSTR colname;
59 UINT type;
60 UINT offset;
61 INT ref_count;
62 BOOL temporary;
63 MSICOLUMNHASHENTRY **hash_table;
64 } MSICOLUMNINFO;
66 typedef struct tagMSIORDERINFO
68 UINT *reorder;
69 UINT num_cols;
70 UINT cols[1];
71 } MSIORDERINFO;
73 struct tagMSITABLE
75 BYTE **data;
76 BOOL *data_persistent;
77 UINT row_count;
78 struct list entry;
79 MSICOLUMNINFO *colinfo;
80 UINT col_count;
81 MSICONDITION persistent;
82 INT ref_count;
83 WCHAR name[1];
86 static const WCHAR szStringData[] = {
87 '_','S','t','r','i','n','g','D','a','t','a',0 };
88 static const WCHAR szStringPool[] = {
89 '_','S','t','r','i','n','g','P','o','o','l',0 };
91 /* information for default tables */
92 static WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
93 static WCHAR szTable[] = { 'T','a','b','l','e',0 };
94 static WCHAR szName[] = { 'N','a','m','e',0 };
95 static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
96 static WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
97 static WCHAR szType[] = { 'T','y','p','e',0 };
99 static const MSICOLUMNINFO _Columns_cols[4] = {
100 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
101 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
102 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
103 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
106 static const MSICOLUMNINFO _Tables_cols[1] = {
107 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
110 #define MAX_STREAM_NAME 0x1f
112 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
113 MSICOLUMNINFO **pcols, UINT *pcount );
114 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
115 DWORD count );
116 static UINT get_tablecolumns( MSIDATABASE *db,
117 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
118 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
120 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col )
122 if( MSITYPE_IS_BINARY(col->type) )
123 return 2;
125 if( col->type & MSITYPE_STRING )
126 return db->bytes_per_strref;
128 if( (col->type & 0xff) <= 2)
129 return 2;
131 if( (col->type & 0xff) != 4 )
132 ERR("Invalid column size!\n");
134 return 4;
137 static int utf2mime(int x)
139 if( (x>='0') && (x<='9') )
140 return x-'0';
141 if( (x>='A') && (x<='Z') )
142 return x-'A'+10;
143 if( (x>='a') && (x<='z') )
144 return x-'a'+10+26;
145 if( x=='.' )
146 return 10+26+26;
147 if( x=='_' )
148 return 10+26+26+1;
149 return -1;
152 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
154 DWORD count = MAX_STREAM_NAME;
155 DWORD ch, next;
156 LPWSTR out, p;
158 if( !bTable )
159 count = lstrlenW( in )+2;
160 out = msi_alloc( count*sizeof(WCHAR) );
161 p = out;
163 if( bTable )
165 *p++ = 0x4840;
166 count --;
168 while( count -- )
170 ch = *in++;
171 if( !ch )
173 *p = ch;
174 return out;
176 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
178 ch = utf2mime(ch) + 0x4800;
179 next = *in;
180 if( next && (next<0x80) )
182 next = utf2mime(next);
183 if( next != -1 )
185 next += 0x3ffffc0;
186 ch += (next<<6);
187 in++;
191 *p++ = ch;
193 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
194 msi_free( out );
195 return NULL;
198 static int mime2utf(int x)
200 if( x<10 )
201 return x + '0';
202 if( x<(10+26))
203 return x - 10 + 'A';
204 if( x<(10+26+26))
205 return x - 10 - 26 + 'a';
206 if( x == (10+26+26) )
207 return '.';
208 return '_';
211 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
213 WCHAR ch;
214 DWORD count = 0;
216 while ( (ch = *in++) )
218 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
220 if( ch >= 0x4800 )
221 ch = mime2utf(ch-0x4800);
222 else
224 ch -= 0x3800;
225 *out++ = mime2utf(ch&0x3f);
226 count++;
227 ch = mime2utf((ch>>6)&0x3f);
230 *out++ = ch;
231 count++;
233 *out = 0;
234 return count;
237 void enum_stream_names( IStorage *stg )
239 IEnumSTATSTG *stgenum = NULL;
240 HRESULT r;
241 STATSTG stat;
242 ULONG n, count;
243 WCHAR name[0x40];
245 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
246 if( FAILED( r ) )
247 return;
249 n = 0;
250 while( 1 )
252 count = 0;
253 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
254 if( FAILED( r ) || !count )
255 break;
256 decode_streamname( stat.pwcsName, name );
257 TRACE("stream %2d -> %s %s\n", n,
258 debugstr_w(stat.pwcsName), debugstr_w(name) );
259 CoTaskMemFree( stat.pwcsName );
260 n++;
263 IEnumSTATSTG_Release( stgenum );
266 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
267 BYTE **pdata, UINT *psz )
269 HRESULT r;
270 UINT ret = ERROR_FUNCTION_FAILED;
271 VOID *data;
272 ULONG sz, count;
273 IStream *stm = NULL;
274 STATSTG stat;
275 LPWSTR encname;
277 encname = encode_streamname(table, stname);
279 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
281 r = IStorage_OpenStream(stg, encname, NULL,
282 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
283 msi_free( encname );
284 if( FAILED( r ) )
286 WARN("open stream failed r = %08x - empty table?\n", r);
287 return ret;
290 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
291 if( FAILED( r ) )
293 WARN("open stream failed r = %08x!\n", r);
294 goto end;
297 if( stat.cbSize.QuadPart >> 32 )
299 WARN("Too big!\n");
300 goto end;
303 sz = stat.cbSize.QuadPart;
304 data = msi_alloc( sz );
305 if( !data )
307 WARN("couldn't allocate memory r=%08x!\n", r);
308 ret = ERROR_NOT_ENOUGH_MEMORY;
309 goto end;
312 r = IStream_Read(stm, data, sz, &count );
313 if( FAILED( r ) || ( count != sz ) )
315 msi_free( data );
316 WARN("read stream failed r = %08x!\n", r);
317 goto end;
320 *pdata = data;
321 *psz = sz;
322 ret = ERROR_SUCCESS;
324 end:
325 IStream_Release( stm );
327 return ret;
330 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
331 LPCVOID data, UINT sz, BOOL bTable )
333 HRESULT r;
334 UINT ret = ERROR_FUNCTION_FAILED;
335 ULONG count;
336 IStream *stm = NULL;
337 ULARGE_INTEGER size;
338 LARGE_INTEGER pos;
339 LPWSTR encname;
341 encname = encode_streamname(bTable, stname );
342 r = IStorage_OpenStream( stg, encname, NULL,
343 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
344 if( FAILED(r) )
346 r = IStorage_CreateStream( stg, encname,
347 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
349 msi_free( encname );
350 if( FAILED( r ) )
352 WARN("open stream failed r = %08x\n", r);
353 return ret;
356 size.QuadPart = sz;
357 r = IStream_SetSize( stm, size );
358 if( FAILED( r ) )
360 WARN("Failed to SetSize\n");
361 goto end;
364 pos.QuadPart = 0;
365 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
366 if( FAILED( r ) )
368 WARN("Failed to Seek\n");
369 goto end;
372 if (sz)
374 r = IStream_Write(stm, data, sz, &count );
375 if( FAILED( r ) || ( count != sz ) )
377 WARN("Failed to Write\n");
378 goto end;
382 ret = ERROR_SUCCESS;
384 end:
385 IStream_Release( stm );
387 return ret;
390 static void free_table( MSITABLE *table )
392 UINT i;
393 for( i=0; i<table->row_count; i++ )
394 msi_free( table->data[i] );
395 msi_free( table->data );
396 msi_free( table->data_persistent );
397 msi_free_colinfo( table->colinfo, table->col_count );
398 msi_free( table->colinfo );
399 msi_free( table );
402 static UINT msi_table_get_row_size( MSIDATABASE *db,const MSICOLUMNINFO *cols,
403 UINT count )
405 const MSICOLUMNINFO *last_col = &cols[count-1];
406 if (!count)
407 return 0;
408 return last_col->offset + bytes_per_column( db, last_col );
411 /* add this table to the list of cached tables in the database */
412 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
414 BYTE *rawdata = NULL;
415 UINT rawsize = 0, i, j, row_size = 0;
417 TRACE("%s\n",debugstr_w(t->name));
419 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
421 /* if we can't read the table, just assume that it's empty */
422 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
423 if( !rawdata )
424 return ERROR_SUCCESS;
426 TRACE("Read %d bytes\n", rawsize );
428 if( rawsize % row_size )
430 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
431 goto err;
434 t->row_count = rawsize / row_size;
435 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
436 if( !t->data )
437 goto err;
438 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
439 if ( !t->data_persistent )
440 goto err;
442 /* transpose all the data */
443 TRACE("Transposing data from %d rows\n", t->row_count );
444 for( i=0; i<t->row_count; i++ )
446 t->data[i] = msi_alloc( row_size );
447 if( !t->data[i] )
448 goto err;
449 t->data_persistent[i] = TRUE;
451 for( j=0; j<t->col_count; j++ )
453 UINT ofs = t->colinfo[j].offset;
454 UINT n = bytes_per_column( db, &t->colinfo[j] );
455 UINT k;
457 if ( n != 2 && n != 3 && n != 4 )
459 ERR("oops - unknown column width %d\n", n);
460 goto err;
463 for ( k = 0; k < n; k++ )
464 t->data[i][ofs + k] = rawdata[ofs*t->row_count + i * n + k];
468 msi_free( rawdata );
469 return ERROR_SUCCESS;
470 err:
471 msi_free( rawdata );
472 return ERROR_FUNCTION_FAILED;
475 void free_cached_tables( MSIDATABASE *db )
477 while( !list_empty( &db->tables ) )
479 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
481 list_remove( &t->entry );
482 free_table( t );
486 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
488 MSITABLE *t;
490 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
491 if( !lstrcmpW( name, t->name ) )
492 return t;
494 return NULL;
497 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
499 UINT r, column_count = 0;
500 MSICOLUMNINFO *columns;
502 /* get the number of columns in this table */
503 column_count = 0;
504 r = get_tablecolumns( db, name, NULL, &column_count );
505 if( r != ERROR_SUCCESS )
506 return r;
508 *pcount = column_count;
510 /* if there's no columns, there's no table */
511 if( column_count == 0 )
512 return ERROR_INVALID_PARAMETER;
514 TRACE("Table %s found\n", debugstr_w(name) );
516 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
517 if( !columns )
518 return ERROR_FUNCTION_FAILED;
520 r = get_tablecolumns( db, name, columns, &column_count );
521 if( r != ERROR_SUCCESS )
523 msi_free( columns );
524 return ERROR_FUNCTION_FAILED;
527 *pcols = columns;
529 return r;
532 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
533 MSICONDITION persistent, MSITABLE **table_ret)
535 UINT r, nField;
536 MSIVIEW *tv = NULL;
537 MSIRECORD *rec = NULL;
538 column_info *col;
539 MSITABLE *table;
540 UINT i;
542 /* only add tables that don't exist already */
543 if( TABLE_Exists(db, name ) )
545 WARN("table %s exists\n", debugstr_w(name));
546 return ERROR_BAD_QUERY_SYNTAX;
549 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
550 if( !table )
551 return ERROR_FUNCTION_FAILED;
553 table->ref_count = 1;
554 table->row_count = 0;
555 table->data = NULL;
556 table->data_persistent = NULL;
557 table->colinfo = NULL;
558 table->col_count = 0;
559 table->persistent = persistent;
560 lstrcpyW( table->name, name );
562 for( col = col_info; col; col = col->next )
563 table->col_count++;
565 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
566 if (!table->colinfo)
568 free_table( table );
569 return ERROR_FUNCTION_FAILED;
572 for( i = 0, col = col_info; col; i++, col = col->next )
574 table->colinfo[ i ].tablename = strdupW( col->table );
575 table->colinfo[ i ].number = i + 1;
576 table->colinfo[ i ].colname = strdupW( col->column );
577 table->colinfo[ i ].type = col->type;
578 table->colinfo[ i ].offset = 0;
579 table->colinfo[ i ].ref_count = 0;
580 table->colinfo[ i ].hash_table = NULL;
581 table->colinfo[ i ].temporary = col->temporary;
583 table_calc_column_offsets( db, table->colinfo, table->col_count);
585 r = TABLE_CreateView( db, szTables, &tv );
586 TRACE("CreateView returned %x\n", r);
587 if( r )
589 free_table( table );
590 return r;
593 r = tv->ops->execute( tv, 0 );
594 TRACE("tv execute returned %x\n", r);
595 if( r )
596 goto err;
598 rec = MSI_CreateRecord( 1 );
599 if( !rec )
600 goto err;
602 r = MSI_RecordSetStringW( rec, 1, name );
603 if( r )
604 goto err;
606 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
607 TRACE("insert_row returned %x\n", r);
608 if( r )
609 goto err;
611 tv->ops->delete( tv );
612 tv = NULL;
614 msiobj_release( &rec->hdr );
615 rec = NULL;
617 if( persistent != MSICONDITION_FALSE )
619 /* add each column to the _Columns table */
620 r = TABLE_CreateView( db, szColumns, &tv );
621 if( r )
622 return r;
624 r = tv->ops->execute( tv, 0 );
625 TRACE("tv execute returned %x\n", r);
626 if( r )
627 goto err;
629 rec = MSI_CreateRecord( 4 );
630 if( !rec )
631 goto err;
633 r = MSI_RecordSetStringW( rec, 1, name );
634 if( r )
635 goto err;
638 * need to set the table, column number, col name and type
639 * for each column we enter in the table
641 nField = 1;
642 for( col = col_info; col; col = col->next )
644 r = MSI_RecordSetInteger( rec, 2, nField );
645 if( r )
646 goto err;
648 r = MSI_RecordSetStringW( rec, 3, col->column );
649 if( r )
650 goto err;
652 r = MSI_RecordSetInteger( rec, 4, col->type );
653 if( r )
654 goto err;
656 r = tv->ops->insert_row( tv, rec, -1, FALSE );
657 if( r )
658 goto err;
660 nField++;
662 if( !col )
663 r = ERROR_SUCCESS;
666 err:
667 if (rec)
668 msiobj_release( &rec->hdr );
669 /* FIXME: remove values from the string table on error */
670 if( tv )
671 tv->ops->delete( tv );
673 if (r == ERROR_SUCCESS)
675 list_add_head( &db->tables, &table->entry );
676 *table_ret = table;
678 else
679 free_table( table );
681 return r;
684 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
686 MSITABLE *table;
687 UINT r;
689 /* first, see if the table is cached */
690 table = find_cached_table( db, name );
691 if( table )
693 *table_ret = table;
694 return ERROR_SUCCESS;
697 /* nonexistent tables should be interpreted as empty tables */
698 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
699 if( !table )
700 return ERROR_FUNCTION_FAILED;
702 table->row_count = 0;
703 table->data = NULL;
704 table->data_persistent = NULL;
705 table->colinfo = NULL;
706 table->col_count = 0;
707 table->persistent = MSICONDITION_TRUE;
708 lstrcpyW( table->name, name );
710 if ( !lstrcmpW(name, szTables) || !lstrcmpW(name, szColumns) )
711 table->persistent = MSICONDITION_NONE;
713 r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
714 if (r != ERROR_SUCCESS)
716 free_table ( table );
717 return r;
720 r = read_table_from_storage( db, table, db->storage );
721 if( r != ERROR_SUCCESS )
723 free_table( table );
724 return r;
727 list_add_head( &db->tables, &table->entry );
728 *table_ret = table;
729 return ERROR_SUCCESS;
732 static UINT save_table( MSIDATABASE *db, const MSITABLE *t )
734 BYTE *rawdata = NULL, *p;
735 UINT rawsize, r, i, j, row_size;
737 /* Nothing to do for non-persistent tables */
738 if( t->persistent == MSICONDITION_FALSE )
739 return ERROR_SUCCESS;
741 TRACE("Saving %s\n", debugstr_w( t->name ) );
743 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
745 rawsize = t->row_count * row_size;
746 rawdata = msi_alloc_zero( rawsize );
747 if( !rawdata )
749 r = ERROR_NOT_ENOUGH_MEMORY;
750 goto err;
753 rawsize = 0;
754 p = rawdata;
755 for( i=0; i<t->col_count; i++ )
757 for( j=0; j<t->row_count; j++ )
759 UINT offset = t->colinfo[i].offset;
761 if (!t->data_persistent[j]) continue;
762 if (i == 0)
763 rawsize += row_size;
765 *p++ = t->data[j][offset];
766 *p++ = t->data[j][offset + 1];
767 if( 4 == bytes_per_column( db, &t->colinfo[i] ) )
769 *p++ = t->data[j][offset + 2];
770 *p++ = t->data[j][offset + 3];
775 TRACE("writing %d bytes\n", rawsize);
776 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
778 err:
779 msi_free( rawdata );
781 return r;
784 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
785 DWORD count )
787 DWORD i;
789 for( i=0; colinfo && (i<count); i++ )
791 assert( (i+1) == colinfo[ i ].number );
792 if (i)
793 colinfo[i].offset = colinfo[ i - 1 ].offset
794 + bytes_per_column( db, &colinfo[ i - 1 ] );
795 else
796 colinfo[i].offset = 0;
797 TRACE("column %d is [%s] with type %08x ofs %d\n",
798 colinfo[i].number, debugstr_w(colinfo[i].colname),
799 colinfo[i].type, colinfo[i].offset);
803 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
804 MSICOLUMNINFO *colinfo, UINT *sz)
806 const MSICOLUMNINFO *p;
807 DWORD i, n;
809 TRACE("%s\n", debugstr_w(name));
811 if (!lstrcmpW( name, szTables ))
813 p = _Tables_cols;
814 n = 1;
816 else if (!lstrcmpW( name, szColumns ))
818 p = _Columns_cols;
819 n = 4;
821 else
822 return ERROR_FUNCTION_FAILED;
824 /* duplicate the string data so we can free it in msi_free_colinfo */
825 for (i=0; i<n; i++)
827 if (colinfo && (i < *sz) )
829 colinfo[i] = p[i];
830 colinfo[i].tablename = strdupW( p[i].tablename );
831 colinfo[i].colname = strdupW( p[i].colname );
833 if( colinfo && (i >= *sz) )
834 break;
836 table_calc_column_offsets( db, colinfo, n );
837 *sz = n;
838 return ERROR_SUCCESS;
841 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
843 UINT i;
845 for( i=0; i<count; i++ )
847 msi_free( colinfo[i].tablename );
848 msi_free( colinfo[i].colname );
849 msi_free( colinfo[i].hash_table );
853 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
855 return strdupW(msi_string_lookup_id( db->strings, stringid ));
858 static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
860 UINT ret = 0, i;
862 for (i = 0; i < bytes; i++)
863 ret += (data[row][col + i] << i * 8);
865 return ret;
868 static UINT get_tablecolumns( MSIDATABASE *db,
869 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
871 UINT r, i, n=0, table_id, count, maxcount = *sz;
872 MSITABLE *table = NULL;
874 TRACE("%s\n", debugstr_w(szTableName));
876 /* first check if there is a default table with that name */
877 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
878 if( ( r == ERROR_SUCCESS ) && *sz )
879 return r;
881 r = get_table( db, szColumns, &table );
882 if( r != ERROR_SUCCESS )
884 ERR("couldn't load _Columns table\n");
885 return ERROR_FUNCTION_FAILED;
888 /* convert table and column names to IDs from the string table */
889 r = msi_string2idW( db->strings, szTableName, &table_id );
890 if( r != ERROR_SUCCESS )
892 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
893 return r;
896 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
898 /* Note: _Columns table doesn't have non-persistent data */
900 /* if maxcount is non-zero, assume it's exactly right for this table */
901 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
902 count = table->row_count;
903 for( i=0; i<count; i++ )
905 if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
906 continue;
907 if( colinfo )
909 UINT id = read_table_int(table->data, i, table->colinfo[2].offset, db->bytes_per_strref);
910 UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
912 /* check the column number is in range */
913 if (col<1 || col>maxcount)
915 ERR("column %d out of range\n", col);
916 continue;
919 /* check if this column was already set */
920 if (colinfo[ col - 1 ].number)
922 ERR("duplicate column %d\n", col);
923 continue;
926 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
927 colinfo[ col - 1 ].number = col;
928 colinfo[ col - 1 ].colname = msi_makestring( db, id );
929 colinfo[ col - 1 ].type = read_table_int(table->data, i,
930 table->colinfo[3].offset,
931 sizeof(USHORT)) - (1<<15);
932 colinfo[ col - 1 ].offset = 0;
933 colinfo[ col - 1 ].ref_count = 0;
934 colinfo[ col - 1 ].hash_table = NULL;
936 n++;
939 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
941 if (colinfo && n != maxcount)
943 ERR("missing column in table %s\n", debugstr_w(szTableName));
944 msi_free_colinfo(colinfo, maxcount );
945 return ERROR_FUNCTION_FAILED;
948 table_calc_column_offsets( db, colinfo, n );
949 *sz = n;
951 return ERROR_SUCCESS;
954 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
956 MSITABLE *table;
957 LPWSTR tablename;
958 UINT size, offset, old_count;
959 UINT n;
961 /* We may free name in msi_free_colinfo. */
962 tablename = strdupW( name );
964 table = find_cached_table( db, tablename );
965 old_count = table->col_count;
966 msi_free_colinfo( table->colinfo, table->col_count );
967 msi_free( table->colinfo );
968 table->colinfo = NULL;
970 table_get_column_info( db, tablename, &table->colinfo, &table->col_count );
971 if (!table->col_count)
972 goto done;
974 size = msi_table_get_row_size( db, table->colinfo, table->col_count );
975 offset = table->colinfo[table->col_count - 1].offset;
977 for ( n = 0; n < table->row_count; n++ )
979 table->data[n] = msi_realloc( table->data[n], size );
980 if (old_count < table->col_count)
981 memset( &table->data[n][offset], 0, size - offset );
984 done:
985 msi_free(tablename);
988 /* try to find the table name in the _Tables table */
989 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
991 UINT r, table_id = 0, i, count;
992 MSITABLE *table = NULL;
994 static const WCHAR szStreams[] = {'_','S','t','r','e','a','m','s',0};
995 static const WCHAR szStorages[] = {'_','S','t','o','r','a','g','e','s',0};
997 if( !lstrcmpW( name, szTables ) || !lstrcmpW( name, szColumns ) ||
998 !lstrcmpW( name, szStreams ) || !lstrcmpW( name, szStorages ) )
999 return TRUE;
1001 r = msi_string2idW( db->strings, name, &table_id );
1002 if( r != ERROR_SUCCESS )
1004 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1005 return FALSE;
1008 r = get_table( db, szTables, &table );
1009 if( r != ERROR_SUCCESS )
1011 ERR("table %s not available\n", debugstr_w(szTables));
1012 return FALSE;
1015 count = table->row_count;
1016 for( i=0; i<count; i++ )
1017 if( table->data[ i ][ 0 ] == table_id )
1018 return TRUE;
1020 return FALSE;
1023 /* below is the query interface to a table */
1025 typedef struct tagMSITABLEVIEW
1027 MSIVIEW view;
1028 MSIDATABASE *db;
1029 MSITABLE *table;
1030 MSICOLUMNINFO *columns;
1031 MSIORDERINFO *order;
1032 UINT num_cols;
1033 UINT row_size;
1034 WCHAR name[1];
1035 } MSITABLEVIEW;
1037 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1039 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1040 UINT offset, n;
1042 if( !tv->table )
1043 return ERROR_INVALID_PARAMETER;
1045 if( (col==0) || (col>tv->num_cols) )
1046 return ERROR_INVALID_PARAMETER;
1048 /* how many rows are there ? */
1049 if( row >= tv->table->row_count )
1050 return ERROR_NO_MORE_ITEMS;
1052 if( tv->columns[col-1].offset >= tv->row_size )
1054 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1055 ERR("%p %p\n", tv, tv->columns );
1056 return ERROR_FUNCTION_FAILED;
1059 if (tv->order)
1060 row = tv->order->reorder[row];
1062 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1063 if (n != 2 && n != 3 && n != 4)
1065 ERR("oops! what is %d bytes per column?\n", n );
1066 return ERROR_FUNCTION_FAILED;
1069 offset = tv->columns[col-1].offset;
1070 *val = read_table_int(tv->table->data, row, offset, n);
1072 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1074 return ERROR_SUCCESS;
1077 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1079 LPWSTR p, stname = NULL;
1080 UINT i, r, type, ival;
1081 DWORD len;
1082 LPCWSTR sval;
1083 MSIVIEW *view = (MSIVIEW *) tv;
1085 TRACE("%p %d\n", tv, row);
1087 len = lstrlenW( tv->name ) + 1;
1088 stname = msi_alloc( len*sizeof(WCHAR) );
1089 if ( !stname )
1091 r = ERROR_OUTOFMEMORY;
1092 goto err;
1095 lstrcpyW( stname, tv->name );
1097 for ( i = 0; i < tv->num_cols; i++ )
1099 type = tv->columns[i].type;
1100 if ( type & MSITYPE_KEY )
1102 r = TABLE_fetch_int( view, row, i+1, &ival );
1103 if ( r != ERROR_SUCCESS )
1104 goto err;
1106 if ( tv->columns[i].type & MSITYPE_STRING )
1108 sval = msi_string_lookup_id( tv->db->strings, ival );
1109 if ( !sval )
1111 r = ERROR_INVALID_PARAMETER;
1112 goto err;
1115 else
1117 static const WCHAR fmt[] = { '%','d',0 };
1118 WCHAR number[0x20];
1119 UINT n = bytes_per_column( tv->db, &tv->columns[i] );
1121 switch( n )
1123 case 2:
1124 sprintfW( number, fmt, ival-0x8000 );
1125 break;
1126 case 4:
1127 sprintfW( number, fmt, ival^0x80000000 );
1128 break;
1129 default:
1130 ERR( "oops - unknown column width %d\n", n );
1131 r = ERROR_FUNCTION_FAILED;
1132 goto err;
1134 sval = number;
1137 len += lstrlenW( szDot ) + lstrlenW( sval );
1138 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1139 if ( !p )
1141 r = ERROR_OUTOFMEMORY;
1142 goto err;
1144 stname = p;
1146 lstrcatW( stname, szDot );
1147 lstrcatW( stname, sval );
1149 else
1150 continue;
1153 *pstname = stname;
1154 return ERROR_SUCCESS;
1156 err:
1157 msi_free( stname );
1158 *pstname = NULL;
1159 return r;
1163 * We need a special case for streams, as we need to reference column with
1164 * the name of the stream in the same table, and the table name
1165 * which may not be available at higher levels of the query
1167 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1169 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1170 UINT r;
1171 LPWSTR full_name = NULL;
1173 if( !view->ops->fetch_int )
1174 return ERROR_INVALID_PARAMETER;
1176 r = msi_stream_name( tv, row, &full_name );
1177 if ( r != ERROR_SUCCESS )
1179 ERR("fetching stream, error = %d\n", r);
1180 return r;
1183 r = db_get_raw_stream( tv->db, full_name, stm );
1184 if( r )
1185 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1186 msi_free( full_name );
1188 return r;
1191 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1193 UINT offset, n, i;
1195 if( !tv->table )
1196 return ERROR_INVALID_PARAMETER;
1198 if( (col==0) || (col>tv->num_cols) )
1199 return ERROR_INVALID_PARAMETER;
1201 if( row >= tv->table->row_count )
1202 return ERROR_INVALID_PARAMETER;
1204 if( tv->columns[col-1].offset >= tv->row_size )
1206 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1207 ERR("%p %p\n", tv, tv->columns );
1208 return ERROR_FUNCTION_FAILED;
1211 msi_free( tv->columns[col-1].hash_table );
1212 tv->columns[col-1].hash_table = NULL;
1214 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1215 if ( n != 2 && n != 3 && n != 4 )
1217 ERR("oops! what is %d bytes per column?\n", n );
1218 return ERROR_FUNCTION_FAILED;
1221 offset = tv->columns[col-1].offset;
1222 for ( i = 0; i < n; i++ )
1223 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1225 return ERROR_SUCCESS;
1228 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1230 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1232 if (!tv->table)
1233 return ERROR_INVALID_PARAMETER;
1235 if (tv->order)
1236 row = tv->order->reorder[row];
1238 return msi_view_get_row(tv->db, view, row, rec);
1241 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1243 UINT r;
1244 MSIQUERY *query = NULL;
1245 MSIRECORD *rec = NULL;
1247 static const WCHAR insert[] = {
1248 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1249 '`','_','S','t','r','e','a','m','s','`',' ',
1250 '(','`','N','a','m','e','`',',',
1251 '`','D','a','t','a','`',')',' ',
1252 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1254 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1256 rec = MSI_CreateRecord( 2 );
1257 if ( !rec )
1258 return ERROR_OUTOFMEMORY;
1260 r = MSI_RecordSetStringW( rec, 1, name );
1261 if ( r != ERROR_SUCCESS )
1262 goto err;
1264 r = MSI_RecordSetIStream( rec, 2, data );
1265 if ( r != ERROR_SUCCESS )
1266 goto err;
1268 r = MSI_DatabaseOpenViewW( db, insert, &query );
1269 if ( r != ERROR_SUCCESS )
1270 goto err;
1272 r = MSI_ViewExecute( query, rec );
1274 err:
1275 msiobj_release( &query->hdr );
1276 msiobj_release( &rec->hdr );
1278 return r;
1281 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1283 MSICOLUMNINFO columninfo;
1284 UINT r;
1286 if ( (iField <= 0) ||
1287 (iField > tv->num_cols) ||
1288 MSI_RecordIsNull( rec, iField ) )
1289 return ERROR_FUNCTION_FAILED;
1291 columninfo = tv->columns[ iField - 1 ];
1293 if ( MSITYPE_IS_BINARY(columninfo.type) )
1295 *pvalue = 1; /* refers to the first key column */
1297 else if ( columninfo.type & MSITYPE_STRING )
1299 LPCWSTR sval = MSI_RecordGetString( rec, iField );
1301 r = msi_string2idW(tv->db->strings, sval, pvalue);
1302 if (r != ERROR_SUCCESS)
1303 return ERROR_NOT_FOUND;
1305 else if ( 2 == bytes_per_column( tv->db, &columninfo ) )
1307 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1308 if ( *pvalue & 0xffff0000 )
1310 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1311 return ERROR_FUNCTION_FAILED;
1314 else
1316 INT ival = MSI_RecordGetInteger( rec, iField );
1317 *pvalue = ival ^ 0x80000000;
1320 return ERROR_SUCCESS;
1323 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1325 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1326 UINT i, val, r = ERROR_SUCCESS;
1328 if ( !tv->table )
1329 return ERROR_INVALID_PARAMETER;
1331 /* test if any of the mask bits are invalid */
1332 if ( mask >= (1<<tv->num_cols) )
1333 return ERROR_INVALID_PARAMETER;
1335 for ( i = 0; i < tv->num_cols; i++ )
1337 BOOL persistent;
1339 /* only update the fields specified in the mask */
1340 if ( !(mask&(1<<i)) )
1341 continue;
1343 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1344 (tv->table->data_persistent[row]);
1345 /* FIXME: should we allow updating keys? */
1347 val = 0;
1348 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1350 r = get_table_value_from_record (tv, rec, i + 1, &val);
1351 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1353 IStream *stm;
1354 LPWSTR stname;
1356 if ( r != ERROR_SUCCESS )
1357 return ERROR_FUNCTION_FAILED;
1359 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1360 if ( r != ERROR_SUCCESS )
1361 return r;
1363 r = msi_stream_name( tv, row, &stname );
1364 if ( r != ERROR_SUCCESS )
1366 IStream_Release( stm );
1367 return r;
1370 r = msi_addstreamW( tv->db, stname, stm );
1371 IStream_Release( stm );
1372 msi_free ( stname );
1374 if ( r != ERROR_SUCCESS )
1375 return r;
1377 else if ( tv->columns[i].type & MSITYPE_STRING )
1379 UINT x;
1381 if ( r != ERROR_SUCCESS )
1383 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1384 val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
1385 persistent ? StringPersistent : StringNonPersistent );
1388 else
1390 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1391 if (val == x)
1392 continue;
1395 else
1397 if ( r != ERROR_SUCCESS )
1398 return ERROR_FUNCTION_FAILED;
1402 r = TABLE_set_int( tv, row, i+1, val );
1403 if ( r != ERROR_SUCCESS )
1404 break;
1406 return r;
1409 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1411 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1412 BYTE **p, *row;
1413 BOOL *b;
1414 UINT sz;
1415 BYTE ***data_ptr;
1416 BOOL **data_persist_ptr;
1417 UINT *row_count;
1419 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1421 if( !tv->table )
1422 return ERROR_INVALID_PARAMETER;
1424 row = msi_alloc_zero( tv->row_size );
1425 if( !row )
1426 return ERROR_NOT_ENOUGH_MEMORY;
1428 row_count = &tv->table->row_count;
1429 data_ptr = &tv->table->data;
1430 data_persist_ptr = &tv->table->data_persistent;
1431 if (*num == -1)
1432 *num = tv->table->row_count;
1434 sz = (*row_count + 1) * sizeof (BYTE*);
1435 if( *data_ptr )
1436 p = msi_realloc( *data_ptr, sz );
1437 else
1438 p = msi_alloc( sz );
1439 if( !p )
1441 msi_free( row );
1442 return ERROR_NOT_ENOUGH_MEMORY;
1445 sz = (*row_count + 1) * sizeof (BOOL);
1446 if( *data_persist_ptr )
1447 b = msi_realloc( *data_persist_ptr, sz );
1448 else
1449 b = msi_alloc( sz );
1450 if( !b )
1452 msi_free( row );
1453 msi_free( p );
1454 return ERROR_NOT_ENOUGH_MEMORY;
1457 *data_ptr = p;
1458 (*data_ptr)[*row_count] = row;
1460 *data_persist_ptr = b;
1461 (*data_persist_ptr)[*row_count] = !temporary;
1463 (*row_count)++;
1465 return ERROR_SUCCESS;
1468 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1470 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1472 TRACE("%p %p\n", tv, record);
1474 TRACE("There are %d columns\n", tv->num_cols );
1476 return ERROR_SUCCESS;
1479 static UINT TABLE_close( struct tagMSIVIEW *view )
1481 TRACE("%p\n", view );
1483 return ERROR_SUCCESS;
1486 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1488 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1490 TRACE("%p %p %p\n", view, rows, cols );
1492 if( cols )
1493 *cols = tv->num_cols;
1494 if( rows )
1496 if( !tv->table )
1497 return ERROR_INVALID_PARAMETER;
1498 *rows = tv->table->row_count;
1501 return ERROR_SUCCESS;
1504 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1505 UINT n, LPWSTR *name, UINT *type, BOOL *temporary,
1506 LPWSTR *table_name )
1508 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1510 TRACE("%p %d %p %p\n", tv, n, name, type );
1512 if( ( n == 0 ) || ( n > tv->num_cols ) )
1513 return ERROR_INVALID_PARAMETER;
1515 if( name )
1517 *name = strdupW( tv->columns[n-1].colname );
1518 if( !*name )
1519 return ERROR_FUNCTION_FAILED;
1522 if( table_name )
1524 *table_name = strdupW( tv->columns[n-1].tablename );
1525 if( !*table_name )
1526 return ERROR_FUNCTION_FAILED;
1529 if( type )
1530 *type = tv->columns[n-1].type;
1532 if( temporary )
1533 *temporary = tv->columns[n-1].temporary;
1535 return ERROR_SUCCESS;
1538 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1540 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1542 UINT r, row, i;
1544 /* check there's no null values where they're not allowed */
1545 for( i = 0; i < tv->num_cols; i++ )
1547 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1548 continue;
1550 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1551 TRACE("skipping binary column\n");
1552 else if ( tv->columns[i].type & MSITYPE_STRING )
1554 LPCWSTR str;
1556 str = MSI_RecordGetString( rec, i+1 );
1557 if (str == NULL || str[0] == 0)
1558 return ERROR_INVALID_DATA;
1560 else
1562 UINT n;
1564 n = MSI_RecordGetInteger( rec, i+1 );
1565 if (n == MSI_NULL_INTEGER)
1566 return ERROR_INVALID_DATA;
1570 /* check there's no duplicate keys */
1571 r = msi_table_find_row( tv, rec, &row );
1572 if (r == ERROR_SUCCESS)
1573 return ERROR_FUNCTION_FAILED;
1575 return ERROR_SUCCESS;
1578 static UINT find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *pidx )
1580 UINT r, idx, j, ivalue, x;
1582 TRACE("%p %p %p\n", tv, rec, pidx);
1584 for (idx = 0; idx < tv->table->row_count; idx++)
1586 for (j = 0; j < tv->num_cols; j++ )
1588 r = get_table_value_from_record (tv, rec, j+1, &ivalue);
1589 if (r != ERROR_SUCCESS)
1590 break;
1592 r = TABLE_fetch_int(&tv->view, idx, j + 1, &x);
1593 if (r != ERROR_SUCCESS)
1594 return r;
1596 if (ivalue > x)
1597 break;
1598 else if (ivalue == x)
1599 continue;
1600 else {
1601 TRACE("Found %d.\n", idx);
1602 *pidx = idx;
1603 return ERROR_SUCCESS;
1608 TRACE("Found %d.\n", idx);
1609 *pidx = idx;
1610 return ERROR_SUCCESS;
1613 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1615 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1616 UINT i, r;
1618 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1620 /* check that the key is unique - can we find a matching row? */
1621 r = table_validate_new( tv, rec );
1622 if( r != ERROR_SUCCESS )
1623 return ERROR_FUNCTION_FAILED;
1625 if (row == -1)
1627 r = find_insert_index(tv, rec, &row);
1628 if( r != ERROR_SUCCESS )
1629 return ERROR_FUNCTION_FAILED;
1632 r = table_create_new_row( view, &row, temporary );
1633 TRACE("insert_row returned %08x\n", r);
1634 if( r != ERROR_SUCCESS )
1635 return r;
1637 /* shift the rows to make room for the new row */
1638 for (i = tv->table->row_count - 1; i > row; i--)
1640 memmove(&(tv->table->data[i][0]),
1641 &(tv->table->data[i - 1][0]), tv->row_size);
1642 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1645 /* Re-set the persistence flag */
1646 tv->table->data_persistent[row] = !temporary;
1647 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1650 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1652 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1653 UINT r, num_rows, num_cols, i;
1655 TRACE("%p %d\n", tv, row);
1657 if ( !tv->table )
1658 return ERROR_INVALID_PARAMETER;
1660 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1661 if ( r != ERROR_SUCCESS )
1662 return r;
1664 if ( row >= num_rows )
1665 return ERROR_FUNCTION_FAILED;
1667 num_rows = tv->table->row_count;
1668 tv->table->row_count--;
1670 /* reset the hash tables */
1671 for (i = 0; i < tv->num_cols; i++)
1673 msi_free( tv->columns[i].hash_table );
1674 tv->columns[i].hash_table = NULL;
1677 for (i = row + 1; i < num_rows; i++)
1679 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1680 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1683 msi_free(tv->table->data[num_rows - 1]);
1685 return ERROR_SUCCESS;
1688 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1690 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1691 UINT r, new_row;
1693 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1694 * sets the fetched record apart from other records
1697 if (!tv->table)
1698 return ERROR_INVALID_PARAMETER;
1700 r = msi_table_find_row(tv, rec, &new_row);
1701 if (r != ERROR_SUCCESS)
1703 ERR("can't find row to modify\n");
1704 return ERROR_FUNCTION_FAILED;
1707 /* the row cannot be changed */
1708 if (row != new_row + 1)
1709 return ERROR_FUNCTION_FAILED;
1711 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1714 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1716 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1717 UINT r, row;
1719 if (!tv->table)
1720 return ERROR_INVALID_PARAMETER;
1722 r = msi_table_find_row(tv, rec, &row);
1723 if (r == ERROR_SUCCESS)
1724 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1725 else
1726 return TABLE_insert_row( view, rec, -1, FALSE );
1729 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1731 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1732 UINT row, r;
1734 r = msi_table_find_row(tv, rec, &row);
1735 if (r != ERROR_SUCCESS)
1736 return r;
1738 return TABLE_delete_row(view, row);
1741 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1743 MSIRECORD *curr;
1744 UINT r, i, count;
1746 r = TABLE_get_row(view, row - 1, &curr);
1747 if (r != ERROR_SUCCESS)
1748 return r;
1750 /* Close the original record */
1751 MSI_CloseRecord(&rec->hdr);
1753 count = MSI_RecordGetFieldCount(rec);
1754 for (i = 0; i < count; i++)
1755 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1757 msiobj_release(&curr->hdr);
1758 return ERROR_SUCCESS;
1761 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1762 MSIRECORD *rec, UINT row)
1764 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1765 UINT r;
1767 TRACE("%p %d %p\n", view, eModifyMode, rec );
1769 switch (eModifyMode)
1771 case MSIMODIFY_DELETE:
1772 r = modify_delete_row( view, rec );
1773 break;
1774 case MSIMODIFY_VALIDATE_NEW:
1775 r = table_validate_new( tv, rec );
1776 break;
1778 case MSIMODIFY_INSERT:
1779 r = table_validate_new( tv, rec );
1780 if (r != ERROR_SUCCESS)
1781 break;
1782 r = TABLE_insert_row( view, rec, -1, FALSE );
1783 break;
1785 case MSIMODIFY_INSERT_TEMPORARY:
1786 r = table_validate_new( tv, rec );
1787 if (r != ERROR_SUCCESS)
1788 break;
1789 r = TABLE_insert_row( view, rec, -1, TRUE );
1790 break;
1792 case MSIMODIFY_REFRESH:
1793 r = msi_refresh_record( view, rec, row );
1794 break;
1796 case MSIMODIFY_UPDATE:
1797 r = msi_table_update( view, rec, row );
1798 break;
1800 case MSIMODIFY_ASSIGN:
1801 r = msi_table_assign( view, rec );
1802 break;
1804 case MSIMODIFY_REPLACE:
1805 case MSIMODIFY_MERGE:
1806 case MSIMODIFY_VALIDATE:
1807 case MSIMODIFY_VALIDATE_FIELD:
1808 case MSIMODIFY_VALIDATE_DELETE:
1809 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1810 r = ERROR_CALL_NOT_IMPLEMENTED;
1811 break;
1813 default:
1814 r = ERROR_INVALID_DATA;
1817 return r;
1820 static UINT TABLE_delete( struct tagMSIVIEW *view )
1822 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1824 TRACE("%p\n", view );
1826 tv->table = NULL;
1827 tv->columns = NULL;
1829 if (tv->order)
1831 msi_free( tv->order->reorder );
1832 msi_free( tv->order );
1833 tv->order = NULL;
1836 msi_free( tv );
1838 return ERROR_SUCCESS;
1841 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1842 UINT val, UINT *row, MSIITERHANDLE *handle )
1844 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1845 const MSICOLUMNHASHENTRY *entry;
1847 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1849 if( !tv->table )
1850 return ERROR_INVALID_PARAMETER;
1852 if( (col==0) || (col > tv->num_cols) )
1853 return ERROR_INVALID_PARAMETER;
1855 if( !tv->columns[col-1].hash_table )
1857 UINT i;
1858 UINT num_rows = tv->table->row_count;
1859 MSICOLUMNHASHENTRY **hash_table;
1860 MSICOLUMNHASHENTRY *new_entry;
1862 if( tv->columns[col-1].offset >= tv->row_size )
1864 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1865 ERR("%p %p\n", tv, tv->columns );
1866 return ERROR_FUNCTION_FAILED;
1869 /* allocate contiguous memory for the table and its entries so we
1870 * don't have to do an expensive cleanup */
1871 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1872 num_rows * sizeof(MSICOLUMNHASHENTRY));
1873 if (!hash_table)
1874 return ERROR_OUTOFMEMORY;
1876 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1877 tv->columns[col-1].hash_table = hash_table;
1879 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1881 for (i = 0; i < num_rows; i++, new_entry++)
1883 UINT row_value;
1885 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1886 continue;
1888 new_entry->next = NULL;
1889 new_entry->value = row_value;
1890 new_entry->row = i;
1891 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1893 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1894 while (prev_entry->next)
1895 prev_entry = prev_entry->next;
1896 prev_entry->next = new_entry;
1898 else
1899 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1903 if( !*handle )
1904 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1905 else
1906 entry = (*handle)->next;
1908 while (entry && entry->value != val)
1909 entry = entry->next;
1911 *handle = entry;
1912 if (!entry)
1913 return ERROR_NO_MORE_ITEMS;
1915 *row = entry->row;
1917 return ERROR_SUCCESS;
1920 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1922 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1923 UINT i;
1925 TRACE("%p %d\n", view, tv->table->ref_count);
1927 for (i = 0; i < tv->table->col_count; i++)
1929 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1930 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1933 return InterlockedIncrement(&tv->table->ref_count);
1936 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1938 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1939 MSIRECORD *rec = NULL;
1940 MSIVIEW *columns = NULL;
1941 UINT row, r;
1943 rec = MSI_CreateRecord(2);
1944 if (!rec)
1945 return ERROR_OUTOFMEMORY;
1947 MSI_RecordSetStringW(rec, 1, table);
1948 MSI_RecordSetInteger(rec, 2, number);
1950 r = TABLE_CreateView(tv->db, szColumns, &columns);
1951 if (r != ERROR_SUCCESS)
1952 return r;
1954 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
1955 if (r != ERROR_SUCCESS)
1956 goto done;
1958 r = TABLE_delete_row(columns, row);
1959 if (r != ERROR_SUCCESS)
1960 goto done;
1962 msi_update_table_columns(tv->db, table);
1964 done:
1965 msiobj_release(&rec->hdr);
1966 columns->ops->delete(columns);
1967 return r;
1970 static UINT TABLE_release(struct tagMSIVIEW *view)
1972 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1973 INT ref = tv->table->ref_count;
1974 UINT i, r;
1976 TRACE("%p %d\n", view, ref);
1978 for (i = 0; i < tv->table->col_count; i++)
1980 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1982 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1983 if (ref == 0)
1985 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1986 tv->table->colinfo[i].number);
1987 if (r != ERROR_SUCCESS)
1988 break;
1993 ref = InterlockedDecrement(&tv->table->ref_count);
1994 if (ref == 0)
1996 if (!tv->table->row_count)
1998 list_remove(&tv->table->entry);
1999 free_table(tv->table);
2000 TABLE_delete(view);
2004 return ref;
2007 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2008 LPCWSTR column, UINT type, BOOL hold)
2010 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2011 MSITABLE *msitable;
2012 MSIRECORD *rec;
2013 UINT r, i;
2015 rec = MSI_CreateRecord(4);
2016 if (!rec)
2017 return ERROR_OUTOFMEMORY;
2019 MSI_RecordSetStringW(rec, 1, table);
2020 MSI_RecordSetInteger(rec, 2, number);
2021 MSI_RecordSetStringW(rec, 3, column);
2022 MSI_RecordSetInteger(rec, 4, type);
2024 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2025 if (r != ERROR_SUCCESS)
2026 goto done;
2028 msi_update_table_columns(tv->db, table);
2030 if (!hold)
2031 goto done;
2033 msitable = find_cached_table(tv->db, table);
2034 for (i = 0; i < msitable->col_count; i++)
2036 if (!lstrcmpW(msitable->colinfo[i].colname, column))
2038 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2039 break;
2043 done:
2044 msiobj_release(&rec->hdr);
2045 return r;
2048 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2050 UINT n, r, count;
2051 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2053 r = TABLE_get_dimensions(view, NULL, &count);
2054 if (r != ERROR_SUCCESS)
2055 return r;
2057 if (order->num_cols >= count)
2058 return ERROR_FUNCTION_FAILED;
2060 r = VIEW_find_column(view, name, tv->name, &n);
2061 if (r != ERROR_SUCCESS)
2062 return r;
2064 order->cols[order->num_cols] = n;
2065 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2067 order->num_cols++;
2069 return ERROR_SUCCESS;
2072 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2073 UINT a, UINT b, UINT *swap)
2075 UINT r, i, a_val = 0, b_val = 0;
2077 *swap = 0;
2078 for (i = 0; i < order->num_cols; i++)
2080 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2081 if (r != ERROR_SUCCESS)
2082 return r;
2084 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2085 if (r != ERROR_SUCCESS)
2086 return r;
2088 if (a_val != b_val)
2090 if (a_val > b_val)
2091 *swap = 1;
2092 break;
2096 return ERROR_SUCCESS;
2099 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2100 UINT left, UINT right)
2102 UINT r, i, j, temp;
2103 UINT swap = 0, center = (left + right) / 2;
2104 UINT *array = order->reorder;
2106 if (left == right)
2107 return ERROR_SUCCESS;
2109 /* sort the left half */
2110 r = order_mergesort(view, order, left, center);
2111 if (r != ERROR_SUCCESS)
2112 return r;
2114 /* sort the right half */
2115 r = order_mergesort(view, order, center + 1, right);
2116 if (r != ERROR_SUCCESS)
2117 return r;
2119 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2121 r = order_compare(view, order, array[i], array[j], &swap);
2122 if (r != ERROR_SUCCESS)
2123 return r;
2125 if (swap)
2127 temp = array[j];
2128 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2129 array[i] = temp;
2130 j++;
2131 center++;
2135 return ERROR_SUCCESS;
2138 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2140 UINT i, swap, r;
2142 for (i = 1; i < num_rows; i++)
2144 r = order_compare(view, order, order->reorder[i - 1],
2145 order->reorder[i], &swap);
2146 if (r != ERROR_SUCCESS)
2147 return r;
2149 if (!swap)
2150 continue;
2152 ERR("Bad order! %d\n", i);
2153 return ERROR_FUNCTION_FAILED;
2156 return ERROR_SUCCESS;
2159 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2161 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2162 MSIORDERINFO *order;
2163 column_info *ptr;
2164 UINT r, i;
2165 UINT rows, cols;
2167 TRACE("sorting table %s\n", debugstr_w(tv->name));
2169 r = TABLE_get_dimensions(view, &rows, &cols);
2170 if (r != ERROR_SUCCESS)
2171 return r;
2173 if (rows == 0)
2174 return ERROR_SUCCESS;
2176 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2177 if (!order)
2178 return ERROR_OUTOFMEMORY;
2180 for (ptr = columns; ptr; ptr = ptr->next)
2181 order_add_column(view, order, ptr->column);
2183 order->reorder = msi_alloc(rows * sizeof(UINT));
2184 if (!order->reorder)
2185 return ERROR_OUTOFMEMORY;
2187 for (i = 0; i < rows; i++)
2188 order->reorder[i] = i;
2190 r = order_mergesort(view, order, 0, rows - 1);
2191 if (r != ERROR_SUCCESS)
2192 return r;
2194 r = order_verify(view, order, rows);
2195 if (r != ERROR_SUCCESS)
2196 return r;
2198 tv->order = order;
2200 return ERROR_SUCCESS;
2203 static UINT TABLE_drop(struct tagMSIVIEW *view)
2205 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2206 MSIVIEW *tables = NULL;
2207 MSIRECORD *rec = NULL;
2208 UINT r, row;
2209 INT i;
2211 TRACE("dropping table %s\n", debugstr_w(tv->name));
2213 for (i = tv->table->col_count - 1; i >= 0; i--)
2215 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2216 tv->table->colinfo[i].number);
2217 if (r != ERROR_SUCCESS)
2218 return r;
2221 rec = MSI_CreateRecord(1);
2222 if (!rec)
2223 return ERROR_OUTOFMEMORY;
2225 MSI_RecordSetStringW(rec, 1, tv->name);
2227 r = TABLE_CreateView(tv->db, szTables, &tables);
2228 if (r != ERROR_SUCCESS)
2229 return r;
2231 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
2232 if (r != ERROR_SUCCESS)
2233 goto done;
2235 r = TABLE_delete_row(tables, row);
2236 if (r != ERROR_SUCCESS)
2237 goto done;
2239 list_remove(&tv->table->entry);
2240 free_table(tv->table);
2242 done:
2243 msiobj_release(&rec->hdr);
2244 tables->ops->delete(tables);
2246 return r;
2249 static const MSIVIEWOPS table_ops =
2251 TABLE_fetch_int,
2252 TABLE_fetch_stream,
2253 TABLE_get_row,
2254 TABLE_set_row,
2255 TABLE_insert_row,
2256 TABLE_delete_row,
2257 TABLE_execute,
2258 TABLE_close,
2259 TABLE_get_dimensions,
2260 TABLE_get_column_info,
2261 TABLE_modify,
2262 TABLE_delete,
2263 TABLE_find_matching_rows,
2264 TABLE_add_ref,
2265 TABLE_release,
2266 TABLE_add_column,
2267 TABLE_remove_column,
2268 TABLE_sort,
2269 TABLE_drop,
2272 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2274 MSITABLEVIEW *tv ;
2275 UINT r, sz;
2277 static const WCHAR Streams[] = {'_','S','t','r','e','a','m','s',0};
2278 static const WCHAR Storages[] = {'_','S','t','o','r','a','g','e','s',0};
2280 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2282 if ( !lstrcmpW( name, Streams ) )
2283 return STREAMS_CreateView( db, view );
2284 else if ( !lstrcmpW( name, Storages ) )
2285 return STORAGES_CreateView( db, view );
2287 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2288 tv = msi_alloc_zero( sz );
2289 if( !tv )
2290 return ERROR_FUNCTION_FAILED;
2292 r = get_table( db, name, &tv->table );
2293 if( r != ERROR_SUCCESS )
2295 msi_free( tv );
2296 WARN("table not found\n");
2297 return r;
2300 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2302 /* fill the structure */
2303 tv->view.ops = &table_ops;
2304 tv->db = db;
2305 tv->columns = tv->table->colinfo;
2306 tv->num_cols = tv->table->col_count;
2307 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count );
2309 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2311 *view = (MSIVIEW*) tv;
2312 lstrcpyW( tv->name, name );
2314 return ERROR_SUCCESS;
2317 UINT MSI_CommitTables( MSIDATABASE *db )
2319 UINT r;
2320 MSITABLE *table = NULL;
2322 TRACE("%p\n",db);
2324 r = msi_save_string_table( db->strings, db->storage );
2325 if( r != ERROR_SUCCESS )
2327 WARN("failed to save string table r=%08x\n",r);
2328 return r;
2331 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2333 r = save_table( db, table );
2334 if( r != ERROR_SUCCESS )
2336 WARN("failed to save table %s (r=%08x)\n",
2337 debugstr_w(table->name), r);
2338 return r;
2342 /* force everything to reload next time */
2343 free_cached_tables( db );
2345 return ERROR_SUCCESS;
2348 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2350 MSITABLE *t;
2351 UINT r;
2353 TRACE("%p %s\n", db, debugstr_w(table));
2355 if (!table)
2356 return MSICONDITION_ERROR;
2358 r = get_table( db, table, &t );
2359 if (r != ERROR_SUCCESS)
2360 return MSICONDITION_NONE;
2362 return t->persistent;
2365 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2367 UINT ret = 0, i;
2369 for (i = 0; i < bytes; i++)
2370 ret += (data[col + i] << i * 8);
2372 return ret;
2375 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2377 LPWSTR stname = NULL, sval, p;
2378 DWORD len;
2379 UINT i, r;
2381 TRACE("%p %p\n", tv, rec);
2383 len = lstrlenW( tv->name ) + 1;
2384 stname = msi_alloc( len*sizeof(WCHAR) );
2385 if ( !stname )
2387 r = ERROR_OUTOFMEMORY;
2388 goto err;
2391 lstrcpyW( stname, tv->name );
2393 for ( i = 0; i < tv->num_cols; i++ )
2395 if ( tv->columns[i].type & MSITYPE_KEY )
2397 sval = msi_dup_record_field( rec, i + 1 );
2398 if ( !sval )
2400 r = ERROR_OUTOFMEMORY;
2401 goto err;
2404 len += lstrlenW( szDot ) + lstrlenW ( sval );
2405 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2406 if ( !p )
2408 r = ERROR_OUTOFMEMORY;
2409 goto err;
2411 stname = p;
2413 lstrcatW( stname, szDot );
2414 lstrcatW( stname, sval );
2416 msi_free( sval );
2418 else
2419 continue;
2422 *pstname = encode_streamname( FALSE, stname );
2423 msi_free( stname );
2425 return ERROR_SUCCESS;
2427 err:
2428 msi_free ( stname );
2429 *pstname = NULL;
2430 return r;
2433 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2434 IStorage *stg,
2435 const BYTE *rawdata, UINT bytes_per_strref )
2437 UINT i, val, ofs = 0;
2438 USHORT mask;
2439 MSICOLUMNINFO *columns = tv->columns;
2440 MSIRECORD *rec;
2442 mask = rawdata[0] | (rawdata[1] << 8);
2443 rawdata += 2;
2445 rec = MSI_CreateRecord( tv->num_cols );
2446 if( !rec )
2447 return rec;
2449 TRACE("row ->\n");
2450 for( i=0; i<tv->num_cols; i++ )
2452 if ( (mask&1) && (i>=(mask>>8)) )
2453 break;
2454 /* all keys must be present */
2455 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2456 continue;
2458 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2460 LPWSTR encname;
2461 IStream *stm = NULL;
2462 UINT r;
2464 ofs += bytes_per_column( tv->db, &columns[i] );
2466 r = msi_record_encoded_stream_name( tv, rec, &encname );
2467 if ( r != ERROR_SUCCESS )
2468 return NULL;
2470 r = IStorage_OpenStream( stg, encname, NULL,
2471 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2472 msi_free( encname );
2473 if ( r != ERROR_SUCCESS )
2474 return NULL;
2476 MSI_RecordSetStream( rec, i+1, stm );
2477 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2479 else if( columns[i].type & MSITYPE_STRING )
2481 LPCWSTR sval;
2483 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2484 sval = msi_string_lookup_id( st, val );
2485 MSI_RecordSetStringW( rec, i+1, sval );
2486 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2487 ofs += bytes_per_strref;
2489 else
2491 UINT n = bytes_per_column( tv->db, &columns[i] );
2492 switch( n )
2494 case 2:
2495 val = read_raw_int(rawdata, ofs, n);
2496 if (val)
2497 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2498 TRACE(" field %d [0x%04x]\n", i+1, val );
2499 break;
2500 case 4:
2501 val = read_raw_int(rawdata, ofs, n);
2502 if (val)
2503 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2504 TRACE(" field %d [0x%08x]\n", i+1, val );
2505 break;
2506 default:
2507 ERR("oops - unknown column width %d\n", n);
2508 break;
2510 ofs += n;
2513 return rec;
2516 static void dump_record( MSIRECORD *rec )
2518 UINT i, n;
2520 n = MSI_RecordGetFieldCount( rec );
2521 for( i=1; i<=n; i++ )
2523 LPCWSTR sval = MSI_RecordGetString( rec, i );
2525 if( MSI_RecordIsNull( rec, i ) )
2526 TRACE("row -> []\n");
2527 else if( (sval = MSI_RecordGetString( rec, i )) )
2528 TRACE("row -> [%s]\n", debugstr_w(sval));
2529 else
2530 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2534 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2536 LPCWSTR sval;
2537 UINT i;
2539 for( i=0; i<(rawsize/2); i++ )
2541 sval = msi_string_lookup_id( st, rawdata[i] );
2542 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2546 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2548 LPCWSTR str;
2549 UINT i, r, *data;
2551 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2552 for( i=0; i<tv->num_cols; i++ )
2554 data[i] = 0;
2556 if ( ~tv->columns[i].type & MSITYPE_KEY )
2557 continue;
2559 /* turn the transform column value into a row value */
2560 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2561 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2563 str = MSI_RecordGetString( rec, i+1 );
2564 r = msi_string2idW( tv->db->strings, str, &data[i] );
2566 /* if there's no matching string in the string table,
2567 these keys can't match any record, so fail now. */
2568 if( ERROR_SUCCESS != r )
2570 msi_free( data );
2571 return NULL;
2574 else
2576 data[i] = MSI_RecordGetInteger( rec, i+1 );
2578 if (data[i] == MSI_NULL_INTEGER)
2579 data[i] = 0;
2580 else if ((tv->columns[i].type&0xff) == 2)
2581 data[i] += 0x8000;
2582 else
2583 data[i] += 0x80000000;
2586 return data;
2589 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2591 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2593 for( i=0; i<tv->num_cols; i++ )
2595 if ( ~tv->columns[i].type & MSITYPE_KEY )
2596 continue;
2598 /* turn the transform column value into a row value */
2599 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2600 if ( r != ERROR_SUCCESS )
2602 ERR("TABLE_fetch_int shouldn't fail here\n");
2603 break;
2606 /* if this key matches, move to the next column */
2607 if ( x != data[i] )
2609 ret = ERROR_FUNCTION_FAILED;
2610 break;
2613 ret = ERROR_SUCCESS;
2616 return ret;
2619 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
2621 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2623 data = msi_record_to_row( tv, rec );
2624 if( !data )
2625 return r;
2626 for( i = 0; i < tv->table->row_count; i++ )
2628 r = msi_row_matches( tv, i, data );
2629 if( r == ERROR_SUCCESS )
2631 *row = i;
2632 break;
2635 msi_free( data );
2636 return r;
2639 typedef struct
2641 struct list entry;
2642 LPWSTR name;
2643 } TRANSFORMDATA;
2645 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2646 string_table *st, TRANSFORMDATA *transform,
2647 UINT bytes_per_strref )
2649 UINT rawsize = 0;
2650 BYTE *rawdata = NULL;
2651 MSITABLEVIEW *tv = NULL;
2652 UINT r, n, sz, i, mask;
2653 MSIRECORD *rec = NULL;
2654 UINT colcol = 0;
2655 WCHAR coltable[32];
2656 LPWSTR name;
2658 if (!transform)
2659 return ERROR_SUCCESS;
2661 name = transform->name;
2663 coltable[0] = 0;
2664 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2666 /* read the transform data */
2667 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2668 if ( !rawdata )
2670 TRACE("table %s empty\n", debugstr_w(name) );
2671 return ERROR_INVALID_TABLE;
2674 /* create a table view */
2675 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2676 if( r != ERROR_SUCCESS )
2677 goto err;
2679 r = tv->view.ops->execute( &tv->view, NULL );
2680 if( r != ERROR_SUCCESS )
2681 goto err;
2683 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2684 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2686 /* interpret the data */
2687 r = ERROR_SUCCESS;
2688 for( n=0; n < rawsize; )
2690 mask = rawdata[n] | (rawdata[n+1] << 8);
2692 if (mask&1)
2695 * if the low bit is set, columns are continuous and
2696 * the number of columns is specified in the high byte
2698 sz = 2;
2699 for( i=0; i<tv->num_cols; i++ )
2701 if( (tv->columns[i].type & MSITYPE_STRING) &&
2702 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2703 sz += bytes_per_strref;
2704 else
2705 sz += bytes_per_column( tv->db, &tv->columns[i] );
2708 else
2711 * If the low bit is not set, mask is a bitmask.
2712 * Excepting for key fields, which are always present,
2713 * each bit indicates that a field is present in the transform record.
2715 * mask == 0 is a special case ... only the keys will be present
2716 * and it means that this row should be deleted.
2718 sz = 2;
2719 for( i=0; i<tv->num_cols; i++ )
2721 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2723 if( (tv->columns[i].type & MSITYPE_STRING) &&
2724 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2725 sz += bytes_per_strref;
2726 else
2727 sz += bytes_per_column( tv->db, &tv->columns[i] );
2732 /* check we didn't run of the end of the table */
2733 if ( (n+sz) > rawsize )
2735 ERR("borked.\n");
2736 dump_table( st, (USHORT *)rawdata, rawsize );
2737 break;
2740 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2741 if (rec)
2743 if ( mask & 1 )
2745 WCHAR table[32];
2746 DWORD sz = 32;
2747 UINT number = MSI_NULL_INTEGER;
2749 TRACE("inserting record\n");
2751 if (!lstrcmpW(name, szColumns))
2753 MSI_RecordGetStringW( rec, 1, table, &sz );
2754 number = MSI_RecordGetInteger( rec, 2 );
2757 * Native msi seems writes nul into the Number (2nd) column of
2758 * the _Columns table, only when the columns are from a new table
2760 if ( number == MSI_NULL_INTEGER )
2762 /* reset the column number on a new table */
2763 if ( lstrcmpW(coltable, table) )
2765 colcol = 0;
2766 lstrcpyW( coltable, table );
2769 /* fix nul column numbers */
2770 MSI_RecordSetInteger( rec, 2, ++colcol );
2774 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2775 if (r != ERROR_SUCCESS)
2776 WARN("insert row failed\n");
2778 if ( number != MSI_NULL_INTEGER && !lstrcmpW(name, szColumns) )
2779 msi_update_table_columns( db, table );
2781 else
2783 UINT row = 0;
2785 r = msi_table_find_row( tv, rec, &row );
2786 if (r != ERROR_SUCCESS)
2787 WARN("no matching row to transform\n");
2788 else if ( mask )
2790 TRACE("modifying row [%d]:\n", row);
2791 TABLE_set_row( &tv->view, row, rec, mask );
2793 else
2795 TRACE("deleting row [%d]:\n", row);
2796 TABLE_delete_row( &tv->view, row );
2799 if( TRACE_ON(msidb) ) dump_record( rec );
2800 msiobj_release( &rec->hdr );
2803 n += sz;
2806 err:
2807 /* no need to free the table, it's associated with the database */
2808 msi_free( rawdata );
2809 if( tv )
2810 tv->view.ops->delete( &tv->view );
2812 return ERROR_SUCCESS;
2816 * msi_table_apply_transform
2818 * Enumerate the table transforms in a transform storage and apply each one.
2820 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2822 struct list transforms;
2823 IEnumSTATSTG *stgenum = NULL;
2824 TRANSFORMDATA *transform;
2825 TRANSFORMDATA *tables = NULL, *columns = NULL;
2826 HRESULT r;
2827 STATSTG stat;
2828 string_table *strings;
2829 UINT ret = ERROR_FUNCTION_FAILED;
2830 UINT bytes_per_strref;
2832 TRACE("%p %p\n", db, stg );
2834 strings = msi_load_string_table( stg, &bytes_per_strref );
2835 if( !strings )
2836 goto end;
2838 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2839 if( FAILED( r ) )
2840 goto end;
2842 list_init(&transforms);
2844 while ( TRUE )
2846 MSITABLEVIEW *tv = NULL;
2847 WCHAR name[0x40];
2848 ULONG count = 0;
2850 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2851 if ( FAILED( r ) || !count )
2852 break;
2854 decode_streamname( stat.pwcsName, name );
2855 CoTaskMemFree( stat.pwcsName );
2856 if ( name[0] != 0x4840 )
2857 continue;
2859 if ( !lstrcmpW( name+1, szStringPool ) ||
2860 !lstrcmpW( name+1, szStringData ) )
2861 continue;
2863 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2864 if ( !transform )
2865 break;
2867 list_add_tail( &transforms, &transform->entry );
2869 transform->name = strdupW( name + 1 );
2871 if ( !lstrcmpW( transform->name, szTables ) )
2872 tables = transform;
2873 else if (!lstrcmpW( transform->name, szColumns ) )
2874 columns = transform;
2876 TRACE("transform contains stream %s\n", debugstr_w(name));
2878 /* load the table */
2879 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2880 if( r != ERROR_SUCCESS )
2881 continue;
2883 r = tv->view.ops->execute( &tv->view, NULL );
2884 if( r != ERROR_SUCCESS )
2886 tv->view.ops->delete( &tv->view );
2887 continue;
2890 tv->view.ops->delete( &tv->view );
2894 * Apply _Tables and _Columns transforms first so that
2895 * the table metadata is correct, and empty tables exist.
2897 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2898 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2899 goto end;
2901 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2902 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2903 goto end;
2905 ret = ERROR_SUCCESS;
2907 while ( !list_empty( &transforms ) )
2909 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2911 if ( lstrcmpW( transform->name, szColumns ) &&
2912 lstrcmpW( transform->name, szTables ) &&
2913 ret == ERROR_SUCCESS )
2915 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2918 list_remove( &transform->entry );
2919 msi_free( transform->name );
2920 msi_free( transform );
2923 if ( ret == ERROR_SUCCESS )
2924 append_storage_to_db( db, stg );
2926 end:
2927 if ( stgenum )
2928 IEnumSTATSTG_Release( stgenum );
2929 if ( strings )
2930 msi_destroy_stringtable( strings );
2932 return ret;