3007d485b2b5650b06e962f4725750886aada400
[reactos.git] / reactos / dll / win32 / msi / database.c
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
3 *
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
39
40 #include "initguid.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
43
44 /*
45 * .MSI file format
46 *
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
52 */
53
54 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
55
56 typedef struct tagMSITRANSFORM {
57 struct list entry;
58 IStorage *stg;
59 } MSITRANSFORM;
60
61 typedef struct tagMSISTREAM {
62 struct list entry;
63 IStream *stm;
64 } MSISTREAM;
65
66 static UINT find_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
67 {
68 MSISTREAM *stream;
69
70 LIST_FOR_EACH_ENTRY( stream, &db->streams, MSISTREAM, entry )
71 {
72 HRESULT r;
73 STATSTG stat;
74
75 r = IStream_Stat( stream->stm, &stat, 0 );
76 if( FAILED( r ) )
77 {
78 WARN("failed to stat stream r = %08x!\n", r);
79 continue;
80 }
81
82 if( !lstrcmpW( name, stat.pwcsName ) )
83 {
84 TRACE("found %s\n", debugstr_w(name));
85 *stm = stream->stm;
86 CoTaskMemFree( stat.pwcsName );
87 return ERROR_SUCCESS;
88 }
89
90 CoTaskMemFree( stat.pwcsName );
91 }
92
93 return ERROR_FUNCTION_FAILED;
94 }
95
96 static UINT clone_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
97 {
98 IStream *stream;
99
100 if (find_open_stream( db, name, &stream ) == ERROR_SUCCESS)
101 {
102 HRESULT r;
103 LARGE_INTEGER pos;
104
105 r = IStream_Clone( stream, stm );
106 if( FAILED( r ) )
107 {
108 WARN("failed to clone stream r = %08x!\n", r);
109 return ERROR_FUNCTION_FAILED;
110 }
111
112 pos.QuadPart = 0;
113 r = IStream_Seek( *stm, pos, STREAM_SEEK_SET, NULL );
114 if( FAILED( r ) )
115 {
116 IStream_Release( *stm );
117 return ERROR_FUNCTION_FAILED;
118 }
119
120 return ERROR_SUCCESS;
121 }
122
123 return ERROR_FUNCTION_FAILED;
124 }
125
126 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
127 {
128 HRESULT r;
129 WCHAR decoded[MAX_STREAM_NAME_LEN];
130
131 decode_streamname( stname, decoded );
132 TRACE("%s -> %s\n", debugstr_w(stname), debugstr_w(decoded));
133
134 if (clone_open_stream( db, stname, stm ) == ERROR_SUCCESS)
135 return ERROR_SUCCESS;
136
137 r = IStorage_OpenStream( db->storage, stname, NULL,
138 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
139 if( FAILED( r ) )
140 {
141 MSITRANSFORM *transform;
142
143 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
144 {
145 r = IStorage_OpenStream( transform->stg, stname, NULL,
146 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
147 if (SUCCEEDED(r))
148 break;
149 }
150 }
151
152 if( SUCCEEDED(r) )
153 {
154 MSISTREAM *stream;
155
156 stream = msi_alloc( sizeof(MSISTREAM) );
157 if( !stream )
158 return ERROR_NOT_ENOUGH_MEMORY;
159
160 stream->stm = *stm;
161 IStream_AddRef( *stm );
162 list_add_tail( &db->streams, &stream->entry );
163 }
164
165 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
166 }
167
168 static void free_transforms( MSIDATABASE *db )
169 {
170 while( !list_empty( &db->transforms ) )
171 {
172 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
173 MSITRANSFORM, entry );
174 list_remove( &t->entry );
175 IStorage_Release( t->stg );
176 msi_free( t );
177 }
178 }
179
180 void db_destroy_stream( MSIDATABASE *db, LPCWSTR stname )
181 {
182 MSISTREAM *stream, *stream2;
183
184 LIST_FOR_EACH_ENTRY_SAFE( stream, stream2, &db->streams, MSISTREAM, entry )
185 {
186 HRESULT r;
187 STATSTG stat;
188
189 r = IStream_Stat( stream->stm, &stat, 0 );
190 if (FAILED(r))
191 {
192 WARN("failed to stat stream r = %08x\n", r);
193 continue;
194 }
195
196 if (!strcmpW( stname, stat.pwcsName ))
197 {
198 TRACE("destroying %s\n", debugstr_w(stname));
199
200 list_remove( &stream->entry );
201 IStream_Release( stream->stm );
202 msi_free( stream );
203 IStorage_DestroyElement( db->storage, stname );
204 CoTaskMemFree( stat.pwcsName );
205 break;
206 }
207 CoTaskMemFree( stat.pwcsName );
208 }
209 }
210
211 static void free_streams( MSIDATABASE *db )
212 {
213 while( !list_empty( &db->streams ) )
214 {
215 MSISTREAM *s = LIST_ENTRY( list_head( &db->streams ),
216 MSISTREAM, entry );
217 list_remove( &s->entry );
218 IStream_Release( s->stm );
219 msi_free( s );
220 }
221 }
222
223 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
224 {
225 MSITRANSFORM *t;
226
227 t = msi_alloc( sizeof *t );
228 t->stg = stg;
229 IStorage_AddRef( stg );
230 list_add_head( &db->transforms, &t->entry );
231
232 /* the transform may add or replace streams */
233 free_streams( db );
234 }
235
236 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
237 {
238 MSIDATABASE *db = (MSIDATABASE *) arg;
239
240 msi_free(db->path);
241 free_cached_tables( db );
242 free_streams( db );
243 free_transforms( db );
244 if (db->strings) msi_destroy_stringtable( db->strings );
245 IStorage_Release( db->storage );
246 if (db->deletefile)
247 {
248 DeleteFileW( db->deletefile );
249 msi_free( db->deletefile );
250 }
251 if (db->localfile)
252 {
253 DeleteFileW( db->localfile );
254 msi_free( db->localfile );
255 }
256 }
257
258 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
259 {
260 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
261 HRESULT hr;
262
263 hr = IStorage_SetClass( stg, clsid );
264 if (FAILED( hr ))
265 {
266 WARN("failed to set class id 0x%08x\n", hr);
267 return hr;
268 }
269
270 /* create the _Tables stream */
271 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
272 if (FAILED( hr ))
273 {
274 WARN("failed to create _Tables stream 0x%08x\n", hr);
275 return hr;
276 }
277
278 hr = msi_init_string_table( stg );
279 if (FAILED( hr ))
280 {
281 WARN("failed to initialize string table 0x%08x\n", hr);
282 return hr;
283 }
284
285 hr = IStorage_Commit( stg, 0 );
286 if (FAILED( hr ))
287 {
288 WARN("failed to commit changes 0x%08x\n", hr);
289 return hr;
290 }
291
292 return S_OK;
293 }
294
295 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
296 {
297 IStorage *stg = NULL;
298 HRESULT r;
299 MSIDATABASE *db = NULL;
300 UINT ret = ERROR_FUNCTION_FAILED;
301 LPCWSTR szMode, save_path;
302 STATSTG stat;
303 BOOL created = FALSE, patch = FALSE;
304 WCHAR path[MAX_PATH];
305
306 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
307
308 if( !pdb )
309 return ERROR_INVALID_PARAMETER;
310
311 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
312 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
313 {
314 TRACE("Database is a patch\n");
315 szPersist -= MSIDBOPEN_PATCHFILE;
316 patch = TRUE;
317 }
318
319 save_path = szDBPath;
320 szMode = szPersist;
321 if( !IS_INTMSIDBOPEN(szPersist) )
322 {
323 if (!CopyFileW( szDBPath, szPersist, FALSE ))
324 return ERROR_OPEN_FAILED;
325
326 szDBPath = szPersist;
327 szPersist = MSIDBOPEN_TRANSACT;
328 created = TRUE;
329 }
330
331 if( szPersist == MSIDBOPEN_READONLY )
332 {
333 r = StgOpenStorage( szDBPath, NULL,
334 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
335 }
336 else if( szPersist == MSIDBOPEN_CREATE )
337 {
338 r = StgCreateDocfile( szDBPath,
339 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
340
341 if( SUCCEEDED(r) )
342 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
343 created = TRUE;
344 }
345 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
346 {
347 r = StgCreateDocfile( szDBPath,
348 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
349
350 if( SUCCEEDED(r) )
351 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
352 created = TRUE;
353 }
354 else if( szPersist == MSIDBOPEN_TRANSACT )
355 {
356 r = StgOpenStorage( szDBPath, NULL,
357 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
358 }
359 else if( szPersist == MSIDBOPEN_DIRECT )
360 {
361 r = StgOpenStorage( szDBPath, NULL,
362 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
363 }
364 else
365 {
366 ERR("unknown flag %p\n",szPersist);
367 return ERROR_INVALID_PARAMETER;
368 }
369
370 if( FAILED( r ) || !stg )
371 {
372 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
373 return ERROR_FUNCTION_FAILED;
374 }
375
376 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
377 if( FAILED( r ) )
378 {
379 FIXME("Failed to stat storage\n");
380 goto end;
381 }
382
383 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
384 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
385 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
386 {
387 ERR("storage GUID is not a MSI database GUID %s\n",
388 debugstr_guid(&stat.clsid) );
389 goto end;
390 }
391
392 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
393 {
394 ERR("storage GUID is not the MSI patch GUID %s\n",
395 debugstr_guid(&stat.clsid) );
396 ret = ERROR_OPEN_FAILED;
397 goto end;
398 }
399
400 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
401 MSI_CloseDatabase );
402 if( !db )
403 {
404 FIXME("Failed to allocate a handle\n");
405 goto end;
406 }
407
408 if (!strchrW( save_path, '\\' ))
409 {
410 GetCurrentDirectoryW( MAX_PATH, path );
411 lstrcatW( path, szBackSlash );
412 lstrcatW( path, save_path );
413 }
414 else
415 lstrcpyW( path, save_path );
416
417 db->path = strdupW( path );
418
419 if( TRACE_ON( msi ) )
420 enum_stream_names( stg );
421
422 db->storage = stg;
423 db->mode = szMode;
424 if (created)
425 db->deletefile = strdupW( szDBPath );
426 list_init( &db->tables );
427 list_init( &db->transforms );
428 list_init( &db->streams );
429
430 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
431 if( !db->strings )
432 goto end;
433
434 ret = ERROR_SUCCESS;
435
436 msiobj_addref( &db->hdr );
437 IStorage_AddRef( stg );
438 *pdb = db;
439
440 end:
441 if( db )
442 msiobj_release( &db->hdr );
443 if( stg )
444 IStorage_Release( stg );
445
446 return ret;
447 }
448
449 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
450 {
451 MSIDATABASE *db;
452 UINT ret;
453
454 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
455
456 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
457 if( ret == ERROR_SUCCESS )
458 {
459 *phDB = alloc_msihandle( &db->hdr );
460 if (! *phDB)
461 ret = ERROR_NOT_ENOUGH_MEMORY;
462 msiobj_release( &db->hdr );
463 }
464
465 return ret;
466 }
467
468 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
469 {
470 HRESULT r = ERROR_FUNCTION_FAILED;
471 LPWSTR szwDBPath = NULL, szwPersist = NULL;
472
473 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
474
475 if( szDBPath )
476 {
477 szwDBPath = strdupAtoW( szDBPath );
478 if( !szwDBPath )
479 goto end;
480 }
481
482 if( !IS_INTMSIDBOPEN(szPersist) )
483 {
484 szwPersist = strdupAtoW( szPersist );
485 if( !szwPersist )
486 goto end;
487 }
488 else
489 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
490
491 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
492
493 end:
494 if( !IS_INTMSIDBOPEN(szPersist) )
495 msi_free( szwPersist );
496 msi_free( szwDBPath );
497
498 return r;
499 }
500
501 static LPWSTR msi_read_text_archive(LPCWSTR path)
502 {
503 HANDLE file;
504 LPSTR data = NULL;
505 LPWSTR wdata = NULL;
506 DWORD read, size = 0;
507
508 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
509 if (file == INVALID_HANDLE_VALUE)
510 return NULL;
511
512 size = GetFileSize( file, NULL );
513 data = msi_alloc( size + 1 );
514 if (!data)
515 goto done;
516
517 if (!ReadFile( file, data, size, &read, NULL ))
518 goto done;
519
520 data[size] = '\0';
521 wdata = strdupAtoW( data );
522
523 done:
524 CloseHandle( file );
525 msi_free( data );
526 return wdata;
527 }
528
529 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
530 {
531 LPWSTR ptr = *line, save;
532 DWORD i, count = 1;
533
534 *entries = NULL;
535
536 /* stay on this line */
537 while (*ptr && *ptr != '\n')
538 {
539 /* entries are separated by tabs */
540 if (*ptr == '\t')
541 count++;
542
543 ptr++;
544 }
545
546 *entries = msi_alloc(count * sizeof(LPWSTR));
547 if (!*entries)
548 return;
549
550 /* store pointers into the data */
551 for (i = 0, ptr = *line; i < count; i++)
552 {
553 while (*ptr && *ptr == '\r') ptr++;
554 save = ptr;
555
556 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
557
558 /* NULL-separate the data */
559 if (*ptr == '\n' || *ptr == '\r')
560 {
561 while (*ptr == '\n' || *ptr == '\r')
562 *(ptr++) = '\0';
563 }
564 else if (*ptr)
565 *ptr++ = '\0';
566
567 (*entries)[i] = save;
568 }
569
570 /* move to the next line if there's more, else EOF */
571 *line = ptr;
572
573 if (num_entries)
574 *num_entries = count;
575 }
576
577 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
578 {
579 LPWSTR prelude;
580 DWORD size;
581
582 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
583
584 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
585 prelude = msi_alloc(size * sizeof(WCHAR));
586 if (!prelude)
587 return NULL;
588
589 sprintfW(prelude, create_fmt, table);
590 return prelude;
591 }
592
593 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
594 {
595 LPWSTR columns, p;
596 LPCWSTR type;
597 DWORD sql_size = 1, i, len;
598 WCHAR expanded[128], *ptr;
599 WCHAR size[10], comma[2], extra[30];
600
601 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
602 static const WCHAR size_fmt[] = {'(','%','s',')',0};
603 static const WCHAR type_char[] = {'C','H','A','R',0};
604 static const WCHAR type_int[] = {'I','N','T',0};
605 static const WCHAR type_long[] = {'L','O','N','G',0};
606 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
607 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
608 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
609
610 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
611 if (!columns)
612 return NULL;
613
614 for (i = 0; i < num_columns; i++)
615 {
616 type = NULL;
617 comma[1] = size[0] = extra[0] = '\0';
618
619 if (i == num_columns - 1)
620 comma[0] = '\0';
621 else
622 comma[0] = ',';
623
624 ptr = &types[i][1];
625 len = atolW(ptr);
626 extra[0] = '\0';
627
628 switch (types[i][0])
629 {
630 case 'l':
631 lstrcpyW(extra, type_notnull);
632 case 'L':
633 lstrcatW(extra, localizable);
634 type = type_char;
635 sprintfW(size, size_fmt, ptr);
636 break;
637 case 's':
638 lstrcpyW(extra, type_notnull);
639 case 'S':
640 type = type_char;
641 sprintfW(size, size_fmt, ptr);
642 break;
643 case 'i':
644 lstrcpyW(extra, type_notnull);
645 case 'I':
646 if (len <= 2)
647 type = type_int;
648 else if (len == 4)
649 type = type_long;
650 else
651 {
652 WARN("invalid int width %u\n", len);
653 msi_free(columns);
654 return NULL;
655 }
656 break;
657 case 'v':
658 lstrcpyW(extra, type_notnull);
659 case 'V':
660 type = type_object;
661 break;
662 default:
663 ERR("Unknown type: %c\n", types[i][0]);
664 msi_free(columns);
665 return NULL;
666 }
667
668 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
669 sql_size += lstrlenW(expanded);
670
671 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
672 if (!p)
673 {
674 msi_free(columns);
675 return NULL;
676 }
677 columns = p;
678
679 lstrcatW(columns, expanded);
680 }
681
682 return columns;
683 }
684
685 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
686 {
687 LPWSTR postlude, keys, ptr;
688 DWORD size, key_size, i;
689
690 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
691 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
692
693 for (i = 0, size = 1; i < num_keys; i++)
694 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
695
696 keys = msi_alloc(size * sizeof(WCHAR));
697 if (!keys)
698 return NULL;
699
700 for (i = 0, ptr = keys; i < num_keys; i++)
701 {
702 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
703 sprintfW(ptr, key_fmt, primary_keys[i]);
704 ptr += key_size;
705 }
706
707 /* remove final ', ' */
708 *(ptr - 2) = '\0';
709
710 size = lstrlenW(postlude_fmt) + size - 1;
711 postlude = msi_alloc(size * sizeof(WCHAR));
712 if (!postlude)
713 goto done;
714
715 sprintfW(postlude, postlude_fmt, keys);
716
717 done:
718 msi_free(keys);
719 return postlude;
720 }
721
722 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
723 {
724 UINT r = ERROR_OUTOFMEMORY;
725 DWORD size;
726 MSIQUERY *view;
727 LPWSTR create_sql = NULL;
728 LPWSTR prelude, columns_sql, postlude;
729
730 prelude = msi_build_createsql_prelude(labels[0]);
731 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
732 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
733
734 if (!prelude || !columns_sql || !postlude)
735 goto done;
736
737 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
738 create_sql = msi_alloc(size * sizeof(WCHAR));
739 if (!create_sql)
740 goto done;
741
742 lstrcpyW(create_sql, prelude);
743 lstrcatW(create_sql, columns_sql);
744 lstrcatW(create_sql, postlude);
745
746 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
747 if (r != ERROR_SUCCESS)
748 goto done;
749
750 r = MSI_ViewExecute(view, NULL);
751 MSI_ViewClose(view);
752 msiobj_release(&view->hdr);
753
754 done:
755 msi_free(prelude);
756 msi_free(columns_sql);
757 msi_free(postlude);
758 msi_free(create_sql);
759 return r;
760 }
761
762 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
763 {
764 DWORD len;
765 LPWSTR fullname, ptr;
766
767 len = lstrlenW(path) + lstrlenW(name) + 1;
768 fullname = msi_alloc(len*sizeof(WCHAR));
769 if (!fullname)
770 return NULL;
771
772 lstrcpyW( fullname, path );
773
774 /* chop off extension from path */
775 ptr = strrchrW(fullname, '.');
776 if (!ptr)
777 {
778 msi_free (fullname);
779 return NULL;
780 }
781 *ptr++ = '\\';
782 lstrcpyW( ptr, name );
783 return fullname;
784 }
785
786 static UINT construct_record(DWORD num_columns, LPWSTR *types,
787 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
788 {
789 UINT i;
790
791 *rec = MSI_CreateRecord(num_columns);
792 if (!*rec)
793 return ERROR_OUTOFMEMORY;
794
795 for (i = 0; i < num_columns; i++)
796 {
797 switch (types[i][0])
798 {
799 case 'L': case 'l': case 'S': case 's':
800 MSI_RecordSetStringW(*rec, i + 1, data[i]);
801 break;
802 case 'I': case 'i':
803 if (*data[i])
804 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
805 break;
806 case 'V': case 'v':
807 if (*data[i])
808 {
809 UINT r;
810 LPWSTR file = msi_import_stream_filename(path, data[i]);
811 if (!file)
812 return ERROR_FUNCTION_FAILED;
813
814 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
815 msi_free (file);
816 if (r != ERROR_SUCCESS)
817 return ERROR_FUNCTION_FAILED;
818 }
819 break;
820 default:
821 ERR("Unhandled column type: %c\n", types[i][0]);
822 msiobj_release(&(*rec)->hdr);
823 return ERROR_FUNCTION_FAILED;
824 }
825 }
826
827 return ERROR_SUCCESS;
828 }
829
830 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
831 LPWSTR *labels, LPWSTR **records,
832 int num_columns, int num_records,
833 LPWSTR path)
834 {
835 UINT r;
836 int i;
837 MSIQUERY *view;
838 MSIRECORD *rec;
839
840 static const WCHAR select[] = {
841 'S','E','L','E','C','T',' ','*',' ',
842 'F','R','O','M',' ','`','%','s','`',0
843 };
844
845 r = MSI_OpenQuery(db, &view, select, labels[0]);
846 if (r != ERROR_SUCCESS)
847 return r;
848
849 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
850 {
851 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
852 msiobj_release(&rec->hdr);
853 if (r != ERROR_SUCCESS)
854 goto done;
855 }
856
857 for (i = 0; i < num_records; i++)
858 {
859 r = construct_record(num_columns, types, records[i], path, &rec);
860 if (r != ERROR_SUCCESS)
861 goto done;
862
863 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
864 if (r != ERROR_SUCCESS)
865 {
866 msiobj_release(&rec->hdr);
867 goto done;
868 }
869
870 msiobj_release(&rec->hdr);
871 }
872
873 done:
874 msiobj_release(&view->hdr);
875 return r;
876 }
877
878 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
879 {
880 UINT r;
881 DWORD len, i;
882 DWORD num_labels, num_types;
883 DWORD num_columns, num_records = 0;
884 LPWSTR *columns, *types, *labels;
885 LPWSTR path, ptr, data;
886 LPWSTR **records = NULL;
887 LPWSTR **temp_records;
888
889 static const WCHAR suminfo[] =
890 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
891
892 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
893
894 if( folder == NULL || file == NULL )
895 return ERROR_INVALID_PARAMETER;
896
897 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
898 path = msi_alloc( len * sizeof(WCHAR) );
899 if (!path)
900 return ERROR_OUTOFMEMORY;
901
902 lstrcpyW( path, folder );
903 lstrcatW( path, szBackSlash );
904 lstrcatW( path, file );
905
906 data = msi_read_text_archive( path );
907
908 ptr = data;
909 msi_parse_line( &ptr, &columns, &num_columns );
910 msi_parse_line( &ptr, &types, &num_types );
911 msi_parse_line( &ptr, &labels, &num_labels );
912
913 if (num_columns != num_types)
914 {
915 r = ERROR_FUNCTION_FAILED;
916 goto done;
917 }
918
919 records = msi_alloc(sizeof(LPWSTR *));
920 if (!records)
921 {
922 r = ERROR_OUTOFMEMORY;
923 goto done;
924 }
925
926 /* read in the table records */
927 while (*ptr)
928 {
929 msi_parse_line( &ptr, &records[num_records], NULL );
930
931 num_records++;
932 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
933 if (!temp_records)
934 {
935 r = ERROR_OUTOFMEMORY;
936 goto done;
937 }
938 records = temp_records;
939 }
940
941 if (!strcmpW(labels[0], suminfo))
942 {
943 r = msi_add_suminfo( db, records, num_records, num_columns );
944 if (r != ERROR_SUCCESS)
945 {
946 r = ERROR_FUNCTION_FAILED;
947 goto done;
948 }
949 }
950 else
951 {
952 if (!TABLE_Exists(db, labels[0]))
953 {
954 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
955 if (r != ERROR_SUCCESS)
956 {
957 r = ERROR_FUNCTION_FAILED;
958 goto done;
959 }
960 }
961
962 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
963 }
964
965 done:
966 msi_free(path);
967 msi_free(data);
968 msi_free(columns);
969 msi_free(types);
970 msi_free(labels);
971
972 for (i = 0; i < num_records; i++)
973 msi_free(records[i]);
974
975 msi_free(records);
976
977 return r;
978 }
979
980 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
981 {
982 MSIDATABASE *db;
983 UINT r;
984
985 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
986
987 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
988 if( !db )
989 {
990 IWineMsiRemoteDatabase *remote_database;
991
992 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
993 if ( !remote_database )
994 return ERROR_INVALID_HANDLE;
995
996 IWineMsiRemoteDatabase_Release( remote_database );
997 WARN("MsiDatabaseImport not allowed during a custom action!\n");
998
999 return ERROR_SUCCESS;
1000 }
1001
1002 r = MSI_DatabaseImport( db, szFolder, szFilename );
1003 msiobj_release( &db->hdr );
1004 return r;
1005 }
1006
1007 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
1008 LPCSTR szFolder, LPCSTR szFilename )
1009 {
1010 LPWSTR path = NULL, file = NULL;
1011 UINT r = ERROR_OUTOFMEMORY;
1012
1013 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
1014
1015 if( szFolder )
1016 {
1017 path = strdupAtoW( szFolder );
1018 if( !path )
1019 goto end;
1020 }
1021
1022 if( szFilename )
1023 {
1024 file = strdupAtoW( szFilename );
1025 if( !file )
1026 goto end;
1027 }
1028
1029 r = MsiDatabaseImportW( handle, path, file );
1030
1031 end:
1032 msi_free( path );
1033 msi_free( file );
1034
1035 return r;
1036 }
1037
1038 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
1039 {
1040 UINT i, count, len, r = ERROR_SUCCESS;
1041 const char *sep;
1042 char *buffer;
1043 DWORD sz;
1044
1045 len = 0x100;
1046 buffer = msi_alloc( len );
1047 if ( !buffer )
1048 return ERROR_OUTOFMEMORY;
1049
1050 count = MSI_RecordGetFieldCount( row );
1051 for ( i=start; i<=count; i++ )
1052 {
1053 sz = len;
1054 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1055 if (r == ERROR_MORE_DATA)
1056 {
1057 char *p = msi_realloc( buffer, sz + 1 );
1058 if (!p)
1059 break;
1060 len = sz + 1;
1061 buffer = p;
1062 }
1063 sz = len;
1064 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1065 if (r != ERROR_SUCCESS)
1066 break;
1067
1068 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
1069 {
1070 r = ERROR_FUNCTION_FAILED;
1071 break;
1072 }
1073
1074 sep = (i < count) ? "\t" : "\r\n";
1075 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1076 {
1077 r = ERROR_FUNCTION_FAILED;
1078 break;
1079 }
1080 }
1081 msi_free( buffer );
1082 return r;
1083 }
1084
1085 static UINT msi_export_row( MSIRECORD *row, void *arg )
1086 {
1087 return msi_export_record( arg, row, 1 );
1088 }
1089
1090 static UINT msi_export_forcecodepage( HANDLE handle )
1091 {
1092 DWORD sz;
1093
1094 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
1095
1096 FIXME("Read the codepage from the strings table!\n");
1097
1098 sz = lstrlenA(data) + 1;
1099 if (!WriteFile(handle, data, sz, &sz, NULL))
1100 return ERROR_FUNCTION_FAILED;
1101
1102 return ERROR_SUCCESS;
1103 }
1104
1105 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
1106 LPCWSTR folder, LPCWSTR file )
1107 {
1108 static const WCHAR query[] = {
1109 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
1110 static const WCHAR forcecodepage[] = {
1111 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
1112 MSIRECORD *rec = NULL;
1113 MSIQUERY *view = NULL;
1114 LPWSTR filename;
1115 HANDLE handle;
1116 UINT len, r;
1117
1118 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1119 debugstr_w(folder), debugstr_w(file) );
1120
1121 if( folder == NULL || file == NULL )
1122 return ERROR_INVALID_PARAMETER;
1123
1124 len = lstrlenW(folder) + lstrlenW(file) + 2;
1125 filename = msi_alloc(len * sizeof (WCHAR));
1126 if (!filename)
1127 return ERROR_OUTOFMEMORY;
1128
1129 lstrcpyW( filename, folder );
1130 lstrcatW( filename, szBackSlash );
1131 lstrcatW( filename, file );
1132
1133 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1134 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1135 msi_free( filename );
1136 if (handle == INVALID_HANDLE_VALUE)
1137 return ERROR_FUNCTION_FAILED;
1138
1139 if (!lstrcmpW( table, forcecodepage ))
1140 {
1141 r = msi_export_forcecodepage( handle );
1142 goto done;
1143 }
1144
1145 r = MSI_OpenQuery( db, &view, query, table );
1146 if (r == ERROR_SUCCESS)
1147 {
1148 /* write out row 1, the column names */
1149 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1150 if (r == ERROR_SUCCESS)
1151 {
1152 msi_export_record( handle, rec, 1 );
1153 msiobj_release( &rec->hdr );
1154 }
1155
1156 /* write out row 2, the column types */
1157 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1158 if (r == ERROR_SUCCESS)
1159 {
1160 msi_export_record( handle, rec, 1 );
1161 msiobj_release( &rec->hdr );
1162 }
1163
1164 /* write out row 3, the table name + keys */
1165 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1166 if (r == ERROR_SUCCESS)
1167 {
1168 MSI_RecordSetStringW( rec, 0, table );
1169 msi_export_record( handle, rec, 0 );
1170 msiobj_release( &rec->hdr );
1171 }
1172
1173 /* write out row 4 onwards, the data */
1174 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1175 msiobj_release( &view->hdr );
1176 }
1177
1178 done:
1179 CloseHandle( handle );
1180 return r;
1181 }
1182
1183 /***********************************************************************
1184 * MsiExportDatabaseW [MSI.@]
1185 *
1186 * Writes a file containing the table data as tab separated ASCII.
1187 *
1188 * The format is as follows:
1189 *
1190 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1191 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1192 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1193 *
1194 * Followed by the data, starting at row 1 with one row per line
1195 *
1196 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1197 */
1198 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1199 LPCWSTR szFolder, LPCWSTR szFilename )
1200 {
1201 MSIDATABASE *db;
1202 UINT r;
1203
1204 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1205 debugstr_w(szFolder), debugstr_w(szFilename));
1206
1207 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1208 if( !db )
1209 {
1210 IWineMsiRemoteDatabase *remote_database;
1211
1212 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1213 if ( !remote_database )
1214 return ERROR_INVALID_HANDLE;
1215
1216 IWineMsiRemoteDatabase_Release( remote_database );
1217 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1218
1219 return ERROR_SUCCESS;
1220 }
1221
1222 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1223 msiobj_release( &db->hdr );
1224 return r;
1225 }
1226
1227 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1228 LPCSTR szFolder, LPCSTR szFilename )
1229 {
1230 LPWSTR path = NULL, file = NULL, table = NULL;
1231 UINT r = ERROR_OUTOFMEMORY;
1232
1233 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1234 debugstr_a(szFolder), debugstr_a(szFilename));
1235
1236 if( szTable )
1237 {
1238 table = strdupAtoW( szTable );
1239 if( !table )
1240 goto end;
1241 }
1242
1243 if( szFolder )
1244 {
1245 path = strdupAtoW( szFolder );
1246 if( !path )
1247 goto end;
1248 }
1249
1250 if( szFilename )
1251 {
1252 file = strdupAtoW( szFilename );
1253 if( !file )
1254 goto end;
1255 }
1256
1257 r = MsiDatabaseExportW( handle, table, path, file );
1258
1259 end:
1260 msi_free( table );
1261 msi_free( path );
1262 msi_free( file );
1263
1264 return r;
1265 }
1266
1267 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1268 LPCSTR szTableName)
1269 {
1270 UINT r;
1271 LPWSTR table;
1272
1273 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1274 debugstr_a(szTableName));
1275
1276 table = strdupAtoW(szTableName);
1277 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1278
1279 msi_free(table);
1280 return r;
1281 }
1282
1283 typedef struct _tagMERGETABLE
1284 {
1285 struct list entry;
1286 struct list rows;
1287 LPWSTR name;
1288 DWORD numconflicts;
1289 LPWSTR *columns;
1290 DWORD numcolumns;
1291 LPWSTR *types;
1292 DWORD numtypes;
1293 LPWSTR *labels;
1294 DWORD numlabels;
1295 } MERGETABLE;
1296
1297 typedef struct _tagMERGEROW
1298 {
1299 struct list entry;
1300 MSIRECORD *data;
1301 } MERGEROW;
1302
1303 typedef struct _tagMERGEDATA
1304 {
1305 MSIDATABASE *db;
1306 MSIDATABASE *merge;
1307 MERGETABLE *curtable;
1308 MSIQUERY *curview;
1309 struct list *tabledata;
1310 } MERGEDATA;
1311
1312 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1313 {
1314 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1315 ((type2[0] == 'l') || (type2[0] == 's')))
1316 return TRUE;
1317
1318 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1319 ((type2[0] == 'L') || (type2[0] == 'S')))
1320 return TRUE;
1321
1322 return !lstrcmpW(type1, type2);
1323 }
1324
1325 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1326 {
1327 MSIRECORD *dbrec, *mergerec;
1328 UINT r, i, count;
1329
1330 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1331 if (r != ERROR_SUCCESS)
1332 return r;
1333
1334 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1335 if (r != ERROR_SUCCESS)
1336 return r;
1337
1338 count = MSI_RecordGetFieldCount(dbrec);
1339 for (i = 1; i <= count; i++)
1340 {
1341 if (!MSI_RecordGetString(mergerec, i))
1342 break;
1343
1344 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1345 MSI_RecordGetString(mergerec, i)))
1346 {
1347 r = ERROR_DATATYPE_MISMATCH;
1348 goto done;
1349 }
1350 }
1351
1352 msiobj_release(&dbrec->hdr);
1353 msiobj_release(&mergerec->hdr);
1354 dbrec = mergerec = NULL;
1355
1356 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1357 if (r != ERROR_SUCCESS)
1358 return r;
1359
1360 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1361 if (r != ERROR_SUCCESS)
1362 return r;
1363
1364 count = MSI_RecordGetFieldCount(dbrec);
1365 for (i = 1; i <= count; i++)
1366 {
1367 if (!MSI_RecordGetString(mergerec, i))
1368 break;
1369
1370 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1371 MSI_RecordGetString(mergerec, i)))
1372 {
1373 r = ERROR_DATATYPE_MISMATCH;
1374 break;
1375 }
1376 }
1377
1378 done:
1379 msiobj_release(&dbrec->hdr);
1380 msiobj_release(&mergerec->hdr);
1381
1382 return r;
1383 }
1384
1385 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1386 LPCWSTR table)
1387 {
1388 MSIRECORD *dbrec, *mergerec = NULL;
1389 UINT r, i, count;
1390
1391 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1392 if (r != ERROR_SUCCESS)
1393 return r;
1394
1395 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1396 if (r != ERROR_SUCCESS)
1397 goto done;
1398
1399 count = MSI_RecordGetFieldCount(dbrec);
1400 if (count != MSI_RecordGetFieldCount(mergerec))
1401 {
1402 r = ERROR_DATATYPE_MISMATCH;
1403 goto done;
1404 }
1405
1406 for (i = 1; i <= count; i++)
1407 {
1408 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1409 MSI_RecordGetString(mergerec, i)))
1410 {
1411 r = ERROR_DATATYPE_MISMATCH;
1412 goto done;
1413 }
1414 }
1415
1416 done:
1417 msiobj_release(&dbrec->hdr);
1418 msiobj_release(&mergerec->hdr);
1419
1420 return r;
1421 }
1422
1423 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1424 {
1425 MSIRECORD *colnames;
1426 LPWSTR str, val;
1427 UINT r, i = 0, sz = 0;
1428 int cmp;
1429
1430 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1431 if (r != ERROR_SUCCESS)
1432 return NULL;
1433
1434 do
1435 {
1436 str = msi_dup_record_field(colnames, ++i);
1437 cmp = lstrcmpW(key, str);
1438 msi_free(str);
1439 } while (cmp);
1440
1441 msiobj_release(&colnames->hdr);
1442
1443 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1444 if (r != ERROR_SUCCESS)
1445 return NULL;
1446 sz++;
1447
1448 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1449 {
1450 /* quote string record fields */
1451 const WCHAR szQuote[] = {'\'', 0};
1452 sz += 2;
1453 val = msi_alloc(sz*sizeof(WCHAR));
1454 if (!val)
1455 return NULL;
1456
1457 lstrcpyW(val, szQuote);
1458 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1459 lstrcpyW(val+1+sz, szQuote);
1460 }
1461 else
1462 {
1463 /* do not quote integer record fields */
1464 val = msi_alloc(sz*sizeof(WCHAR));
1465 if (!val)
1466 return NULL;
1467
1468 r = MSI_RecordGetStringW(rec, i, val, &sz);
1469 }
1470
1471 if (r != ERROR_SUCCESS)
1472 {
1473 ERR("failed to get string!\n");
1474 msi_free(val);
1475 return NULL;
1476 }
1477
1478 return val;
1479 }
1480
1481 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1482 LPWSTR table, MSIRECORD *rec)
1483 {
1484 LPWSTR query = NULL, clause = NULL;
1485 LPWSTR ptr = NULL, val;
1486 LPCWSTR setptr;
1487 DWORD size = 1, oldsize;
1488 LPCWSTR key;
1489 MSIRECORD *keys;
1490 UINT r, i, count;
1491
1492 static const WCHAR keyset[] = {
1493 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1494 static const WCHAR lastkeyset[] = {
1495 '`','%','s','`',' ','=',' ','%','s',' ',0};
1496 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1497 'F','R','O','M',' ','`','%','s','`',' ',
1498 'W','H','E','R','E',' ','%','s',0};
1499
1500 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1501 if (r != ERROR_SUCCESS)
1502 return NULL;
1503
1504 clause = msi_alloc_zero(size * sizeof(WCHAR));
1505 if (!clause)
1506 goto done;
1507
1508 ptr = clause;
1509 count = MSI_RecordGetFieldCount(keys);
1510 for (i = 1; i <= count; i++)
1511 {
1512 key = MSI_RecordGetString(keys, i);
1513 val = get_key_value(view, key, rec);
1514
1515 if (i == count)
1516 setptr = lastkeyset;
1517 else
1518 setptr = keyset;
1519
1520 oldsize = size;
1521 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1522 clause = msi_realloc(clause, size * sizeof (WCHAR));
1523 if (!clause)
1524 {
1525 msi_free(val);
1526 goto done;
1527 }
1528
1529 ptr = clause + oldsize - 1;
1530 sprintfW(ptr, setptr, key, val);
1531 msi_free(val);
1532 }
1533
1534 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1535 query = msi_alloc(size * sizeof(WCHAR));
1536 if (!query)
1537 goto done;
1538
1539 sprintfW(query, fmt, table, clause);
1540
1541 done:
1542 msi_free(clause);
1543 msiobj_release(&keys->hdr);
1544 return query;
1545 }
1546
1547 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1548 {
1549 MERGEDATA *data = param;
1550 MERGETABLE *table = data->curtable;
1551 MERGEROW *mergerow;
1552 MSIQUERY *dbview = NULL;
1553 MSIRECORD *row = NULL;
1554 LPWSTR query = NULL;
1555 UINT r = ERROR_SUCCESS;
1556
1557 if (TABLE_Exists(data->db, table->name))
1558 {
1559 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1560 if (!query)
1561 return ERROR_OUTOFMEMORY;
1562
1563 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1564 if (r != ERROR_SUCCESS)
1565 goto done;
1566
1567 r = MSI_ViewExecute(dbview, NULL);
1568 if (r != ERROR_SUCCESS)
1569 goto done;
1570
1571 r = MSI_ViewFetch(dbview, &row);
1572 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1573 {
1574 table->numconflicts++;
1575 goto done;
1576 }
1577 else if (r != ERROR_NO_MORE_ITEMS)
1578 goto done;
1579
1580 r = ERROR_SUCCESS;
1581 }
1582
1583 mergerow = msi_alloc(sizeof(MERGEROW));
1584 if (!mergerow)
1585 {
1586 r = ERROR_OUTOFMEMORY;
1587 goto done;
1588 }
1589
1590 mergerow->data = MSI_CloneRecord(rec);
1591 if (!mergerow->data)
1592 {
1593 r = ERROR_OUTOFMEMORY;
1594 msi_free(mergerow);
1595 goto done;
1596 }
1597
1598 list_add_tail(&table->rows, &mergerow->entry);
1599
1600 done:
1601 msi_free(query);
1602 msiobj_release(&row->hdr);
1603 msiobj_release(&dbview->hdr);
1604 return r;
1605 }
1606
1607 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1608 {
1609 UINT r, i, count;
1610 MSIRECORD *prec = NULL;
1611
1612 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1613 if (r != ERROR_SUCCESS)
1614 return r;
1615
1616 count = MSI_RecordGetFieldCount(prec);
1617 *numlabels = count + 1;
1618 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1619 if (!*labels)
1620 {
1621 r = ERROR_OUTOFMEMORY;
1622 goto end;
1623 }
1624
1625 (*labels)[0] = strdupW(table);
1626 for (i=1; i<=count; i++ )
1627 {
1628 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1629 }
1630
1631 end:
1632 msiobj_release( &prec->hdr );
1633 return r;
1634 }
1635
1636 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1637 {
1638 UINT r, i, count;
1639 MSIRECORD *prec = NULL;
1640
1641 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1642 if (r != ERROR_SUCCESS)
1643 return r;
1644
1645 count = MSI_RecordGetFieldCount(prec);
1646 *columns = msi_alloc(count*sizeof(LPWSTR));
1647 if (!*columns)
1648 {
1649 r = ERROR_OUTOFMEMORY;
1650 goto end;
1651 }
1652
1653 for (i=1; i<=count; i++ )
1654 {
1655 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1656 }
1657
1658 *numcolumns = count;
1659
1660 end:
1661 msiobj_release( &prec->hdr );
1662 return r;
1663 }
1664
1665 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1666 {
1667 UINT r, i, count;
1668 MSIRECORD *prec = NULL;
1669
1670 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1671 if (r != ERROR_SUCCESS)
1672 return r;
1673
1674 count = MSI_RecordGetFieldCount(prec);
1675 *types = msi_alloc(count*sizeof(LPWSTR));
1676 if (!*types)
1677 {
1678 r = ERROR_OUTOFMEMORY;
1679 goto end;
1680 }
1681
1682 *numtypes = count;
1683 for (i=1; i<=count; i++ )
1684 {
1685 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1686 }
1687
1688 end:
1689 msiobj_release( &prec->hdr );
1690 return r;
1691 }
1692
1693 static void merge_free_rows(MERGETABLE *table)
1694 {
1695 struct list *item, *cursor;
1696
1697 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1698 {
1699 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1700
1701 list_remove(&row->entry);
1702 msiobj_release(&row->data->hdr);
1703 msi_free(row);
1704 }
1705 }
1706
1707 static void free_merge_table(MERGETABLE *table)
1708 {
1709 UINT i;
1710
1711 if (table->labels != NULL)
1712 {
1713 for (i = 0; i < table->numlabels; i++)
1714 msi_free(table->labels[i]);
1715
1716 msi_free(table->labels);
1717 }
1718
1719 if (table->columns != NULL)
1720 {
1721 for (i = 0; i < table->numcolumns; i++)
1722 msi_free(table->columns[i]);
1723
1724 msi_free(table->columns);
1725 }
1726
1727 if (table->types != NULL)
1728 {
1729 for (i = 0; i < table->numtypes; i++)
1730 msi_free(table->types[i]);
1731
1732 msi_free(table->types);
1733 }
1734
1735 msi_free(table->name);
1736 merge_free_rows(table);
1737
1738 msi_free(table);
1739 }
1740
1741 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1742 {
1743 UINT r;
1744 MERGETABLE *table;
1745 MSIQUERY *mergeview = NULL;
1746
1747 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1748 'F','R','O','M',' ','`','%','s','`',0};
1749
1750 table = msi_alloc_zero(sizeof(MERGETABLE));
1751 if (!table)
1752 {
1753 *ptable = NULL;
1754 return ERROR_OUTOFMEMORY;
1755 }
1756
1757 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1758 if (r != ERROR_SUCCESS)
1759 goto err;
1760
1761 r = MSI_OpenQuery(db, &mergeview, query, name);
1762 if (r != ERROR_SUCCESS)
1763 goto err;
1764
1765 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1766 if (r != ERROR_SUCCESS)
1767 goto err;
1768
1769 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1770 if (r != ERROR_SUCCESS)
1771 goto err;
1772
1773 list_init(&table->rows);
1774
1775 table->name = strdupW(name);
1776 table->numconflicts = 0;
1777
1778 msiobj_release(&mergeview->hdr);
1779 *ptable = table;
1780 return ERROR_SUCCESS;
1781
1782 err:
1783 msiobj_release(&mergeview->hdr);
1784 free_merge_table(table);
1785 *ptable = NULL;
1786 return r;
1787 }
1788
1789 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1790 {
1791 MERGEDATA *data = param;
1792 MERGETABLE *table;
1793 MSIQUERY *dbview = NULL;
1794 MSIQUERY *mergeview = NULL;
1795 LPCWSTR name;
1796 UINT r;
1797
1798 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1799 'F','R','O','M',' ','`','%','s','`',0};
1800
1801 name = MSI_RecordGetString(rec, 1);
1802
1803 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1804 if (r != ERROR_SUCCESS)
1805 goto done;
1806
1807 if (TABLE_Exists(data->db, name))
1808 {
1809 r = MSI_OpenQuery(data->db, &dbview, query, name);
1810 if (r != ERROR_SUCCESS)
1811 goto done;
1812
1813 r = merge_verify_colnames(dbview, mergeview);
1814 if (r != ERROR_SUCCESS)
1815 goto done;
1816
1817 r = merge_verify_primary_keys(data->db, data->merge, name);
1818 if (r != ERROR_SUCCESS)
1819 goto done;
1820 }
1821
1822 r = msi_get_merge_table(data->merge, name, &table);
1823 if (r != ERROR_SUCCESS)
1824 goto done;
1825
1826 data->curtable = table;
1827 data->curview = mergeview;
1828 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1829 if (r != ERROR_SUCCESS)
1830 {
1831 free_merge_table(table);
1832 goto done;
1833 }
1834
1835 list_add_tail(data->tabledata, &table->entry);
1836
1837 done:
1838 msiobj_release(&dbview->hdr);
1839 msiobj_release(&mergeview->hdr);
1840 return r;
1841 }
1842
1843 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1844 struct list *tabledata)
1845 {
1846 UINT r;
1847 MSIQUERY *view;
1848 MERGEDATA data;
1849
1850 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1851 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1852
1853 r = MSI_DatabaseOpenViewW(merge, query, &view);
1854 if (r != ERROR_SUCCESS)
1855 return r;
1856
1857 data.db = db;
1858 data.merge = merge;
1859 data.tabledata = tabledata;
1860 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1861
1862 msiobj_release(&view->hdr);
1863 return r;
1864 }
1865
1866 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1867 {
1868 UINT r;
1869 MERGEROW *row;
1870 MSIVIEW *tv;
1871
1872 if (!TABLE_Exists(db, table->name))
1873 {
1874 r = msi_add_table_to_db(db, table->columns, table->types,
1875 table->labels, table->numlabels, table->numcolumns);
1876 if (r != ERROR_SUCCESS)
1877 return ERROR_FUNCTION_FAILED;
1878 }
1879
1880 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1881 {
1882 r = TABLE_CreateView(db, table->name, &tv);
1883 if (r != ERROR_SUCCESS)
1884 return r;
1885
1886 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1887 tv->ops->delete(tv);
1888
1889 if (r != ERROR_SUCCESS)
1890 return r;
1891 }
1892
1893 return ERROR_SUCCESS;
1894 }
1895
1896 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1897 LPWSTR table, DWORD numconflicts)
1898 {
1899 UINT r;
1900 MSIQUERY *view;
1901
1902 static const WCHAR create[] = {
1903 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1904 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1905 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1906 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1907 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1908 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1909 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1910 static const WCHAR insert[] = {
1911 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1912 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1913 '`','N','u','m','R','o','w','M','e','r','g','e',
1914 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1915 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1916
1917 if (!TABLE_Exists(db, error))
1918 {
1919 r = MSI_OpenQuery(db, &view, create, error);
1920 if (r != ERROR_SUCCESS)
1921 return r;
1922
1923 r = MSI_ViewExecute(view, NULL);
1924 msiobj_release(&view->hdr);
1925 if (r != ERROR_SUCCESS)
1926 return r;
1927 }
1928
1929 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1930 if (r != ERROR_SUCCESS)
1931 return r;
1932
1933 r = MSI_ViewExecute(view, NULL);
1934 msiobj_release(&view->hdr);
1935 return r;
1936 }
1937
1938 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1939 LPCWSTR szTableName)
1940 {
1941 struct list tabledata = LIST_INIT(tabledata);
1942 struct list *item, *cursor;
1943 MSIDATABASE *db, *merge;
1944 MERGETABLE *table;
1945 BOOL conflicts;
1946 UINT r;
1947
1948 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1949 debugstr_w(szTableName));
1950
1951 if (szTableName && !*szTableName)
1952 return ERROR_INVALID_TABLE;
1953
1954 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1955 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1956 if (!db || !merge)
1957 {
1958 r = ERROR_INVALID_HANDLE;
1959 goto done;
1960 }
1961
1962 r = gather_merge_data(db, merge, &tabledata);
1963 if (r != ERROR_SUCCESS)
1964 goto done;
1965
1966 conflicts = FALSE;
1967 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1968 {
1969 if (table->numconflicts)
1970 {
1971 conflicts = TRUE;
1972
1973 r = update_merge_errors(db, szTableName, table->name,
1974 table->numconflicts);
1975 if (r != ERROR_SUCCESS)
1976 break;
1977 }
1978 else
1979 {
1980 r = merge_table(db, table);
1981 if (r != ERROR_SUCCESS)
1982 break;
1983 }
1984 }
1985
1986 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1987 {
1988 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1989 list_remove(&table->entry);
1990 free_merge_table(table);
1991 }
1992
1993 if (conflicts)
1994 r = ERROR_FUNCTION_FAILED;
1995
1996 done:
1997 msiobj_release(&db->hdr);
1998 msiobj_release(&merge->hdr);
1999 return r;
2000 }
2001
2002 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
2003 {
2004 MSIDBSTATE ret = MSIDBSTATE_READ;
2005 MSIDATABASE *db;
2006
2007 TRACE("%d\n", handle);
2008
2009 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
2010 if( !db )
2011 {
2012 IWineMsiRemoteDatabase *remote_database;
2013
2014 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
2015 if ( !remote_database )
2016 return MSIDBSTATE_ERROR;
2017
2018 IWineMsiRemoteDatabase_Release( remote_database );
2019 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
2020
2021 return MSIDBSTATE_READ;
2022 }
2023
2024 if (db->mode != MSIDBOPEN_READONLY )
2025 ret = MSIDBSTATE_WRITE;
2026 msiobj_release( &db->hdr );
2027
2028 return ret;
2029 }
2030
2031 typedef struct _msi_remote_database_impl {
2032 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
2033 MSIHANDLE database;
2034 LONG refs;
2035 } msi_remote_database_impl;
2036
2037 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
2038 {
2039 return (msi_remote_database_impl *)iface;
2040 }
2041
2042 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
2043 REFIID riid,LPVOID *ppobj)
2044 {
2045 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2046 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
2047 {
2048 IUnknown_AddRef( iface );
2049 *ppobj = iface;
2050 return S_OK;
2051 }
2052
2053 return E_NOINTERFACE;
2054 }
2055
2056 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
2057 {
2058 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2059
2060 return InterlockedIncrement( &This->refs );
2061 }
2062
2063 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
2064 {
2065 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2066 ULONG r;
2067
2068 r = InterlockedDecrement( &This->refs );
2069 if (r == 0)
2070 {
2071 MsiCloseHandle( This->database );
2072 msi_free( This );
2073 }
2074 return r;
2075 }
2076
2077 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
2078 LPCWSTR table, MSICONDITION *persistent )
2079 {
2080 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2081 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
2082 return S_OK;
2083 }
2084
2085 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
2086 LPCWSTR table, MSIHANDLE *keys )
2087 {
2088 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2089 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
2090 return HRESULT_FROM_WIN32(r);
2091 }
2092
2093 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
2094 UINT updatecount, MSIHANDLE *suminfo )
2095 {
2096 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2097 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
2098 return HRESULT_FROM_WIN32(r);
2099 }
2100
2101 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
2102 LPCWSTR query, MSIHANDLE *view )
2103 {
2104 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2105 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
2106 return HRESULT_FROM_WIN32(r);
2107 }
2108
2109 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
2110 {
2111 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2112 This->database = handle;
2113 return S_OK;
2114 }
2115
2116 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2117 {
2118 mrd_QueryInterface,
2119 mrd_AddRef,
2120 mrd_Release,
2121 mrd_IsTablePersistent,
2122 mrd_GetPrimaryKeys,
2123 mrd_GetSummaryInformation,
2124 mrd_OpenView,
2125 mrd_SetMsiHandle,
2126 };
2127
2128 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2129 {
2130 msi_remote_database_impl *This;
2131
2132 This = msi_alloc( sizeof *This );
2133 if (!This)
2134 return E_OUTOFMEMORY;
2135
2136 This->lpVtbl = &msi_remote_database_vtbl;
2137 This->database = 0;
2138 This->refs = 1;
2139
2140 *ppObj = This;
2141
2142 return S_OK;
2143 }