winhttp/tests: Initialize a variant with a known value.
[wine/multimedia.git] / dlls / msi / table.c
blob0ea07279795e846f03480cee878513480ccf5f15
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
46 typedef struct tagMSICOLUMNHASHENTRY
48 struct tagMSICOLUMNHASHENTRY *next;
49 UINT value;
50 UINT row;
51 } MSICOLUMNHASHENTRY;
53 typedef struct tagMSICOLUMNINFO
55 LPCWSTR tablename;
56 UINT number;
57 LPCWSTR colname;
58 UINT type;
59 UINT offset;
60 INT ref_count;
61 BOOL temporary;
62 MSICOLUMNHASHENTRY **hash_table;
63 } MSICOLUMNINFO;
65 typedef struct tagMSIORDERINFO
67 UINT *reorder;
68 UINT num_cols;
69 UINT cols[1];
70 } MSIORDERINFO;
72 struct tagMSITABLE
74 BYTE **data;
75 BOOL *data_persistent;
76 UINT row_count;
77 struct list entry;
78 MSICOLUMNINFO *colinfo;
79 UINT col_count;
80 MSICONDITION persistent;
81 INT ref_count;
82 WCHAR name[1];
85 /* information for default tables */
86 static const WCHAR szTables[] = {'_','T','a','b','l','e','s',0};
87 static const WCHAR szTable[] = {'T','a','b','l','e',0};
88 static const WCHAR szColumns[] = {'_','C','o','l','u','m','n','s',0};
89 static const WCHAR szNumber[] = {'N','u','m','b','e','r',0};
90 static const WCHAR szType[] = {'T','y','p','e',0};
92 static const MSICOLUMNINFO _Columns_cols[4] = {
93 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
94 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
95 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
96 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
99 static const MSICOLUMNINFO _Tables_cols[1] = {
100 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
103 #define MAX_STREAM_NAME 0x1f
105 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
107 if( MSITYPE_IS_BINARY(col->type) )
108 return 2;
110 if( col->type & MSITYPE_STRING )
111 return bytes_per_strref;
113 if( (col->type & 0xff) <= 2)
114 return 2;
116 if( (col->type & 0xff) != 4 )
117 ERR("Invalid column size!\n");
119 return 4;
122 static int utf2mime(int x)
124 if( (x>='0') && (x<='9') )
125 return x-'0';
126 if( (x>='A') && (x<='Z') )
127 return x-'A'+10;
128 if( (x>='a') && (x<='z') )
129 return x-'a'+10+26;
130 if( x=='.' )
131 return 10+26+26;
132 if( x=='_' )
133 return 10+26+26+1;
134 return -1;
137 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
139 DWORD count = MAX_STREAM_NAME;
140 DWORD ch, next;
141 LPWSTR out, p;
143 if( !bTable )
144 count = lstrlenW( in )+2;
145 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
146 p = out;
148 if( bTable )
150 *p++ = 0x4840;
151 count --;
153 while( count -- )
155 ch = *in++;
156 if( !ch )
158 *p = ch;
159 return out;
161 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
163 ch = utf2mime(ch) + 0x4800;
164 next = *in;
165 if( next && (next<0x80) )
167 next = utf2mime(next);
168 if( next != -1 )
170 next += 0x3ffffc0;
171 ch += (next<<6);
172 in++;
176 *p++ = ch;
178 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
179 msi_free( out );
180 return NULL;
183 static int mime2utf(int x)
185 if( x<10 )
186 return x + '0';
187 if( x<(10+26))
188 return x - 10 + 'A';
189 if( x<(10+26+26))
190 return x - 10 - 26 + 'a';
191 if( x == (10+26+26) )
192 return '.';
193 return '_';
196 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
198 WCHAR ch;
199 DWORD count = 0;
201 while ( (ch = *in++) )
203 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
205 if( ch >= 0x4800 )
206 ch = mime2utf(ch-0x4800);
207 else
209 ch -= 0x3800;
210 *out++ = mime2utf(ch&0x3f);
211 count++;
212 ch = mime2utf((ch>>6)&0x3f);
215 *out++ = ch;
216 count++;
218 *out = 0;
219 return count;
222 void enum_stream_names( IStorage *stg )
224 IEnumSTATSTG *stgenum = NULL;
225 HRESULT r;
226 STATSTG stat;
227 ULONG n, count;
228 WCHAR name[0x40];
230 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
231 if( FAILED( r ) )
232 return;
234 n = 0;
235 while( 1 )
237 count = 0;
238 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
239 if( FAILED( r ) || !count )
240 break;
241 decode_streamname( stat.pwcsName, name );
242 TRACE("stream %2d -> %s %s\n", n,
243 debugstr_w(stat.pwcsName), debugstr_w(name) );
244 CoTaskMemFree( stat.pwcsName );
245 n++;
248 IEnumSTATSTG_Release( stgenum );
251 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
252 BYTE **pdata, UINT *psz )
254 HRESULT r;
255 UINT ret = ERROR_FUNCTION_FAILED;
256 VOID *data;
257 ULONG sz, count;
258 IStream *stm = NULL;
259 STATSTG stat;
260 LPWSTR encname;
262 encname = encode_streamname(table, stname);
264 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
266 r = IStorage_OpenStream(stg, encname, NULL,
267 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
268 msi_free( encname );
269 if( FAILED( r ) )
271 WARN("open stream failed r = %08x - empty table?\n", r);
272 return ret;
275 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
276 if( FAILED( r ) )
278 WARN("open stream failed r = %08x!\n", r);
279 goto end;
282 if( stat.cbSize.QuadPart >> 32 )
284 WARN("Too big!\n");
285 goto end;
288 sz = stat.cbSize.QuadPart;
289 data = msi_alloc( sz );
290 if( !data )
292 WARN("couldn't allocate memory r=%08x!\n", r);
293 ret = ERROR_NOT_ENOUGH_MEMORY;
294 goto end;
297 r = IStream_Read(stm, data, sz, &count );
298 if( FAILED( r ) || ( count != sz ) )
300 msi_free( data );
301 WARN("read stream failed r = %08x!\n", r);
302 goto end;
305 *pdata = data;
306 *psz = sz;
307 ret = ERROR_SUCCESS;
309 end:
310 IStream_Release( stm );
312 return ret;
315 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
316 LPCVOID data, UINT sz, BOOL bTable )
318 HRESULT r;
319 UINT ret = ERROR_FUNCTION_FAILED;
320 ULONG count;
321 IStream *stm = NULL;
322 ULARGE_INTEGER size;
323 LARGE_INTEGER pos;
324 LPWSTR encname;
326 encname = encode_streamname(bTable, stname );
327 r = IStorage_OpenStream( stg, encname, NULL,
328 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
329 if( FAILED(r) )
331 r = IStorage_CreateStream( stg, encname,
332 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
334 msi_free( encname );
335 if( FAILED( r ) )
337 WARN("open stream failed r = %08x\n", r);
338 return ret;
341 size.QuadPart = sz;
342 r = IStream_SetSize( stm, size );
343 if( FAILED( r ) )
345 WARN("Failed to SetSize\n");
346 goto end;
349 pos.QuadPart = 0;
350 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
351 if( FAILED( r ) )
353 WARN("Failed to Seek\n");
354 goto end;
357 if (sz)
359 r = IStream_Write(stm, data, sz, &count );
360 if( FAILED( r ) || ( count != sz ) )
362 WARN("Failed to Write\n");
363 goto end;
367 ret = ERROR_SUCCESS;
369 end:
370 IStream_Release( stm );
372 return ret;
375 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
377 UINT i;
378 for (i = 0; i < count; i++) msi_free( colinfo[i].hash_table );
381 static void free_table( MSITABLE *table )
383 UINT i;
384 for( i=0; i<table->row_count; i++ )
385 msi_free( table->data[i] );
386 msi_free( table->data );
387 msi_free( table->data_persistent );
388 msi_free_colinfo( table->colinfo, table->col_count );
389 msi_free( table->colinfo );
390 msi_free( table );
393 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
395 const MSICOLUMNINFO *last_col;
397 if (!count)
398 return 0;
400 if (bytes_per_strref != LONG_STR_BYTES)
402 UINT i, size = 0;
403 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
404 return size;
406 last_col = &cols[count - 1];
407 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
410 /* add this table to the list of cached tables in the database */
411 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
413 BYTE *rawdata = NULL;
414 UINT rawsize = 0, i, j, row_size, row_size_mem;
416 TRACE("%s\n",debugstr_w(t->name));
418 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
419 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
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 UINT ofs = 0, ofs_mem = 0;
448 t->data[i] = msi_alloc( row_size_mem );
449 if( !t->data[i] )
450 goto err;
451 t->data_persistent[i] = TRUE;
453 for (j = 0; j < t->col_count; j++)
455 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
456 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
457 UINT k;
459 if ( n != 2 && n != 3 && n != 4 )
461 ERR("oops - unknown column width %d\n", n);
462 goto err;
464 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
466 for (k = 0; k < m; k++)
468 if (k < n)
469 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
470 else
471 t->data[i][ofs_mem + k] = 0;
474 else
476 for (k = 0; k < n; k++)
477 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
479 ofs_mem += m;
480 ofs += n;
484 msi_free( rawdata );
485 return ERROR_SUCCESS;
486 err:
487 msi_free( rawdata );
488 return ERROR_FUNCTION_FAILED;
491 void free_cached_tables( MSIDATABASE *db )
493 while( !list_empty( &db->tables ) )
495 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
497 list_remove( &t->entry );
498 free_table( t );
502 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
504 MSITABLE *t;
506 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
507 if( !strcmpW( name, t->name ) )
508 return t;
510 return NULL;
513 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
515 DWORD i;
517 for (i = 0; colinfo && i < count; i++)
519 assert( i + 1 == colinfo[i].number );
520 if (i) colinfo[i].offset = colinfo[i - 1].offset +
521 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
522 else colinfo[i].offset = 0;
524 TRACE("column %d is [%s] with type %08x ofs %d\n",
525 colinfo[i].number, debugstr_w(colinfo[i].colname),
526 colinfo[i].type, colinfo[i].offset);
530 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
532 const MSICOLUMNINFO *p;
533 DWORD i, n;
535 TRACE("%s\n", debugstr_w(name));
537 if (!strcmpW( name, szTables ))
539 p = _Tables_cols;
540 n = 1;
542 else if (!strcmpW( name, szColumns ))
544 p = _Columns_cols;
545 n = 4;
547 else return ERROR_FUNCTION_FAILED;
549 for (i = 0; i < n; i++)
551 if (colinfo && i < *sz) colinfo[i] = p[i];
552 if (colinfo && i >= *sz) break;
554 table_calc_column_offsets( db, colinfo, n );
555 *sz = n;
556 return ERROR_SUCCESS;
559 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
561 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
563 UINT r, column_count = 0;
564 MSICOLUMNINFO *columns;
566 /* get the number of columns in this table */
567 column_count = 0;
568 r = get_tablecolumns( db, name, NULL, &column_count );
569 if (r != ERROR_SUCCESS)
570 return r;
572 *pcount = column_count;
574 /* if there's no columns, there's no table */
575 if (!column_count)
576 return ERROR_INVALID_PARAMETER;
578 TRACE("table %s found\n", debugstr_w(name));
580 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
581 if (!columns)
582 return ERROR_FUNCTION_FAILED;
584 r = get_tablecolumns( db, name, columns, &column_count );
585 if (r != ERROR_SUCCESS)
587 msi_free( columns );
588 return ERROR_FUNCTION_FAILED;
590 *pcols = columns;
591 return r;
594 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
596 MSITABLE *table;
597 UINT r;
599 /* first, see if the table is cached */
600 table = find_cached_table( db, name );
601 if (table)
603 *table_ret = table;
604 return ERROR_SUCCESS;
607 /* nonexistent tables should be interpreted as empty tables */
608 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
609 if (!table)
610 return ERROR_FUNCTION_FAILED;
612 table->row_count = 0;
613 table->data = NULL;
614 table->data_persistent = NULL;
615 table->colinfo = NULL;
616 table->col_count = 0;
617 table->persistent = MSICONDITION_TRUE;
618 lstrcpyW( table->name, name );
620 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
621 table->persistent = MSICONDITION_NONE;
623 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
624 if (r != ERROR_SUCCESS)
626 free_table( table );
627 return r;
629 r = read_table_from_storage( db, table, db->storage );
630 if (r != ERROR_SUCCESS)
632 free_table( table );
633 return r;
635 list_add_head( &db->tables, &table->entry );
636 *table_ret = table;
637 return ERROR_SUCCESS;
640 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
642 UINT ret = 0, i;
644 for (i = 0; i < bytes; i++)
645 ret += data[row][col + i] << i * 8;
647 return ret;
650 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
652 UINT r, i, n = 0, table_id, count, maxcount = *sz;
653 MSITABLE *table = NULL;
655 TRACE("%s\n", debugstr_w(szTableName));
657 /* first check if there is a default table with that name */
658 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
659 if (r == ERROR_SUCCESS && *sz)
660 return r;
662 r = get_table( db, szColumns, &table );
663 if (r != ERROR_SUCCESS)
665 ERR("couldn't load _Columns table\n");
666 return ERROR_FUNCTION_FAILED;
669 /* convert table and column names to IDs from the string table */
670 r = msi_string2idW( db->strings, szTableName, &table_id );
671 if (r != ERROR_SUCCESS)
673 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
674 return r;
676 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
678 /* Note: _Columns table doesn't have non-persistent data */
680 /* if maxcount is non-zero, assume it's exactly right for this table */
681 memset( colinfo, 0, maxcount * sizeof(*colinfo) );
682 count = table->row_count;
683 for (i = 0; i < count; i++)
685 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
686 if (colinfo)
688 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
689 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
691 /* check the column number is in range */
692 if (col < 1 || col > maxcount)
694 ERR("column %d out of range\n", col);
695 continue;
697 /* check if this column was already set */
698 if (colinfo[col - 1].number)
700 ERR("duplicate column %d\n", col);
701 continue;
703 colinfo[col - 1].tablename = msi_string_lookup_id( db->strings, table_id );
704 colinfo[col - 1].number = col;
705 colinfo[col - 1].colname = msi_string_lookup_id( db->strings, id );
706 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
707 sizeof(USHORT) ) - (1 << 15);
708 colinfo[col - 1].offset = 0;
709 colinfo[col - 1].ref_count = 0;
710 colinfo[col - 1].hash_table = NULL;
712 n++;
714 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
716 if (colinfo && n != maxcount)
718 ERR("missing column in table %s\n", debugstr_w(szTableName));
719 msi_free_colinfo( colinfo, maxcount );
720 return ERROR_FUNCTION_FAILED;
722 table_calc_column_offsets( db, colinfo, n );
723 *sz = n;
724 return ERROR_SUCCESS;
727 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
728 MSICONDITION persistent, MSITABLE **table_ret)
730 enum StringPersistence string_persistence = (persistent) ? StringPersistent : StringNonPersistent;
731 UINT r, nField;
732 MSIVIEW *tv = NULL;
733 MSIRECORD *rec = NULL;
734 column_info *col;
735 MSITABLE *table;
736 UINT i;
738 /* only add tables that don't exist already */
739 if( TABLE_Exists(db, name ) )
741 WARN("table %s exists\n", debugstr_w(name));
742 return ERROR_BAD_QUERY_SYNTAX;
745 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
746 if( !table )
747 return ERROR_FUNCTION_FAILED;
749 table->ref_count = 1;
750 table->row_count = 0;
751 table->data = NULL;
752 table->data_persistent = NULL;
753 table->colinfo = NULL;
754 table->col_count = 0;
755 table->persistent = persistent;
756 lstrcpyW( table->name, name );
758 for( col = col_info; col; col = col->next )
759 table->col_count++;
761 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
762 if (!table->colinfo)
764 free_table( table );
765 return ERROR_FUNCTION_FAILED;
768 for( i = 0, col = col_info; col; i++, col = col->next )
770 UINT table_id = msi_addstringW( db->strings, col->table, -1, 1, string_persistence );
771 UINT col_id = msi_addstringW( db->strings, col->column, -1, 1, string_persistence );
773 table->colinfo[ i ].tablename = msi_string_lookup_id( db->strings, table_id );
774 table->colinfo[ i ].number = i + 1;
775 table->colinfo[ i ].colname = msi_string_lookup_id( db->strings, col_id );
776 table->colinfo[ i ].type = col->type;
777 table->colinfo[ i ].offset = 0;
778 table->colinfo[ i ].ref_count = 0;
779 table->colinfo[ i ].hash_table = NULL;
780 table->colinfo[ i ].temporary = col->temporary;
782 table_calc_column_offsets( db, table->colinfo, table->col_count);
784 r = TABLE_CreateView( db, szTables, &tv );
785 TRACE("CreateView returned %x\n", r);
786 if( r )
788 free_table( table );
789 return r;
792 r = tv->ops->execute( tv, 0 );
793 TRACE("tv execute returned %x\n", r);
794 if( r )
795 goto err;
797 rec = MSI_CreateRecord( 1 );
798 if( !rec )
799 goto err;
801 r = MSI_RecordSetStringW( rec, 1, name );
802 if( r )
803 goto err;
805 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
806 TRACE("insert_row returned %x\n", r);
807 if( r )
808 goto err;
810 tv->ops->delete( tv );
811 tv = NULL;
813 msiobj_release( &rec->hdr );
814 rec = NULL;
816 if( persistent != MSICONDITION_FALSE )
818 /* add each column to the _Columns table */
819 r = TABLE_CreateView( db, szColumns, &tv );
820 if( r )
821 return r;
823 r = tv->ops->execute( tv, 0 );
824 TRACE("tv execute returned %x\n", r);
825 if( r )
826 goto err;
828 rec = MSI_CreateRecord( 4 );
829 if( !rec )
830 goto err;
832 r = MSI_RecordSetStringW( rec, 1, name );
833 if( r )
834 goto err;
837 * need to set the table, column number, col name and type
838 * for each column we enter in the table
840 nField = 1;
841 for( col = col_info; col; col = col->next )
843 r = MSI_RecordSetInteger( rec, 2, nField );
844 if( r )
845 goto err;
847 r = MSI_RecordSetStringW( rec, 3, col->column );
848 if( r )
849 goto err;
851 r = MSI_RecordSetInteger( rec, 4, col->type );
852 if( r )
853 goto err;
855 r = tv->ops->insert_row( tv, rec, -1, FALSE );
856 if( r )
857 goto err;
859 nField++;
861 if( !col )
862 r = ERROR_SUCCESS;
865 err:
866 if (rec)
867 msiobj_release( &rec->hdr );
868 /* FIXME: remove values from the string table on error */
869 if( tv )
870 tv->ops->delete( tv );
872 if (r == ERROR_SUCCESS)
874 list_add_head( &db->tables, &table->entry );
875 *table_ret = table;
877 else
878 free_table( table );
880 return r;
883 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
885 BYTE *rawdata = NULL;
886 UINT rawsize, i, j, row_size, row_count;
887 UINT r = ERROR_FUNCTION_FAILED;
889 /* Nothing to do for non-persistent tables */
890 if( t->persistent == MSICONDITION_FALSE )
891 return ERROR_SUCCESS;
893 TRACE("Saving %s\n", debugstr_w( t->name ) );
895 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
896 row_count = t->row_count;
897 for (i = 0; i < t->row_count; i++)
899 if (!t->data_persistent[i])
901 row_count = 1; /* yes, this is bizarre */
902 break;
905 rawsize = row_count * row_size;
906 rawdata = msi_alloc_zero( rawsize );
907 if( !rawdata )
909 r = ERROR_NOT_ENOUGH_MEMORY;
910 goto err;
913 rawsize = 0;
914 for (i = 0; i < t->row_count; i++)
916 UINT ofs = 0, ofs_mem = 0;
918 if (!t->data_persistent[i]) break;
920 for (j = 0; j < t->col_count; j++)
922 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
923 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
924 UINT k;
926 if (n != 2 && n != 3 && n != 4)
928 ERR("oops - unknown column width %d\n", n);
929 goto err;
931 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
933 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
934 if (id > 1 << bytes_per_strref * 8)
936 ERR("string id %u out of range\n", id);
937 goto err;
940 for (k = 0; k < n; k++)
942 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
944 ofs_mem += m;
945 ofs += n;
947 rawsize += row_size;
950 TRACE("writing %d bytes\n", rawsize);
951 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
953 err:
954 msi_free( rawdata );
955 return r;
958 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
960 MSITABLE *table;
961 UINT size, offset, old_count;
962 UINT n;
964 table = find_cached_table( db, name );
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, name, &table->colinfo, &table->col_count );
971 if (!table->col_count) return;
973 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
974 offset = table->colinfo[table->col_count - 1].offset;
976 for ( n = 0; n < table->row_count; n++ )
978 table->data[n] = msi_realloc( table->data[n], size );
979 if (old_count < table->col_count)
980 memset( &table->data[n][offset], 0, size - offset );
984 /* try to find the table name in the _Tables table */
985 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
987 UINT r, table_id, i;
988 MSITABLE *table;
990 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
991 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
992 return TRUE;
994 r = msi_string2idW( db->strings, name, &table_id );
995 if( r != ERROR_SUCCESS )
997 TRACE("Couldn't find id for %s\n", debugstr_w(name));
998 return FALSE;
1001 r = get_table( db, szTables, &table );
1002 if( r != ERROR_SUCCESS )
1004 ERR("table %s not available\n", debugstr_w(szTables));
1005 return FALSE;
1008 for( i = 0; i < table->row_count; i++ )
1010 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
1011 return TRUE;
1014 return FALSE;
1017 /* below is the query interface to a table */
1019 typedef struct tagMSITABLEVIEW
1021 MSIVIEW view;
1022 MSIDATABASE *db;
1023 MSITABLE *table;
1024 MSICOLUMNINFO *columns;
1025 MSIORDERINFO *order;
1026 UINT num_cols;
1027 UINT row_size;
1028 WCHAR name[1];
1029 } MSITABLEVIEW;
1031 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1033 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1034 UINT offset, n;
1036 if( !tv->table )
1037 return ERROR_INVALID_PARAMETER;
1039 if( (col==0) || (col>tv->num_cols) )
1040 return ERROR_INVALID_PARAMETER;
1042 /* how many rows are there ? */
1043 if( row >= tv->table->row_count )
1044 return ERROR_NO_MORE_ITEMS;
1046 if( tv->columns[col-1].offset >= tv->row_size )
1048 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1049 ERR("%p %p\n", tv, tv->columns );
1050 return ERROR_FUNCTION_FAILED;
1053 if (tv->order)
1054 row = tv->order->reorder[row];
1056 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1057 if (n != 2 && n != 3 && n != 4)
1059 ERR("oops! what is %d bytes per column?\n", n );
1060 return ERROR_FUNCTION_FAILED;
1063 offset = tv->columns[col-1].offset;
1064 *val = read_table_int(tv->table->data, row, offset, n);
1066 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1068 return ERROR_SUCCESS;
1071 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1073 LPWSTR p, stname = NULL;
1074 UINT i, r, type, ival;
1075 DWORD len;
1076 LPCWSTR sval;
1077 MSIVIEW *view = (MSIVIEW *) tv;
1079 TRACE("%p %d\n", tv, row);
1081 len = lstrlenW( tv->name ) + 1;
1082 stname = msi_alloc( len*sizeof(WCHAR) );
1083 if ( !stname )
1085 r = ERROR_OUTOFMEMORY;
1086 goto err;
1089 lstrcpyW( stname, tv->name );
1091 for ( i = 0; i < tv->num_cols; i++ )
1093 type = tv->columns[i].type;
1094 if ( type & MSITYPE_KEY )
1096 WCHAR number[0x20];
1098 r = TABLE_fetch_int( view, row, i+1, &ival );
1099 if ( r != ERROR_SUCCESS )
1100 goto err;
1102 if ( tv->columns[i].type & MSITYPE_STRING )
1104 sval = msi_string_lookup_id( tv->db->strings, ival );
1105 if ( !sval )
1107 r = ERROR_INVALID_PARAMETER;
1108 goto err;
1111 else
1113 static const WCHAR fmt[] = { '%','d',0 };
1114 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1116 switch( n )
1118 case 2:
1119 sprintfW( number, fmt, ival-0x8000 );
1120 break;
1121 case 4:
1122 sprintfW( number, fmt, ival^0x80000000 );
1123 break;
1124 default:
1125 ERR( "oops - unknown column width %d\n", n );
1126 r = ERROR_FUNCTION_FAILED;
1127 goto err;
1129 sval = number;
1132 len += lstrlenW( szDot ) + lstrlenW( sval );
1133 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1134 if ( !p )
1136 r = ERROR_OUTOFMEMORY;
1137 goto err;
1139 stname = p;
1141 lstrcatW( stname, szDot );
1142 lstrcatW( stname, sval );
1144 else
1145 continue;
1148 *pstname = stname;
1149 return ERROR_SUCCESS;
1151 err:
1152 msi_free( stname );
1153 *pstname = NULL;
1154 return r;
1158 * We need a special case for streams, as we need to reference column with
1159 * the name of the stream in the same table, and the table name
1160 * which may not be available at higher levels of the query
1162 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1164 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1165 UINT r;
1166 LPWSTR encname, full_name = NULL;
1168 if( !view->ops->fetch_int )
1169 return ERROR_INVALID_PARAMETER;
1171 r = msi_stream_name( tv, row, &full_name );
1172 if ( r != ERROR_SUCCESS )
1174 ERR("fetching stream, error = %d\n", r);
1175 return r;
1178 encname = encode_streamname( FALSE, full_name );
1179 r = msi_get_raw_stream( tv->db, encname, stm );
1180 if( r )
1181 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1183 msi_free( full_name );
1184 msi_free( encname );
1185 return r;
1188 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1190 UINT offset, n, i;
1192 if( !tv->table )
1193 return ERROR_INVALID_PARAMETER;
1195 if( (col==0) || (col>tv->num_cols) )
1196 return ERROR_INVALID_PARAMETER;
1198 if( row >= tv->table->row_count )
1199 return ERROR_INVALID_PARAMETER;
1201 if( tv->columns[col-1].offset >= tv->row_size )
1203 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1204 ERR("%p %p\n", tv, tv->columns );
1205 return ERROR_FUNCTION_FAILED;
1208 msi_free( tv->columns[col-1].hash_table );
1209 tv->columns[col-1].hash_table = NULL;
1211 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1212 if ( n != 2 && n != 3 && n != 4 )
1214 ERR("oops! what is %d bytes per column?\n", n );
1215 return ERROR_FUNCTION_FAILED;
1218 offset = tv->columns[col-1].offset;
1219 for ( i = 0; i < n; i++ )
1220 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1222 return ERROR_SUCCESS;
1225 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1227 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1229 if (!tv->table)
1230 return ERROR_INVALID_PARAMETER;
1232 if (tv->order)
1233 row = tv->order->reorder[row];
1235 return msi_view_get_row(tv->db, view, row, rec);
1238 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1240 static const WCHAR insert[] = {
1241 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1242 '`','_','S','t','r','e','a','m','s','`',' ',
1243 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1244 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1245 MSIQUERY *query = NULL;
1246 MSIRECORD *rec;
1247 UINT r;
1249 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1251 rec = MSI_CreateRecord( 2 );
1252 if ( !rec )
1253 return ERROR_OUTOFMEMORY;
1255 r = MSI_RecordSetStringW( rec, 1, name );
1256 if ( r != ERROR_SUCCESS )
1257 goto err;
1259 r = MSI_RecordSetIStream( rec, 2, data );
1260 if ( r != ERROR_SUCCESS )
1261 goto err;
1263 r = MSI_DatabaseOpenViewW( db, insert, &query );
1264 if ( r != ERROR_SUCCESS )
1265 goto err;
1267 r = MSI_ViewExecute( query, rec );
1269 err:
1270 msiobj_release( &query->hdr );
1271 msiobj_release( &rec->hdr );
1272 return r;
1275 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1277 MSICOLUMNINFO columninfo;
1278 UINT r;
1280 if ( (iField <= 0) ||
1281 (iField > tv->num_cols) ||
1282 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 LPCWSTR sval = MSI_RecordGetString( rec, iField );
1294 if (sval)
1296 r = msi_string2idW(tv->db->strings, sval, pvalue);
1297 if (r != ERROR_SUCCESS)
1298 return ERROR_NOT_FOUND;
1300 else *pvalue = 0;
1302 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1304 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1305 if ( *pvalue & 0xffff0000 )
1307 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1308 return ERROR_FUNCTION_FAILED;
1311 else
1313 INT ival = MSI_RecordGetInteger( rec, iField );
1314 *pvalue = ival ^ 0x80000000;
1317 return ERROR_SUCCESS;
1320 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1322 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1323 UINT i, val, r = ERROR_SUCCESS;
1325 if ( !tv->table )
1326 return ERROR_INVALID_PARAMETER;
1328 /* test if any of the mask bits are invalid */
1329 if ( mask >= (1<<tv->num_cols) )
1330 return ERROR_INVALID_PARAMETER;
1332 for ( i = 0; i < tv->num_cols; i++ )
1334 BOOL persistent;
1336 /* only update the fields specified in the mask */
1337 if ( !(mask&(1<<i)) )
1338 continue;
1340 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1341 (tv->table->data_persistent[row]);
1342 /* FIXME: should we allow updating keys? */
1344 val = 0;
1345 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1347 r = get_table_value_from_record (tv, rec, i + 1, &val);
1348 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1350 IStream *stm;
1351 LPWSTR stname;
1353 if ( r != ERROR_SUCCESS )
1354 return ERROR_FUNCTION_FAILED;
1356 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1357 if ( r != ERROR_SUCCESS )
1358 return r;
1360 r = msi_stream_name( tv, row, &stname );
1361 if ( r != ERROR_SUCCESS )
1363 IStream_Release( stm );
1364 return r;
1367 r = msi_addstreamW( tv->db, stname, stm );
1368 IStream_Release( stm );
1369 msi_free ( stname );
1371 if ( r != ERROR_SUCCESS )
1372 return r;
1374 else if ( tv->columns[i].type & MSITYPE_STRING )
1376 UINT x;
1378 if ( r != ERROR_SUCCESS )
1380 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1381 val = msi_addstringW( tv->db->strings, sval, -1, 1,
1382 persistent ? StringPersistent : StringNonPersistent );
1384 else
1386 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1387 if (val == x)
1388 continue;
1391 else
1393 if ( r != ERROR_SUCCESS )
1394 return ERROR_FUNCTION_FAILED;
1398 r = TABLE_set_int( tv, row, i+1, val );
1399 if ( r != ERROR_SUCCESS )
1400 break;
1402 return r;
1405 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1407 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1408 BYTE **p, *row;
1409 BOOL *b;
1410 UINT sz;
1411 BYTE ***data_ptr;
1412 BOOL **data_persist_ptr;
1413 UINT *row_count;
1415 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1417 if( !tv->table )
1418 return ERROR_INVALID_PARAMETER;
1420 row = msi_alloc_zero( tv->row_size );
1421 if( !row )
1422 return ERROR_NOT_ENOUGH_MEMORY;
1424 row_count = &tv->table->row_count;
1425 data_ptr = &tv->table->data;
1426 data_persist_ptr = &tv->table->data_persistent;
1427 if (*num == -1)
1428 *num = tv->table->row_count;
1430 sz = (*row_count + 1) * sizeof (BYTE*);
1431 if( *data_ptr )
1432 p = msi_realloc( *data_ptr, sz );
1433 else
1434 p = msi_alloc( sz );
1435 if( !p )
1437 msi_free( row );
1438 return ERROR_NOT_ENOUGH_MEMORY;
1441 sz = (*row_count + 1) * sizeof (BOOL);
1442 if( *data_persist_ptr )
1443 b = msi_realloc( *data_persist_ptr, sz );
1444 else
1445 b = msi_alloc( sz );
1446 if( !b )
1448 msi_free( row );
1449 msi_free( p );
1450 return ERROR_NOT_ENOUGH_MEMORY;
1453 *data_ptr = p;
1454 (*data_ptr)[*row_count] = row;
1456 *data_persist_ptr = b;
1457 (*data_persist_ptr)[*row_count] = !temporary;
1459 (*row_count)++;
1461 return ERROR_SUCCESS;
1464 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1466 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1468 TRACE("%p %p\n", tv, record);
1470 TRACE("There are %d columns\n", tv->num_cols );
1472 return ERROR_SUCCESS;
1475 static UINT TABLE_close( struct tagMSIVIEW *view )
1477 TRACE("%p\n", view );
1479 return ERROR_SUCCESS;
1482 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1484 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1486 TRACE("%p %p %p\n", view, rows, cols );
1488 if( cols )
1489 *cols = tv->num_cols;
1490 if( rows )
1492 if( !tv->table )
1493 return ERROR_INVALID_PARAMETER;
1494 *rows = tv->table->row_count;
1497 return ERROR_SUCCESS;
1500 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1501 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1502 LPCWSTR *table_name )
1504 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1506 TRACE("%p %d %p %p\n", tv, n, name, type );
1508 if( ( n == 0 ) || ( n > tv->num_cols ) )
1509 return ERROR_INVALID_PARAMETER;
1511 if( name )
1513 *name = tv->columns[n-1].colname;
1514 if( !*name )
1515 return ERROR_FUNCTION_FAILED;
1518 if( table_name )
1520 *table_name = tv->columns[n-1].tablename;
1521 if( !*table_name )
1522 return ERROR_FUNCTION_FAILED;
1525 if( type )
1526 *type = tv->columns[n-1].type;
1528 if( temporary )
1529 *temporary = tv->columns[n-1].temporary;
1531 return ERROR_SUCCESS;
1534 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1536 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1538 UINT r, row, i;
1540 /* check there's no null values where they're not allowed */
1541 for( i = 0; i < tv->num_cols; i++ )
1543 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1544 continue;
1546 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1547 TRACE("skipping binary column\n");
1548 else if ( tv->columns[i].type & MSITYPE_STRING )
1550 LPCWSTR str;
1552 str = MSI_RecordGetString( rec, i+1 );
1553 if (str == NULL || str[0] == 0)
1555 if (column) *column = i;
1556 return ERROR_INVALID_DATA;
1559 else
1561 UINT n;
1563 n = MSI_RecordGetInteger( rec, i+1 );
1564 if (n == MSI_NULL_INTEGER)
1566 if (column) *column = i;
1567 return ERROR_INVALID_DATA;
1572 /* check there's no duplicate keys */
1573 r = msi_table_find_row( tv, rec, &row, column );
1574 if (r == ERROR_SUCCESS)
1575 return ERROR_FUNCTION_FAILED;
1577 return ERROR_SUCCESS;
1580 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1582 UINT r, i, ivalue, x;
1584 for (i = 0; i < tv->num_cols; i++ )
1586 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1588 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1589 if (r != ERROR_SUCCESS)
1590 return 1;
1592 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1593 if (r != ERROR_SUCCESS)
1595 WARN("TABLE_fetch_int should not fail here %u\n", r);
1596 return -1;
1598 if (ivalue > x)
1600 return 1;
1602 else if (ivalue == x)
1604 if (i < tv->num_cols - 1) continue;
1605 return 0;
1607 else
1608 return -1;
1610 return 1;
1613 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1615 int idx, c, low = 0, high = tv->table->row_count - 1;
1617 TRACE("%p %p\n", tv, rec);
1619 while (low <= high)
1621 idx = (low + high) / 2;
1622 c = compare_record( tv, idx, rec );
1624 if (c < 0)
1625 high = idx - 1;
1626 else if (c > 0)
1627 low = idx + 1;
1628 else
1630 TRACE("found %u\n", idx);
1631 return idx;
1634 TRACE("found %u\n", high + 1);
1635 return high + 1;
1638 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1640 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1641 UINT i, r;
1643 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1645 /* check that the key is unique - can we find a matching row? */
1646 r = table_validate_new( tv, rec, NULL );
1647 if( r != ERROR_SUCCESS )
1648 return ERROR_FUNCTION_FAILED;
1650 if (row == -1)
1651 row = find_insert_index( tv, rec );
1653 r = table_create_new_row( view, &row, temporary );
1654 TRACE("insert_row returned %08x\n", r);
1655 if( r != ERROR_SUCCESS )
1656 return r;
1658 /* shift the rows to make room for the new row */
1659 for (i = tv->table->row_count - 1; i > row; i--)
1661 memmove(&(tv->table->data[i][0]),
1662 &(tv->table->data[i - 1][0]), tv->row_size);
1663 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1666 /* Re-set the persistence flag */
1667 tv->table->data_persistent[row] = !temporary;
1668 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1671 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1673 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1674 UINT r, num_rows, num_cols, i;
1676 TRACE("%p %d\n", tv, row);
1678 if ( !tv->table )
1679 return ERROR_INVALID_PARAMETER;
1681 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1682 if ( r != ERROR_SUCCESS )
1683 return r;
1685 if ( row >= num_rows )
1686 return ERROR_FUNCTION_FAILED;
1688 num_rows = tv->table->row_count;
1689 tv->table->row_count--;
1691 /* reset the hash tables */
1692 for (i = 0; i < tv->num_cols; i++)
1694 msi_free( tv->columns[i].hash_table );
1695 tv->columns[i].hash_table = NULL;
1698 for (i = row + 1; i < num_rows; i++)
1700 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1701 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1704 msi_free(tv->table->data[num_rows - 1]);
1706 return ERROR_SUCCESS;
1709 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1711 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1712 UINT r, new_row;
1714 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1715 * sets the fetched record apart from other records
1718 if (!tv->table)
1719 return ERROR_INVALID_PARAMETER;
1721 r = msi_table_find_row(tv, rec, &new_row, NULL);
1722 if (r != ERROR_SUCCESS)
1724 ERR("can't find row to modify\n");
1725 return ERROR_FUNCTION_FAILED;
1728 /* the row cannot be changed */
1729 if (row != new_row + 1)
1730 return ERROR_FUNCTION_FAILED;
1732 if(tv->order)
1733 new_row = tv->order->reorder[new_row];
1735 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1738 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1740 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1741 UINT r, row;
1743 if (!tv->table)
1744 return ERROR_INVALID_PARAMETER;
1746 r = msi_table_find_row(tv, rec, &row, NULL);
1747 if (r == ERROR_SUCCESS)
1748 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1749 else
1750 return TABLE_insert_row( view, rec, -1, FALSE );
1753 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1755 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1756 UINT row, r;
1758 r = msi_table_find_row(tv, rec, &row, NULL);
1759 if (r != ERROR_SUCCESS)
1760 return r;
1762 return TABLE_delete_row(view, row);
1765 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1767 MSIRECORD *curr;
1768 UINT r, i, count;
1770 r = TABLE_get_row(view, row - 1, &curr);
1771 if (r != ERROR_SUCCESS)
1772 return r;
1774 /* Close the original record */
1775 MSI_CloseRecord(&rec->hdr);
1777 count = MSI_RecordGetFieldCount(rec);
1778 for (i = 0; i < count; i++)
1779 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1781 msiobj_release(&curr->hdr);
1782 return ERROR_SUCCESS;
1785 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1786 MSIRECORD *rec, UINT row)
1788 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1789 UINT r, column;
1791 TRACE("%p %d %p\n", view, eModifyMode, rec );
1793 switch (eModifyMode)
1795 case MSIMODIFY_DELETE:
1796 r = modify_delete_row( view, rec );
1797 break;
1798 case MSIMODIFY_VALIDATE_NEW:
1799 r = table_validate_new( tv, rec, &column );
1800 if (r != ERROR_SUCCESS)
1802 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1803 tv->view.error_column = tv->columns[column].colname;
1804 r = ERROR_INVALID_DATA;
1806 break;
1808 case MSIMODIFY_INSERT:
1809 r = table_validate_new( tv, rec, NULL );
1810 if (r != ERROR_SUCCESS)
1811 break;
1812 r = TABLE_insert_row( view, rec, -1, FALSE );
1813 break;
1815 case MSIMODIFY_INSERT_TEMPORARY:
1816 r = table_validate_new( tv, rec, NULL );
1817 if (r != ERROR_SUCCESS)
1818 break;
1819 r = TABLE_insert_row( view, rec, -1, TRUE );
1820 break;
1822 case MSIMODIFY_REFRESH:
1823 r = msi_refresh_record( view, rec, row );
1824 break;
1826 case MSIMODIFY_UPDATE:
1827 r = msi_table_update( view, rec, row );
1828 break;
1830 case MSIMODIFY_ASSIGN:
1831 r = msi_table_assign( view, rec );
1832 break;
1834 case MSIMODIFY_REPLACE:
1835 case MSIMODIFY_MERGE:
1836 case MSIMODIFY_VALIDATE:
1837 case MSIMODIFY_VALIDATE_FIELD:
1838 case MSIMODIFY_VALIDATE_DELETE:
1839 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1840 r = ERROR_CALL_NOT_IMPLEMENTED;
1841 break;
1843 default:
1844 r = ERROR_INVALID_DATA;
1847 return r;
1850 static UINT TABLE_delete( struct tagMSIVIEW *view )
1852 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1854 TRACE("%p\n", view );
1856 tv->table = NULL;
1857 tv->columns = NULL;
1859 if (tv->order)
1861 msi_free( tv->order->reorder );
1862 msi_free( tv->order );
1863 tv->order = NULL;
1866 msi_free( tv );
1868 return ERROR_SUCCESS;
1871 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1872 UINT val, UINT *row, MSIITERHANDLE *handle )
1874 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1875 const MSICOLUMNHASHENTRY *entry;
1877 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1879 if( !tv->table )
1880 return ERROR_INVALID_PARAMETER;
1882 if( (col==0) || (col > tv->num_cols) )
1883 return ERROR_INVALID_PARAMETER;
1885 if( !tv->columns[col-1].hash_table )
1887 UINT i;
1888 UINT num_rows = tv->table->row_count;
1889 MSICOLUMNHASHENTRY **hash_table;
1890 MSICOLUMNHASHENTRY *new_entry;
1892 if( tv->columns[col-1].offset >= tv->row_size )
1894 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1895 ERR("%p %p\n", tv, tv->columns );
1896 return ERROR_FUNCTION_FAILED;
1899 /* allocate contiguous memory for the table and its entries so we
1900 * don't have to do an expensive cleanup */
1901 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1902 num_rows * sizeof(MSICOLUMNHASHENTRY));
1903 if (!hash_table)
1904 return ERROR_OUTOFMEMORY;
1906 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1907 tv->columns[col-1].hash_table = hash_table;
1909 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1911 for (i = 0; i < num_rows; i++, new_entry++)
1913 UINT row_value;
1915 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1916 continue;
1918 new_entry->next = NULL;
1919 new_entry->value = row_value;
1920 new_entry->row = i;
1921 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1923 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1924 while (prev_entry->next)
1925 prev_entry = prev_entry->next;
1926 prev_entry->next = new_entry;
1928 else
1929 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1933 if( !*handle )
1934 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1935 else
1936 entry = (*handle)->next;
1938 while (entry && entry->value != val)
1939 entry = entry->next;
1941 *handle = entry;
1942 if (!entry)
1943 return ERROR_NO_MORE_ITEMS;
1945 *row = entry->row;
1947 return ERROR_SUCCESS;
1950 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1952 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1953 UINT i;
1955 TRACE("%p %d\n", view, tv->table->ref_count);
1957 for (i = 0; i < tv->table->col_count; i++)
1959 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1960 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1963 return InterlockedIncrement(&tv->table->ref_count);
1966 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1968 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1969 MSIRECORD *rec = NULL;
1970 MSIVIEW *columns = NULL;
1971 UINT row, r;
1973 rec = MSI_CreateRecord(2);
1974 if (!rec)
1975 return ERROR_OUTOFMEMORY;
1977 MSI_RecordSetStringW(rec, 1, table);
1978 MSI_RecordSetInteger(rec, 2, number);
1980 r = TABLE_CreateView(tv->db, szColumns, &columns);
1981 if (r != ERROR_SUCCESS)
1982 return r;
1984 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1985 if (r != ERROR_SUCCESS)
1986 goto done;
1988 r = TABLE_delete_row(columns, row);
1989 if (r != ERROR_SUCCESS)
1990 goto done;
1992 msi_update_table_columns(tv->db, table);
1994 done:
1995 msiobj_release(&rec->hdr);
1996 columns->ops->delete(columns);
1997 return r;
2000 static UINT TABLE_release(struct tagMSIVIEW *view)
2002 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2003 INT ref = tv->table->ref_count;
2004 UINT i, r;
2006 TRACE("%p %d\n", view, ref);
2008 for (i = 0; i < tv->table->col_count; i++)
2010 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2012 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2013 if (ref == 0)
2015 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2016 tv->table->colinfo[i].number);
2017 if (r != ERROR_SUCCESS)
2018 break;
2023 ref = InterlockedDecrement(&tv->table->ref_count);
2024 if (ref == 0)
2026 if (!tv->table->row_count)
2028 list_remove(&tv->table->entry);
2029 free_table(tv->table);
2030 TABLE_delete(view);
2034 return ref;
2037 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2038 LPCWSTR column, UINT type, BOOL hold)
2040 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2041 MSITABLE *msitable;
2042 MSIRECORD *rec;
2043 UINT r, i;
2045 rec = MSI_CreateRecord(4);
2046 if (!rec)
2047 return ERROR_OUTOFMEMORY;
2049 MSI_RecordSetStringW(rec, 1, table);
2050 MSI_RecordSetInteger(rec, 2, number);
2051 MSI_RecordSetStringW(rec, 3, column);
2052 MSI_RecordSetInteger(rec, 4, type);
2054 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2055 if (r != ERROR_SUCCESS)
2056 goto done;
2058 msi_update_table_columns(tv->db, table);
2060 if (!hold)
2061 goto done;
2063 msitable = find_cached_table(tv->db, table);
2064 for (i = 0; i < msitable->col_count; i++)
2066 if (!strcmpW( msitable->colinfo[i].colname, column ))
2068 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2069 break;
2073 done:
2074 msiobj_release(&rec->hdr);
2075 return r;
2078 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2080 UINT n, r, count;
2081 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2083 r = TABLE_get_dimensions(view, NULL, &count);
2084 if (r != ERROR_SUCCESS)
2085 return r;
2087 if (order->num_cols >= count)
2088 return ERROR_FUNCTION_FAILED;
2090 r = VIEW_find_column(view, name, tv->name, &n);
2091 if (r != ERROR_SUCCESS)
2092 return r;
2094 order->cols[order->num_cols] = n;
2095 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2097 order->num_cols++;
2099 return ERROR_SUCCESS;
2102 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2103 UINT a, UINT b, UINT *swap)
2105 UINT r, i, a_val = 0, b_val = 0;
2107 *swap = 0;
2108 for (i = 0; i < order->num_cols; i++)
2110 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2111 if (r != ERROR_SUCCESS)
2112 return r;
2114 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2115 if (r != ERROR_SUCCESS)
2116 return r;
2118 if (a_val != b_val)
2120 if (a_val > b_val)
2121 *swap = 1;
2122 break;
2126 return ERROR_SUCCESS;
2129 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2130 UINT left, UINT right)
2132 UINT r, i, j, temp;
2133 UINT swap = 0, center = (left + right) / 2;
2134 UINT *array = order->reorder;
2136 if (left == right)
2137 return ERROR_SUCCESS;
2139 /* sort the left half */
2140 r = order_mergesort(view, order, left, center);
2141 if (r != ERROR_SUCCESS)
2142 return r;
2144 /* sort the right half */
2145 r = order_mergesort(view, order, center + 1, right);
2146 if (r != ERROR_SUCCESS)
2147 return r;
2149 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2151 r = order_compare(view, order, array[i], array[j], &swap);
2152 if (r != ERROR_SUCCESS)
2153 return r;
2155 if (swap)
2157 temp = array[j];
2158 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2159 array[i] = temp;
2160 j++;
2161 center++;
2165 return ERROR_SUCCESS;
2168 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2170 UINT i, swap, r;
2172 for (i = 1; i < num_rows; i++)
2174 r = order_compare(view, order, order->reorder[i - 1],
2175 order->reorder[i], &swap);
2176 if (r != ERROR_SUCCESS)
2177 return r;
2179 if (!swap)
2180 continue;
2182 ERR("Bad order! %d\n", i);
2183 return ERROR_FUNCTION_FAILED;
2186 return ERROR_SUCCESS;
2189 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2191 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2192 MSIORDERINFO *order;
2193 column_info *ptr;
2194 UINT r, i;
2195 UINT rows, cols;
2197 TRACE("sorting table %s\n", debugstr_w(tv->name));
2199 r = TABLE_get_dimensions(view, &rows, &cols);
2200 if (r != ERROR_SUCCESS)
2201 return r;
2203 if (rows == 0)
2204 return ERROR_SUCCESS;
2206 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2207 if (!order)
2208 return ERROR_OUTOFMEMORY;
2210 for (ptr = columns; ptr; ptr = ptr->next)
2211 order_add_column(view, order, ptr->column);
2213 order->reorder = msi_alloc(rows * sizeof(UINT));
2214 if (!order->reorder)
2215 return ERROR_OUTOFMEMORY;
2217 for (i = 0; i < rows; i++)
2218 order->reorder[i] = i;
2220 r = order_mergesort(view, order, 0, rows - 1);
2221 if (r != ERROR_SUCCESS)
2222 return r;
2224 r = order_verify(view, order, rows);
2225 if (r != ERROR_SUCCESS)
2226 return r;
2228 tv->order = order;
2230 return ERROR_SUCCESS;
2233 static UINT TABLE_drop(struct tagMSIVIEW *view)
2235 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2236 MSIVIEW *tables = NULL;
2237 MSIRECORD *rec = NULL;
2238 UINT r, row;
2239 INT i;
2241 TRACE("dropping table %s\n", debugstr_w(tv->name));
2243 for (i = tv->table->col_count - 1; i >= 0; i--)
2245 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2246 tv->table->colinfo[i].number);
2247 if (r != ERROR_SUCCESS)
2248 return r;
2251 rec = MSI_CreateRecord(1);
2252 if (!rec)
2253 return ERROR_OUTOFMEMORY;
2255 MSI_RecordSetStringW(rec, 1, tv->name);
2257 r = TABLE_CreateView(tv->db, szTables, &tables);
2258 if (r != ERROR_SUCCESS)
2259 return r;
2261 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2262 if (r != ERROR_SUCCESS)
2263 goto done;
2265 r = TABLE_delete_row(tables, row);
2266 if (r != ERROR_SUCCESS)
2267 goto done;
2269 list_remove(&tv->table->entry);
2270 free_table(tv->table);
2272 done:
2273 msiobj_release(&rec->hdr);
2274 tables->ops->delete(tables);
2276 return r;
2279 static const MSIVIEWOPS table_ops =
2281 TABLE_fetch_int,
2282 TABLE_fetch_stream,
2283 TABLE_get_row,
2284 TABLE_set_row,
2285 TABLE_insert_row,
2286 TABLE_delete_row,
2287 TABLE_execute,
2288 TABLE_close,
2289 TABLE_get_dimensions,
2290 TABLE_get_column_info,
2291 TABLE_modify,
2292 TABLE_delete,
2293 TABLE_find_matching_rows,
2294 TABLE_add_ref,
2295 TABLE_release,
2296 TABLE_add_column,
2297 TABLE_remove_column,
2298 TABLE_sort,
2299 TABLE_drop,
2302 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2304 MSITABLEVIEW *tv ;
2305 UINT r, sz;
2307 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2309 if ( !strcmpW( name, szStreams ) )
2310 return STREAMS_CreateView( db, view );
2311 else if ( !strcmpW( name, szStorages ) )
2312 return STORAGES_CreateView( db, view );
2314 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2315 tv = msi_alloc_zero( sz );
2316 if( !tv )
2317 return ERROR_FUNCTION_FAILED;
2319 r = get_table( db, name, &tv->table );
2320 if( r != ERROR_SUCCESS )
2322 msi_free( tv );
2323 WARN("table not found\n");
2324 return r;
2327 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2329 /* fill the structure */
2330 tv->view.ops = &table_ops;
2331 tv->db = db;
2332 tv->columns = tv->table->colinfo;
2333 tv->num_cols = tv->table->col_count;
2334 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2336 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2338 *view = (MSIVIEW*) tv;
2339 lstrcpyW( tv->name, name );
2341 return ERROR_SUCCESS;
2344 UINT MSI_CommitTables( MSIDATABASE *db )
2346 UINT r, bytes_per_strref;
2347 HRESULT hr;
2348 MSITABLE *table = NULL;
2350 TRACE("%p\n",db);
2352 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2353 if( r != ERROR_SUCCESS )
2355 WARN("failed to save string table r=%08x\n",r);
2356 return r;
2359 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2361 r = save_table( db, table, bytes_per_strref );
2362 if( r != ERROR_SUCCESS )
2364 WARN("failed to save table %s (r=%08x)\n",
2365 debugstr_w(table->name), r);
2366 return r;
2370 /* force everything to reload next time */
2371 free_cached_tables( db );
2373 hr = IStorage_Commit( db->storage, 0 );
2374 if (FAILED( hr ))
2376 WARN("failed to commit changes 0x%08x\n", hr);
2377 r = ERROR_FUNCTION_FAILED;
2379 return r;
2382 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2384 MSITABLE *t;
2385 UINT r;
2387 TRACE("%p %s\n", db, debugstr_w(table));
2389 if (!table)
2390 return MSICONDITION_ERROR;
2392 r = get_table( db, table, &t );
2393 if (r != ERROR_SUCCESS)
2394 return MSICONDITION_NONE;
2396 return t->persistent;
2399 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2401 UINT ret = 0, i;
2403 for (i = 0; i < bytes; i++)
2404 ret += (data[col + i] << i * 8);
2406 return ret;
2409 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2411 LPWSTR stname = NULL, sval, p;
2412 DWORD len;
2413 UINT i, r;
2415 TRACE("%p %p\n", tv, rec);
2417 len = lstrlenW( tv->name ) + 1;
2418 stname = msi_alloc( len*sizeof(WCHAR) );
2419 if ( !stname )
2421 r = ERROR_OUTOFMEMORY;
2422 goto err;
2425 lstrcpyW( stname, tv->name );
2427 for ( i = 0; i < tv->num_cols; i++ )
2429 if ( tv->columns[i].type & MSITYPE_KEY )
2431 sval = msi_dup_record_field( rec, i + 1 );
2432 if ( !sval )
2434 r = ERROR_OUTOFMEMORY;
2435 goto err;
2438 len += lstrlenW( szDot ) + lstrlenW ( sval );
2439 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2440 if ( !p )
2442 r = ERROR_OUTOFMEMORY;
2443 goto err;
2445 stname = p;
2447 lstrcatW( stname, szDot );
2448 lstrcatW( stname, sval );
2450 msi_free( sval );
2452 else
2453 continue;
2456 *pstname = encode_streamname( FALSE, stname );
2457 msi_free( stname );
2459 return ERROR_SUCCESS;
2461 err:
2462 msi_free ( stname );
2463 *pstname = NULL;
2464 return r;
2467 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2468 IStorage *stg,
2469 const BYTE *rawdata, UINT bytes_per_strref )
2471 UINT i, val, ofs = 0;
2472 USHORT mask;
2473 MSICOLUMNINFO *columns = tv->columns;
2474 MSIRECORD *rec;
2476 mask = rawdata[0] | (rawdata[1] << 8);
2477 rawdata += 2;
2479 rec = MSI_CreateRecord( tv->num_cols );
2480 if( !rec )
2481 return rec;
2483 TRACE("row ->\n");
2484 for( i=0; i<tv->num_cols; i++ )
2486 if ( (mask&1) && (i>=(mask>>8)) )
2487 break;
2488 /* all keys must be present */
2489 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2490 continue;
2492 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2494 LPWSTR encname;
2495 IStream *stm = NULL;
2496 UINT r;
2498 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2500 r = msi_record_encoded_stream_name( tv, rec, &encname );
2501 if ( r != ERROR_SUCCESS )
2502 return NULL;
2504 r = IStorage_OpenStream( stg, encname, NULL,
2505 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2506 msi_free( encname );
2507 if ( r != ERROR_SUCCESS )
2508 return NULL;
2510 MSI_RecordSetStream( rec, i+1, stm );
2511 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2513 else if( columns[i].type & MSITYPE_STRING )
2515 LPCWSTR sval;
2517 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2518 sval = msi_string_lookup_id( st, val );
2519 MSI_RecordSetStringW( rec, i+1, sval );
2520 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2521 ofs += bytes_per_strref;
2523 else
2525 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2526 switch( n )
2528 case 2:
2529 val = read_raw_int(rawdata, ofs, n);
2530 if (val)
2531 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2532 TRACE(" field %d [0x%04x]\n", i+1, val );
2533 break;
2534 case 4:
2535 val = read_raw_int(rawdata, ofs, n);
2536 if (val)
2537 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2538 TRACE(" field %d [0x%08x]\n", i+1, val );
2539 break;
2540 default:
2541 ERR("oops - unknown column width %d\n", n);
2542 break;
2544 ofs += n;
2547 return rec;
2550 static void dump_record( MSIRECORD *rec )
2552 UINT i, n;
2554 n = MSI_RecordGetFieldCount( rec );
2555 for( i=1; i<=n; i++ )
2557 LPCWSTR sval;
2559 if( MSI_RecordIsNull( rec, i ) )
2560 TRACE("row -> []\n");
2561 else if( (sval = MSI_RecordGetString( rec, i )) )
2562 TRACE("row -> [%s]\n", debugstr_w(sval));
2563 else
2564 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2568 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2570 LPCWSTR sval;
2571 UINT i;
2573 for( i=0; i<(rawsize/2); i++ )
2575 sval = msi_string_lookup_id( st, rawdata[i] );
2576 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2580 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2582 LPCWSTR str;
2583 UINT i, r, *data;
2585 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2586 for( i=0; i<tv->num_cols; i++ )
2588 data[i] = 0;
2590 if ( ~tv->columns[i].type & MSITYPE_KEY )
2591 continue;
2593 /* turn the transform column value into a row value */
2594 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2595 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2597 str = MSI_RecordGetString( rec, i+1 );
2598 if (str)
2600 r = msi_string2idW( tv->db->strings, str, &data[i] );
2602 /* if there's no matching string in the string table,
2603 these keys can't match any record, so fail now. */
2604 if (r != ERROR_SUCCESS)
2606 msi_free( data );
2607 return NULL;
2610 else data[i] = 0;
2612 else
2614 data[i] = MSI_RecordGetInteger( rec, i+1 );
2616 if (data[i] == MSI_NULL_INTEGER)
2617 data[i] = 0;
2618 else if ((tv->columns[i].type&0xff) == 2)
2619 data[i] += 0x8000;
2620 else
2621 data[i] += 0x80000000;
2624 return data;
2627 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2629 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2631 for( i=0; i<tv->num_cols; i++ )
2633 if ( ~tv->columns[i].type & MSITYPE_KEY )
2634 continue;
2636 /* turn the transform column value into a row value */
2637 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2638 if ( r != ERROR_SUCCESS )
2640 ERR("TABLE_fetch_int shouldn't fail here\n");
2641 break;
2644 /* if this key matches, move to the next column */
2645 if ( x != data[i] )
2647 ret = ERROR_FUNCTION_FAILED;
2648 break;
2650 if (column) *column = i;
2651 ret = ERROR_SUCCESS;
2653 return ret;
2656 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2658 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2660 data = msi_record_to_row( tv, rec );
2661 if( !data )
2662 return r;
2663 for( i = 0; i < tv->table->row_count; i++ )
2665 r = msi_row_matches( tv, i, data, column );
2666 if( r == ERROR_SUCCESS )
2668 *row = i;
2669 break;
2672 msi_free( data );
2673 return r;
2676 typedef struct
2678 struct list entry;
2679 LPWSTR name;
2680 } TRANSFORMDATA;
2682 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2683 string_table *st, TRANSFORMDATA *transform,
2684 UINT bytes_per_strref )
2686 UINT rawsize = 0;
2687 BYTE *rawdata = NULL;
2688 MSITABLEVIEW *tv = NULL;
2689 UINT r, n, sz, i, mask;
2690 MSIRECORD *rec = NULL;
2691 UINT colcol = 0;
2692 WCHAR coltable[32];
2693 LPWSTR name;
2695 if (!transform)
2696 return ERROR_SUCCESS;
2698 name = transform->name;
2700 coltable[0] = 0;
2701 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2703 /* read the transform data */
2704 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2705 if ( !rawdata )
2707 TRACE("table %s empty\n", debugstr_w(name) );
2708 return ERROR_INVALID_TABLE;
2711 /* create a table view */
2712 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2713 if( r != ERROR_SUCCESS )
2714 goto err;
2716 r = tv->view.ops->execute( &tv->view, NULL );
2717 if( r != ERROR_SUCCESS )
2718 goto err;
2720 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2721 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2723 /* interpret the data */
2724 for( n=0; n < rawsize; )
2726 mask = rawdata[n] | (rawdata[n+1] << 8);
2728 if (mask&1)
2731 * if the low bit is set, columns are continuous and
2732 * the number of columns is specified in the high byte
2734 sz = 2;
2735 for( i=0; i<tv->num_cols; i++ )
2737 if( (tv->columns[i].type & MSITYPE_STRING) &&
2738 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2739 sz += bytes_per_strref;
2740 else
2741 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2744 else
2747 * If the low bit is not set, mask is a bitmask.
2748 * Excepting for key fields, which are always present,
2749 * each bit indicates that a field is present in the transform record.
2751 * mask == 0 is a special case ... only the keys will be present
2752 * and it means that this row should be deleted.
2754 sz = 2;
2755 for( i=0; i<tv->num_cols; i++ )
2757 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2759 if( (tv->columns[i].type & MSITYPE_STRING) &&
2760 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2761 sz += bytes_per_strref;
2762 else
2763 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2768 /* check we didn't run of the end of the table */
2769 if ( (n+sz) > rawsize )
2771 ERR("borked.\n");
2772 dump_table( st, (USHORT *)rawdata, rawsize );
2773 break;
2776 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2777 if (rec)
2779 WCHAR table[32];
2780 DWORD sz = 32;
2781 UINT number = MSI_NULL_INTEGER;
2782 UINT row = 0;
2784 if (!strcmpW( name, szColumns ))
2786 MSI_RecordGetStringW( rec, 1, table, &sz );
2787 number = MSI_RecordGetInteger( rec, 2 );
2790 * Native msi seems writes nul into the Number (2nd) column of
2791 * the _Columns table, only when the columns are from a new table
2793 if ( number == MSI_NULL_INTEGER )
2795 /* reset the column number on a new table */
2796 if (strcmpW( coltable, table ))
2798 colcol = 0;
2799 lstrcpyW( coltable, table );
2802 /* fix nul column numbers */
2803 MSI_RecordSetInteger( rec, 2, ++colcol );
2807 if (TRACE_ON(msidb)) dump_record( rec );
2809 r = msi_table_find_row( tv, rec, &row, NULL );
2810 if (r == ERROR_SUCCESS)
2812 if (!mask)
2814 TRACE("deleting row [%d]:\n", row);
2815 r = TABLE_delete_row( &tv->view, row );
2816 if (r != ERROR_SUCCESS)
2817 WARN("failed to delete row %u\n", r);
2819 else if (mask & 1)
2821 TRACE("modifying full row [%d]:\n", row);
2822 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2823 if (r != ERROR_SUCCESS)
2824 WARN("failed to modify row %u\n", r);
2826 else
2828 TRACE("modifying masked row [%d]:\n", row);
2829 r = TABLE_set_row( &tv->view, row, rec, mask );
2830 if (r != ERROR_SUCCESS)
2831 WARN("failed to modify row %u\n", r);
2834 else
2836 TRACE("inserting row\n");
2837 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2838 if (r != ERROR_SUCCESS)
2839 WARN("failed to insert row %u\n", r);
2842 if (number != MSI_NULL_INTEGER && !strcmpW( name, szColumns ))
2843 msi_update_table_columns( db, table );
2845 msiobj_release( &rec->hdr );
2848 n += sz;
2851 err:
2852 /* no need to free the table, it's associated with the database */
2853 msi_free( rawdata );
2854 if( tv )
2855 tv->view.ops->delete( &tv->view );
2857 return ERROR_SUCCESS;
2861 * msi_table_apply_transform
2863 * Enumerate the table transforms in a transform storage and apply each one.
2865 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2867 struct list transforms;
2868 IEnumSTATSTG *stgenum = NULL;
2869 TRANSFORMDATA *transform;
2870 TRANSFORMDATA *tables = NULL, *columns = NULL;
2871 HRESULT r;
2872 STATSTG stat;
2873 string_table *strings;
2874 UINT ret = ERROR_FUNCTION_FAILED;
2875 UINT bytes_per_strref;
2877 TRACE("%p %p\n", db, stg );
2879 strings = msi_load_string_table( stg, &bytes_per_strref );
2880 if( !strings )
2881 goto end;
2883 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2884 if( FAILED( r ) )
2885 goto end;
2887 list_init(&transforms);
2889 while ( TRUE )
2891 MSITABLEVIEW *tv = NULL;
2892 WCHAR name[0x40];
2893 ULONG count = 0;
2895 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2896 if ( FAILED( r ) || !count )
2897 break;
2899 decode_streamname( stat.pwcsName, name );
2900 CoTaskMemFree( stat.pwcsName );
2901 if ( name[0] != 0x4840 )
2902 continue;
2904 if ( !strcmpW( name+1, szStringPool ) ||
2905 !strcmpW( name+1, szStringData ) )
2906 continue;
2908 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2909 if ( !transform )
2910 break;
2912 list_add_tail( &transforms, &transform->entry );
2914 transform->name = strdupW( name + 1 );
2916 if ( !strcmpW( transform->name, szTables ) )
2917 tables = transform;
2918 else if (!strcmpW( transform->name, szColumns ) )
2919 columns = transform;
2921 TRACE("transform contains stream %s\n", debugstr_w(name));
2923 /* load the table */
2924 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2925 if( r != ERROR_SUCCESS )
2926 continue;
2928 r = tv->view.ops->execute( &tv->view, NULL );
2929 if( r != ERROR_SUCCESS )
2931 tv->view.ops->delete( &tv->view );
2932 continue;
2935 tv->view.ops->delete( &tv->view );
2939 * Apply _Tables and _Columns transforms first so that
2940 * the table metadata is correct, and empty tables exist.
2942 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2943 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2944 goto end;
2946 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2947 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2948 goto end;
2950 ret = ERROR_SUCCESS;
2952 while ( !list_empty( &transforms ) )
2954 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2956 if ( strcmpW( transform->name, szColumns ) &&
2957 strcmpW( transform->name, szTables ) &&
2958 ret == ERROR_SUCCESS )
2960 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2963 list_remove( &transform->entry );
2964 msi_free( transform->name );
2965 msi_free( transform );
2968 if ( ret == ERROR_SUCCESS )
2969 append_storage_to_db( db, stg );
2971 end:
2972 if ( stgenum )
2973 IEnumSTATSTG_Release( stgenum );
2974 if ( strings )
2975 msi_destroy_stringtable( strings );
2977 return ret;