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